@xiboplayer/pwa 0.7.21 → 0.7.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/assets/__vite-browser-external-DeMPM02e.js +2 -0
  2. package/dist/assets/__vite-browser-external-DeMPM02e.js.map +1 -0
  3. package/dist/assets/chunk-DzMEjpoC.js +1 -0
  4. package/dist/assets/{html2canvas-BAfZNSwU.js → html2canvas-EikzC5d8.js} +2 -2
  5. package/dist/assets/{html2canvas-BAfZNSwU.js.map → html2canvas-EikzC5d8.js.map} +1 -1
  6. package/dist/assets/main-CRdq5ifQ.js +3 -0
  7. package/dist/assets/{main-vwJkNw4Y.js.map → main-CRdq5ifQ.js.map} +1 -1
  8. package/dist/assets/main-DTR2QDcF.js +108 -0
  9. package/dist/assets/main-DTR2QDcF.js.map +1 -0
  10. package/dist/assets/{pdf-Bxz9Nzto.js → pdf-CMz6puSt.js} +1 -1
  11. package/dist/assets/{pdf-Bxz9Nzto.js.map → pdf-CMz6puSt.js.map} +1 -1
  12. package/dist/assets/{setup-B4gZX38p.js → setup-Bw8T9Qq6.js} +2 -2
  13. package/dist/assets/{setup-B4gZX38p.js.map → setup-Bw8T9Qq6.js.map} +1 -1
  14. package/dist/assets/src-A5KHvitf.js +2 -0
  15. package/dist/assets/{src-CROvYSP8.js.map → src-A5KHvitf.js.map} +1 -1
  16. package/dist/assets/{src-DAB0dqGG.js → src-BHsN2u2P.js} +2 -2
  17. package/dist/assets/{src-DAB0dqGG.js.map → src-BHsN2u2P.js.map} +1 -1
  18. package/dist/assets/src-BLUMUwZR.js +1 -0
  19. package/dist/assets/src-BXXcWcHh.js +1 -0
  20. package/dist/assets/src-BxSOopk7.js +1 -0
  21. package/dist/assets/{src-WDu491CE.js → src-BxaX1gGg.js} +2 -2
  22. package/dist/assets/{src-WDu491CE.js.map → src-BxaX1gGg.js.map} +1 -1
  23. package/dist/assets/{src-BtVLiVYZ.js → src-CCAyzQUp.js} +3 -3
  24. package/dist/assets/{src-BtVLiVYZ.js.map → src-CCAyzQUp.js.map} +1 -1
  25. package/dist/assets/src-CWJcD3kA.js +1 -0
  26. package/dist/assets/{src-Cx3tXAAu.js → src-CZ1k5h23.js} +3 -3
  27. package/dist/assets/{src-Cx3tXAAu.js.map → src-CZ1k5h23.js.map} +1 -1
  28. package/dist/assets/src-ClrziKzV.js +16 -0
  29. package/dist/assets/src-ClrziKzV.js.map +1 -0
  30. package/dist/assets/{src-C_Lx4lXp.js → src-CtjjclS4.js} +2 -2
  31. package/dist/assets/{src-C_Lx4lXp.js.map → src-CtjjclS4.js.map} +1 -1
  32. package/dist/assets/src-CuVaZcMo.js +2 -0
  33. package/dist/assets/{src-B_BNICay.js.map → src-CuVaZcMo.js.map} +1 -1
  34. package/dist/assets/src-Cy5OUviT.js +1 -0
  35. package/dist/assets/src-DK5BYonP.js +630 -0
  36. package/dist/assets/src-DK5BYonP.js.map +1 -0
  37. package/dist/assets/src-Dk-W3N33.js +1 -0
  38. package/dist/assets/{src-cUopH0nN.js → src-xPTO7Ts6.js} +3 -3
  39. package/dist/assets/{src-cUopH0nN.js.map → src-xPTO7Ts6.js.map} +1 -1
  40. package/dist/assets/sync-manager-zf1tikPt.js +2 -0
  41. package/dist/assets/sync-manager-zf1tikPt.js.map +1 -0
  42. package/dist/index.html +1 -1
  43. package/dist/setup.html +3 -4
  44. package/dist/sw-pwa.js +2 -2
  45. package/dist/sw-pwa.js.map +1 -1
  46. package/package.json +15 -13
  47. package/dist/assets/chunk-7ZXdHUL4.js +0 -1
  48. package/dist/assets/main-oacre7st.js +0 -108
  49. package/dist/assets/main-oacre7st.js.map +0 -1
  50. package/dist/assets/main-vwJkNw4Y.js +0 -3
  51. package/dist/assets/src-B_BNICay.js +0 -2
  52. package/dist/assets/src-Bjt9ooXK.js +0 -16
  53. package/dist/assets/src-Bjt9ooXK.js.map +0 -1
  54. package/dist/assets/src-CKpVxGpH.js +0 -629
  55. package/dist/assets/src-CKpVxGpH.js.map +0 -1
  56. package/dist/assets/src-CROvYSP8.js +0 -2
  57. package/dist/assets/sync-manager-8Z-qwkod.js +0 -2
  58. package/dist/assets/sync-manager-8Z-qwkod.js.map +0 -1
@@ -0,0 +1,16 @@
1
+ import{o as e,t,v as n}from"./src-CCAyzQUp.js";var r={name:`@xiboplayer/xmds`,version:`0.7.23`,description:`XMDS SOAP client for Xibo CMS communication`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./xmds-client":`./src/xmds-client.js`,"./rest-client":`./src/rest-client.js`,"./schedule-parser":`./src/schedule-parser.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`},devDependencies:{vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`xmds`,`soap`,`cms`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/xmds`},homepage:`https://xiboplayer.org`};async function i(e){if(typeof navigator<`u`&&navigator.storage?.estimate)try{let t=await navigator.storage.estimate();e.availableSpace=t.quota-t.usage,e.totalSpace=t.quota}catch{}!e.timeZone&&typeof Intl<`u`&&(e.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),e.statusDialog||=`Current Layout: ${e.currentLayoutId||`None`}`}var a=n(`REST`),o=class{constructor(e){this.config=e,this.schemaVersion=7,this.retryOptions=e.retryOptions||{maxRetries:2,baseDelayMs:2e3},this._token=null,this._tokenExpiresAt=0,this._displayId=null,this._etags=new Map,this._responseCache=new Map,this._maxCacheSize=100,a.info(`Using REST transport`)}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${t}`:(this.config.restApiUrl||`${this.config.cmsUrl}${t}`).replace(/\/+$/,``)}_isProxyMode(){return typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)}_cacheSet(e,t,n){if(this._etags.size>=this._maxCacheSize){let e=this._etags.keys().next().value;this._etags.delete(e),this._responseCache.delete(e)}this._etags.set(e,t),this._responseCache.set(e,n)}async _authenticate(){let t=`${this.getRestBaseUrl()}/auth`;a.debug(`Authenticating...`);let n=await e(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})},this.retryOptions);if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Auth failed: ${n.status} ${n.statusText} ${e}`)}let r=await n.json();this._token=r.token,this._displayId=r.displayId,this._tokenExpiresAt=Date.now()+(r.expiresIn-60)*1e3,a.info(`Authenticated as display ${this._displayId}`)}getToken(){return this._token}async _getToken(){return(!this._token||Date.now()>=this._tokenExpiresAt)&&await this._authenticate(),this._token}async restGet(t,n={},r=!1){let i=await this._getToken(),o=new URL(`${this.getRestBaseUrl()}${t}`);for(let[e,t]of Object.entries(n))o.searchParams.set(e,String(t));let s=t,c={Authorization:`Bearer ${i}`},l=this._etags.get(s);l&&(c[`If-None-Match`]=l),a.debug(`GET ${t}`,n);let u=await e(o.toString(),{method:`GET`,headers:c},this.retryOptions);if(u.status===401){if(r)throw Error(`REST GET ${t} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restGet(t,n,!0)}if(u.status===304){let e=this._responseCache.get(s);if(e)return a.debug(`${t} → 304 (using cache)`),e}if(!u.ok){let e=await u.text().catch(()=>``);throw Error(`REST GET ${t} failed: ${u.status} ${u.statusText} ${e}`)}let d=u.headers.get(`Content-Type`)||``,f;f=d.includes(`application/json`)?await u.json():await u.text();let p=u.headers.get(`ETag`);return p&&this._cacheSet(s,p,f),f}async restSend(t,n,r={},i=!1){let o=await this._getToken(),s=new URL(`${this.getRestBaseUrl()}${n}`);a.debug(`${t} ${n}`);let c=await e(s.toString(),{method:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${o}`},body:JSON.stringify(r)},this.retryOptions);if(c.status===401){if(i)throw Error(`REST ${t} ${n} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restSend(t,n,r,!0)}if(!c.ok){let e=await c.text().catch(()=>``);throw Error(`REST ${t} ${n} failed: ${c.status} ${c.statusText} ${e}`)}return(c.headers.get(`Content-Type`)||``).includes(`application/json`)?await c.json():await c.text()}async registerDisplay(){await this._getToken();let e=typeof navigator<`u`?`${navigator.platform} ${navigator.userAgent}`:`unknown`,t=await this.restSend(`POST`,`/displays`,{displayName:this.config.displayName,clientType:this.config.clientType||`linux`,clientVersion:this.config.clientVersion||`0.1.0`,clientCode:this.config.clientCode||400,operatingSystem:e,macAddress:this.config.macAddress||`n/a`,xmrChannel:this.config.xmrChannel||``,xmrPubKey:this.config.xmrPubKey||``});return this._parseRegisterDisplayJson(t)}_parseRegisterDisplayJson(e){let t=e.display||e,n=t[`@attributes`]||{},r=n.code||t.code,i=n.message||t.message||``;if(r!==`READY`)return{code:r,message:i,settings:null};let a={},o=[],s=[];for(let[e,n]of Object.entries(t))if(!(e===`@attributes`||e===`file`)){if(e===`commands`){Array.isArray(n)&&(s=n.map(e=>({commandCode:e.code||e.commandCode||``,commandString:e.commandString||``})));continue}if(e===`tags`){let e=e=>typeof e==`object`?e.tag||e.value||``:String(e);if(Array.isArray(n))o=n.map(e).filter(Boolean);else if(n&&typeof n==`object`){let t=e(n);t&&(o=[t])}else typeof n==`string`&&n&&(o=[n]);continue}a[e]=typeof n==`object`?JSON.stringify(n):String(n)}let c=n.checkRf||``,l=n.checkSchedule||``,u={date:n.date||t.date||null,timezone:n.timezone||t.timezone||null,status:n.status||t.status||null,localDate:n.localDate||t.localDate||null,version_instructions:n.version_instructions||t.version_instructions||null},d=t.syncConfig||(t.syncGroup?{syncGroup:String(t.syncGroup),syncPublisherPort:parseInt(t.syncPublisherPort||`9590`,10),syncSwitchDelay:parseInt(t.syncSwitchDelay||`750`,10),syncVideoPauseDelay:parseInt(t.syncVideoPauseDelay||`100`,10),isLead:String(t.syncGroup)===`lead`}:null);return{code:r,message:i,settings:a,tags:o,commands:s,displayAttrs:u,checkRf:c,checkSchedule:l,syncConfig:d}}async requiredFiles(){let e=await this.restGet(`/displays/${this._displayId}/media`);return this._parseRequiredFilesV2(e)}_parseRequiredFilesV2(e){let t=[];for(let n of e.media||[])t.push({type:n.type||`media`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:n.saveAs||null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(let n of e.layouts||[])t.push({type:`layout`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(let n of e.widgets||[])t.push({type:`dataset`,id:n.id==null?null:String(n.id),size:0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null,updateInterval:n.updateInterval||0});for(let n of e.dependencies||[])t.push({type:`static`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:n.type||null,code:null,layoutid:null,regionid:null,mediaid:null});return{files:t,purge:[]}}async schedule(){return this.restGet(`/displays/${this._displayId}/schedule`)}async getResource(e,t,n){return this.restGet(`/widgets/${e}/${t}/${n}`)}async notifyStatus(e){return await i(e),this.restSend(`PUT`,`/displays/${this._displayId}/status`,{statusData:e})}async mediaInventory(e){let t=Array.isArray(e)?{inventoryItems:e}:{inventory:e};return this.restSend(`PUT`,`/displays/${this._displayId}/inventory`,t)}async blackList(e,t,n){return a.warn(`BlackList not available in v2 API (${t}/${e}: ${n})`),!1}async submitLog(e,t=null){let n=Array.isArray(e)?{logs:e}:{logXml:e};return(await this.restSend(`POST`,`/displays/${this._displayId}/logs`,n))?.success===!0}async submitScreenShot(e){return(await this.restSend(`POST`,`/displays/${this._displayId}/screenshot`,{screenshot:e}))?.success===!0}async submitStats(e,t=null){try{let t=Array.isArray(e)?{stats:e}:{statXml:e},n=(await this.restSend(`POST`,`/displays/${this._displayId}/stats`,t))?.success===!0;return a.info(`SubmitStats result: ${n}`),n}catch(e){throw a.error(`SubmitStats failed:`,e),e}}async reportFaults(e){return(await this.restSend(`POST`,`/displays/${this._displayId}/faults`,{fault:e}))?.success===!0}async getWeather(){return this.restGet(`/displays/${this._displayId}/weather`)}static async isAvailable(n,r){try{let i=`${typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)?``:n.replace(/\/+$/,``)}${t}/health`,a=r?.timeoutMs||8e3,o={method:`GET`};typeof AbortSignal<`u`&&AbortSignal.timeout&&(o.signal=AbortSignal.timeout(a));let s=await e(i,o,r||{maxRetries:0});if(!s.ok)return!1;let c=await s.json();return c.version===2&&c.status===`ok`}catch{return!1}}};function s(e){let t=[];for(let n of e.children)n.tagName===`criteria`&&t.push({metric:n.getAttribute(`metric`)||``,condition:n.getAttribute(`condition`)||``,type:n.getAttribute(`type`)||`string`,value:n.textContent||``});return t}function c(e){let t=[];for(let n of e.children)if(n.tagName===`tags`)for(let e of n.children){if(e.tagName!==`tag`)continue;let n=(e.textContent||``).trim();n&&t.push(n)}return t}function l(e){let t=new DOMParser().parseFromString(e,`text/xml`),n={default:null,defaultDependants:[],dependants:[],layouts:[],campaigns:[],overlays:[],actions:[],commands:[],dataConnectors:[]},r=t.querySelector(`schedule`);if(r){let e=Array.from(r.children).filter(e=>e.tagName===`dependants`);for(let t of e)if(t.parentElement===r)for(let e of t.querySelectorAll(`file`))e.textContent&&n.dependants.push(e.textContent)}let i=t.querySelector(`default`);if(i){n.default=i.getAttribute(`file`);let e=i.querySelectorAll(`dependants > file`);e.length>0&&(n.defaultDependants=[...e].map(e=>e.textContent))}for(let e of t.querySelectorAll(`campaign`)){let t={id:e.getAttribute(`id`),priority:parseInt(e.getAttribute(`priority`)||`0`),fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),scheduleid:e.getAttribute(`scheduleid`),maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),shareOfVoice:parseInt(e.getAttribute(`shareOfVoice`)||`0`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,criteria:s(e),layouts:[]};for(let n of e.querySelectorAll(`layout`)){let e=n.getAttribute(`file`),r=n.querySelectorAll(`dependants > file`);t.layouts.push({id:String(e),file:e,fromdt:n.getAttribute(`fromdt`)||t.fromdt,todt:n.getAttribute(`todt`)||t.todt,scheduleid:t.scheduleid,priority:t.priority,campaignId:t.id,maxPlaysPerHour:parseInt(n.getAttribute(`maxPlaysPerHour`)||`0`),isGeoAware:n.getAttribute(`isGeoAware`)===`1`,geoLocation:n.getAttribute(`geoLocation`)||``,syncEvent:n.getAttribute(`syncEvent`)===`1`,shareOfVoice:parseInt(n.getAttribute(`shareOfVoice`)||`0`),duration:parseInt(n.getAttribute(`duration`)||`0`),cyclePlayback:n.getAttribute(`cyclePlayback`)===`1`,groupKey:n.getAttribute(`groupKey`)||null,playCount:parseInt(n.getAttribute(`playCount`)||`0`),dependants:r.length>0?[...r].map(e=>e.textContent):[],criteria:s(n),tags:c(n)})}n.campaigns.push(t)}for(let e of t.querySelectorAll(`schedule > layout`)){let t=e.getAttribute(`file`),r=e.querySelectorAll(`dependants > file`);n.layouts.push({id:String(t),file:t,fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),scheduleid:e.getAttribute(`scheduleid`),priority:parseInt(e.getAttribute(`priority`)||`0`),campaignId:null,maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,shareOfVoice:parseInt(e.getAttribute(`shareOfVoice`)||`0`),duration:parseInt(e.getAttribute(`duration`)||`0`),cyclePlayback:e.getAttribute(`cyclePlayback`)===`1`,groupKey:e.getAttribute(`groupKey`)||null,playCount:parseInt(e.getAttribute(`playCount`)||`0`),recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,dependants:r.length>0?[...r].map(e=>e.textContent):[],criteria:s(e),tags:c(e)})}let a=t.querySelector(`overlays`);if(a)for(let e of a.querySelectorAll(`overlay`)){let t=e.getAttribute(`file`);n.overlays.push({id:String(t),duration:parseInt(e.getAttribute(`duration`)||`60`),file:t,fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),priority:parseInt(e.getAttribute(`priority`)||`0`),scheduleid:e.getAttribute(`scheduleid`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,criteria:s(e)})}let o=t.querySelector(`actions`);if(o)for(let e of o.querySelectorAll(`action`))n.actions.push({actionType:e.getAttribute(`actionType`)||``,triggerCode:e.getAttribute(`triggerCode`)||``,layoutCode:e.getAttribute(`layoutCode`)||``,commandCode:e.getAttribute(`commandCode`)||``,duration:parseInt(e.getAttribute(`duration`)||`0`),fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),priority:parseInt(e.getAttribute(`priority`)||`0`),scheduleid:e.getAttribute(`scheduleid`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``});for(let e of t.querySelectorAll(`schedule > command`))n.commands.push({code:e.getAttribute(`code`)||``,date:e.getAttribute(`date`)||``});let l=t.querySelector(`dataConnectors`);if(l)for(let e of l.querySelectorAll(`connector`))n.dataConnectors.push({id:e.getAttribute(`id`)||``,dataConnectorId:e.getAttribute(`dataConnectorId`)||``,dataSetId:e.getAttribute(`dataSetId`)||``,dataKey:e.getAttribute(`dataKey`)||``,dataParams:e.getAttribute(`dataParams`)||``,js:e.getAttribute(`js`)||``,url:e.getAttribute(`url`)||``,updateInterval:parseInt(e.getAttribute(`updateInterval`)||`300`,10)});return n}var u=n(`XMDS`),d=class{constructor(e){this.config=e,this.schemaVersion=5,this.retryOptions=e.retryOptions||{maxRetries:2,baseDelayMs:2e3}}buildEnvelope(e,t){return`<?xml version="1.0" encoding="UTF-8"?>
2
+ <soap:Envelope
3
+ xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
4
+ xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
5
+ xmlns:tns="urn:xmds"
6
+ xmlns:types="urn:xmds/encodedTypes"
7
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
8
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema">
9
+ <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
10
+ <tns:${e}>
11
+ ${Object.entries(t).map(([e,t])=>`<${e} xsi:type="xsd:string">${String(t).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}</${e}>`).join(`
12
+ `)}
13
+ </tns:${e}>
14
+ </soap:Body>
15
+ </soap:Envelope>`}rewriteXmdsUrl(e){return typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)?`/xmds-proxy?cms=${encodeURIComponent(e)}`:`${e}/xmds.php`}async call(t,n={}){let r=this.rewriteXmdsUrl(this.config.cmsUrl),i=`${r}${r.includes(`?`)?`&`:`?`}v=${this.schemaVersion}&method=${t}`,a=this.buildEnvelope(t,n);u.debug(`${t}`,n),u.debug(`URL: ${i}`);let o=await e(i,{method:`POST`,headers:{"Content-Type":`text/xml; charset=utf-8`},body:a},this.retryOptions);if(!o.ok)throw Error(`XMDS ${t} failed: ${o.status} ${o.statusText}`);let s=await o.text();return this.parseResponse(s,t)}parseResponse(e,t){let n=new DOMParser().parseFromString(e,`text/xml`),r=n.querySelector(`Fault`);if(r||=Array.from(n.querySelectorAll(`*`)).find(e=>e.localName===`Fault`||e.tagName.endsWith(`:Fault`)),r){let e=r.querySelector(`faultstring`)?.textContent||Array.from(r.querySelectorAll(`*`)).find(e=>e.localName===`faultstring`)?.textContent||`Unknown SOAP fault`;throw Error(`SOAP Fault: ${e}`)}let i=`${t}Response`,a=n.querySelector(i);if(a||=Array.from(n.querySelectorAll(`*`)).find(e=>e.localName===i||e.tagName.endsWith(`:`+i)),!a)throw Error(`No ${i} element in SOAP response`);let o=a.firstElementChild;return o?o.textContent:null}async registerDisplay(){let e=`${navigator.platform} ${navigator.userAgent}`,t=await this.call(`RegisterDisplay`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,displayName:this.config.displayName,clientType:this.config.clientType||`linux`,clientVersion:this.config.clientVersion||`0.1.0`,clientCode:this.config.clientCode||`400`,operatingSystem:e,macAddress:this.config.macAddress||`n/a`,xmrChannel:this.config.xmrChannel||``,xmrPubKey:this.config.xmrPubKey||``,licenceResult:`licensed`});return this.parseRegisterDisplayResponse(t)}parseRegisterDisplayResponse(e){let t=new DOMParser().parseFromString(e,`text/xml`).querySelector(`display`);if(!t)throw Error(`Invalid RegisterDisplay response: no <display> element`);let n=t.getAttribute(`code`),r=t.getAttribute(`message`);if(n!==`READY`)return{code:n,message:r,settings:null};let i={},a=[],o=[];for(let e of t.children){let t=e.tagName.toLowerCase();if(t!==`file`){if(t===`commands`){for(let t of e.querySelectorAll(`command`))o.push({commandCode:t.getAttribute(`code`)||t.getAttribute(`commandCode`)||``,commandString:t.getAttribute(`commandString`)||``});continue}if(t===`tags`){for(let t of e.querySelectorAll(`tag`))t.textContent&&a.push(t.textContent);continue}i[e.tagName]=e.textContent}}let s=t.getAttribute(`checkRf`)||``,c=t.getAttribute(`checkSchedule`)||``,l={date:t.getAttribute(`date`)||null,timezone:t.getAttribute(`timezone`)||null,status:t.getAttribute(`status`)||null,localDate:t.getAttribute(`localDate`)||null,version_instructions:t.getAttribute(`version_instructions`)||null},u=i.syncGroup||null;return{code:n,message:r,settings:i,tags:a,commands:o,displayAttrs:l,checkRf:s,checkSchedule:c,syncConfig:u?{syncGroup:u,syncPublisherPort:parseInt(i.syncPublisherPort||`9590`,10),syncSwitchDelay:parseInt(i.syncSwitchDelay||`750`,10),syncVideoPauseDelay:parseInt(i.syncVideoPauseDelay||`100`,10),isLead:u===`lead`}:null}}async requiredFiles(){let e=await this.call(`RequiredFiles`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return this.parseRequiredFilesResponse(e)}parseRequiredFilesResponse(e){let n=new DOMParser().parseFromString(e,`text/xml`),r=[];for(let e of n.querySelectorAll(`file`)){let n={type:e.getAttribute(`type`),id:e.getAttribute(`id`),size:parseInt(e.getAttribute(`size`)||`0`),md5:e.getAttribute(`md5`),download:e.getAttribute(`download`),path:e.getAttribute(`path`),saveAs:e.getAttribute(`saveAs`)||null,fileType:e.getAttribute(`fileType`)||null,code:e.getAttribute(`code`),layoutid:e.getAttribute(`layoutid`),regionid:e.getAttribute(`regionid`),mediaid:e.getAttribute(`mediaid`)};if(n.path&&n.path.includes(`xmds.php`)){n.cmsDownloadUrl=n.path;let e=n.fileType;e===`L`||n.type===`layout`?n.path=`${t}/layouts/${n.id}`:e===`P`?n.path=`${t}/dependencies/${n.saveAs||n.id}`:n.path=`${t}/media/file/${n.saveAs||n.id}`}r.push(n)}let i=[],a=n.querySelector(`purge`);if(a)for(let e of a.querySelectorAll(`item`))i.push({id:e.getAttribute(`id`),storedAs:e.getAttribute(`storedAs`)});return{files:r,purge:i}}async schedule(){return l(await this.call(`Schedule`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey}))}async getResource(e,t,n){return await this.call(`GetResource`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,layoutId:String(e),regionId:String(t),mediaId:String(n)})}async notifyStatus(e){return await i(e),await this.call(`NotifyStatus`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,status:JSON.stringify(e)})}async mediaInventory(e){return await this.call(`MediaInventory`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaInventory:e})}async blackList(e,t,n){try{let r=await this.call(`BlackList`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaId:String(e),type:t||`media`,reason:n||`Failed to render`});return u.info(`BlackListed ${t}/${e}: ${n}`),r===`true`}catch(e){return u.warn(`BlackList failed:`,e),!1}}async submitLog(e,t=null){return await this.call(`SubmitLog`,{serverKey:this.config.cmsKey,hardwareKey:t||this.config.hardwareKey,logXml:e})===`true`}async submitScreenShot(e){return await this.call(`SubmitScreenShot`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,screenShot:e})===`true`}async reportFaults(e){return this.call(`ReportFaults`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,fault:e})}async getWeather(){return this.call(`GetWeather`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})}async submitStats(e,t=null){try{let n=await this.call(`SubmitStats`,{serverKey:this.config.cmsKey,hardwareKey:t||this.config.hardwareKey,statXml:e})===`true`;return u.info(`SubmitStats result: ${n}`),n}catch(e){throw u.error(`SubmitStats failed:`,e),e}}},f=[`registerDisplay`,`requiredFiles`,`schedule`,`getResource`,`notifyStatus`,`mediaInventory`,`blackList`,`submitLog`,`submitScreenShot`,`submitStats`,`reportFaults`,`getWeather`];function p(e,t=`client`){for(let n of f)if(typeof e[n]!=`function`)throw Error(`${t} missing CmsClient method: ${n}()`)}var m=n(`Protocol`),h=1e4,g=5e3,_=5e3,v=12e4,y=2,b=class{constructor(e,t,n,r={}){this.cmsUrl=e,this.RestClient=t,this.XmdsClient=n;let i=r.probeTimeoutMs;this.firstProbeTimeoutMs=r.firstProbeTimeoutMs??i??h,this.reprobeTimeoutMs=r.reprobeTimeoutMs??i??g,this.reprobeMinDelayMs=r.reprobeMinDelayMs??_,this.reprobeMaxDelayMs=r.reprobeMaxDelayMs??v,this.protocol=null,this.lastProbeTime=0,this._reprobeTimer=null,this._reprobeDelay=this.reprobeMinDelayMs}async probe(e={}){let t=e.first?this.firstProbeTimeoutMs:this.reprobeTimeoutMs,n=await this.RestClient.isAvailable(this.cmsUrl,{maxRetries:0,timeoutMs:t});return this.lastProbeTime=Date.now(),n}async detect(e,t){if(t===`rest`){this.protocol=`rest`,m.info(`Using REST transport (forced)`);let t=new this.RestClient(e);return p(t,`RestClient`),{client:t,protocol:`rest`}}if(t===`xmds`){this.protocol=`xmds`,m.info(`Using XMDS/SOAP transport (forced)`);let t=new this.XmdsClient(e);return p(t,`XmdsClient`),{client:t,protocol:`xmds`}}m.info(`Probing CMS for REST API availability (timeout ${this.firstProbeTimeoutMs}ms)...`);let n=!1;try{n=await this.probe({first:!0})}catch(e){m.warn(`REST probe failed:`,e?.message||e)}if(n){this.protocol=`rest`,m.info(`REST transport detected — using PlayerRestApi`);let t=new this.RestClient(e);return p(t,`RestClient`),{client:t,protocol:`rest`}}this.protocol=`xmds`,m.warn(`REST unavailable — falling back to XMDS/SOAP transport`);let r=new this.XmdsClient(e);return p(r,`XmdsClient`),{client:r,protocol:`xmds`}}async reprobe(e){let t=this.protocol,n=!1;try{n=await this.probe({first:!1})}catch(e){m.warn(`Re-probe failed:`,e?.message||e)}let r=n?`rest`:`xmds`;if(r!==t){m.info(`Protocol changed: ${t} → ${r}`),this.protocol=r;let i=n?new this.RestClient(e):new this.XmdsClient(e);return p(i,n?`RestClient`:`XmdsClient`),{client:i,protocol:r,changed:!0}}return{client:null,protocol:r,changed:!1}}startAutoReprobe(e,t){if(this.protocol!==`xmds`)return;this.stopAutoReprobe(),this._reprobeDelay=this.reprobeMinDelayMs;let n=()=>{let r=this._reprobeDelay;this._reprobeTimer=setTimeout(async()=>{this._reprobeTimer=null;let r;try{r=await this.reprobe(e)}catch(e){m.warn(`Auto-reprobe error:`,e?.message||e),r={changed:!1,protocol:`xmds`,client:null}}if(r.changed&&r.protocol===`rest`){m.info(`REST recovered — promoting back from XMDS fallback`),this._reprobeDelay=this.reprobeMinDelayMs;try{t(r.client)}catch(e){m.warn(`onRestPromoted callback threw:`,e?.message||e)}return}let i=Math.min(this._reprobeDelay*y,this.reprobeMaxDelayMs);m.warn(`Still on XMDS fallback — REST probe failed, next attempt in ${Math.round(i/1e3)}s`),this._reprobeDelay=i,n()},r)};m.info(`Auto-reprobe scheduled — first attempt in ${Math.round(this._reprobeDelay/1e3)}s (backoff up to ${Math.round(this.reprobeMaxDelayMs/1e3)}s)`),n()}stopAutoReprobe(){this._reprobeTimer&&=(clearTimeout(this._reprobeTimer),null),this._reprobeDelay=this.reprobeMinDelayMs}getProtocol(){return this.protocol}},x=r.version;export{d as a,p as i,b as n,l as o,f as r,o as s,x as t};
16
+ //# sourceMappingURL=src-ClrziKzV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-ClrziKzV.js","names":["log","log","pkg"],"sources":["../../../xmds/package.json","../../../xmds/src/status-enrichment.js","../../../xmds/src/rest-client.js","../../../xmds/src/schedule-parser.js","../../../xmds/src/xmds-client.js","../../../xmds/src/cms-client.js","../../../xmds/src/protocol-detector.js","../../../xmds/src/index.js"],"sourcesContent":["{\n \"name\": \"@xiboplayer/xmds\",\n \"version\": \"0.7.23\",\n \"description\": \"XMDS SOAP client for Xibo CMS communication\",\n \"type\": \"module\",\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./xmds-client\": \"./src/xmds-client.js\",\n \"./rest-client\": \"./src/rest-client.js\",\n \"./schedule-parser\": \"./src/schedule-parser.js\"\n },\n \"scripts\": {\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@xiboplayer/utils\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"vitest\": \"^4.1.2\"\n },\n \"keywords\": [\n \"xibo\",\n \"digital-signage\",\n \"xmds\",\n \"soap\",\n \"cms\"\n ],\n \"author\": \"Pau Aliagas <linuxnow@gmail.com>\",\n \"license\": \"AGPL-3.0-or-later\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/xibo-players/xiboplayer.git\",\n \"directory\": \"packages/xmds\"\n },\n \"homepage\": \"https://xiboplayer.org\"\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Shared notifyStatus enrichment — adds storage estimate, timezone,\n * and statusDialog to the status object before submission.\n *\n * @param {Object} status - Mutable status object to enrich in place\n * @returns {Promise<void>}\n */\nexport async function enrichStatus(status) {\n // Add storage estimate if available\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n // Add timezone if not already provided\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n // Add statusDialog (summary for CMS display status page) if not provided\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * REST transport client for Xibo CMS Player API.\n *\n * Uses the Player API REST endpoints with JWT auth, resource-oriented URLs,\n * and native JSON responses (no XML parsing required).\n *\n * - JWT bearer token auth (single POST /auth → token for all requests)\n * - Resource-oriented URLs (/displays/{id}/schedule vs /schedule)\n * - Native JSON schedule (no client-side XML parsing)\n * - Categorized required files (media/layouts/widgets)\n * - CDN/reverse proxy compatible (GET with cache headers)\n *\n * Same public API as XmdsClient — drop-in replacement.\n */\nimport { createLogger, fetchWithRetry, PLAYER_API } from '@xiboplayer/utils';\nimport { enrichStatus } from './status-enrichment.js';\n\nconst log = createLogger('REST');\n\nexport class RestClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 7;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n\n // JWT auth state\n this._token = null;\n this._tokenExpiresAt = 0;\n this._displayId = null;\n\n // ETag-based HTTP caching (capped at _maxCacheSize entries)\n this._etags = new Map();\n this._responseCache = new Map();\n this._maxCacheSize = 100;\n\n log.info('Using REST transport');\n }\n\n // ─── Transport helpers ──────────────────────────────────────────\n\n /**\n * Get the REST API base URL.\n * In proxy mode (Electron/Chromium), returns the local relative path so\n * requests go through the Express proxy's mirror routes.\n * In direct mode (standalone PWA), returns the full CMS URL.\n */\n getRestBaseUrl() {\n if (this._isProxyMode()) {\n return `${window.location.origin}${PLAYER_API}`;\n }\n const base = this.config.restApiUrl || `${this.config.cmsUrl}${PLAYER_API}`;\n return base.replace(/\\/+$/, '');\n }\n\n /**\n * Check if running behind the local proxy (Electron or Chromium kiosk).\n */\n _isProxyMode() {\n return typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost');\n }\n\n /**\n * Store a response in the ETag cache, evicting the oldest entry if full.\n */\n _cacheSet(path, etag, data) {\n if (this._etags.size >= this._maxCacheSize) {\n const oldest = this._etags.keys().next().value;\n this._etags.delete(oldest);\n this._responseCache.delete(oldest);\n }\n this._etags.set(path, etag);\n this._responseCache.set(path, data);\n }\n\n // ─── JWT auth ─────────────────────────────────────────────────\n\n /**\n * Authenticate with the CMS and obtain a JWT token.\n * Called automatically before the first authenticated request.\n */\n async _authenticate() {\n const url = `${this.getRestBaseUrl()}/auth`;\n\n log.debug('Authenticating...');\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n }),\n }, this.retryOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`Auth failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const data = await response.json();\n this._token = data.token;\n this._displayId = data.displayId;\n // Refresh 60s before expiry to avoid edge-case rejections\n this._tokenExpiresAt = Date.now() + (data.expiresIn - 60) * 1000;\n\n log.info(`Authenticated as display ${this._displayId}`);\n }\n\n /**\n * Get current token synchronously (may be null or expired).\n * @returns {string|null}\n */\n getToken() {\n return this._token;\n }\n\n /**\n * Get a valid JWT token, refreshing if expired or missing.\n */\n async _getToken() {\n if (!this._token || Date.now() >= this._tokenExpiresAt) {\n await this._authenticate();\n }\n return this._token;\n }\n\n /**\n * Make an authenticated GET request with ETag caching.\n */\n async restGet(path, queryParams = {}, _retrying = false) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, String(value));\n }\n\n const cacheKey = path;\n const headers = { 'Authorization': `Bearer ${token}` };\n const cachedEtag = this._etags.get(cacheKey);\n if (cachedEtag) {\n headers['If-None-Match'] = cachedEtag;\n }\n\n log.debug(`GET ${path}`, queryParams);\n\n const response = await fetchWithRetry(url.toString(), {\n method: 'GET',\n headers,\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n if (_retrying) {\n throw new Error(`REST GET ${path} failed: 401 Unauthorized (after re-auth)`);\n }\n this._token = null;\n return this.restGet(path, queryParams, true);\n }\n\n if (response.status === 304) {\n const cached = this._responseCache.get(cacheKey);\n if (cached) {\n log.debug(`${path} → 304 (using cache)`);\n return cached;\n }\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST GET ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n let data;\n if (contentType.includes('application/json')) {\n data = await response.json();\n } else {\n data = await response.text();\n }\n\n const etag = response.headers.get('ETag');\n if (etag) {\n this._cacheSet(cacheKey, etag, data);\n }\n\n return data;\n }\n\n /**\n * Make an authenticated POST/PUT request with JSON body.\n */\n async restSend(method, path, body = {}, _retrying = false) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n\n log.debug(`${method} ${path}`);\n\n const response = await fetchWithRetry(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n if (_retrying) {\n throw new Error(`REST ${method} ${path} failed: 401 Unauthorized (after re-auth)`);\n }\n this._token = null;\n return this.restSend(method, path, body, true);\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST ${method} ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return await response.json();\n }\n return await response.text();\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings.\n * POST /displays → JSON with display settings\n */\n async registerDisplay() {\n // Auth first to get displayId\n await this._getToken();\n\n const os = typeof navigator !== 'undefined'\n ? `${navigator.platform} ${navigator.userAgent}`\n : 'unknown';\n\n const json = await this.restSend('POST', '/displays', {\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || 400,\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel || '',\n xmrPubKey: this.config.xmrPubKey || '',\n });\n\n return this._parseRegisterDisplayJson(json);\n }\n\n /**\n * Parse register display JSON response.\n * Same output format as XmdsClient.\n */\n _parseRegisterDisplayJson(json) {\n const display = json.display || json;\n const attrs = display['@attributes'] || {};\n const code = attrs.code || display.code;\n const message = attrs.message || display.message || '';\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n let tags = [];\n let commands = [];\n for (const [key, value] of Object.entries(display)) {\n if (key === '@attributes' || key === 'file') continue;\n if (key === 'commands') {\n if (Array.isArray(value)) {\n commands = value.map(c => ({\n commandCode: c.code || c.commandCode || '',\n commandString: c.commandString || ''\n }));\n }\n continue;\n }\n if (key === 'tags') {\n const extractTag = (t) => typeof t === 'object' ? (t.tag || t.value || '') : String(t);\n if (Array.isArray(value)) {\n tags = value.map(extractTag).filter(Boolean);\n } else if (value && typeof value === 'object') {\n const t = extractTag(value);\n if (t) tags = [t];\n } else if (typeof value === 'string' && value) {\n tags = [value];\n }\n continue;\n }\n settings[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n\n const checkRf = attrs.checkRf || '';\n const checkSchedule = attrs.checkSchedule || '';\n\n const displayAttrs = {\n date: attrs.date || display.date || null,\n timezone: attrs.timezone || display.timezone || null,\n status: attrs.status || display.status || null,\n localDate: attrs.localDate || display.localDate || null,\n version_instructions: attrs.version_instructions || display.version_instructions || null,\n };\n\n // Prefer structured syncConfig from REST module; fall back to flat SOAP fields\n const syncConfig = display.syncConfig || (display.syncGroup ? {\n syncGroup: String(display.syncGroup),\n syncPublisherPort: parseInt(display.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(display.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(display.syncVideoPauseDelay || '100', 10),\n isLead: String(display.syncGroup) === 'lead',\n } : null);\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download.\n * GET /displays/{id}/media → categorized JSON (no XML parsing)\n */\n async requiredFiles() {\n const json = await this.restGet(`/displays/${this._displayId}/media`);\n return this._parseRequiredFilesV2(json);\n }\n\n /**\n * Parse v2 categorized required files into the same flat format\n * that the download pipeline expects.\n *\n * v2 server returns: { media: [...], layouts: [...], widgets: [...] }\n * We flatten back to: { files: [...], purge: [] }\n */\n _parseRequiredFilesV2(json) {\n const files = [];\n\n // Media files (images, videos)\n for (const m of json.media || []) {\n files.push({\n type: m.type || 'media',\n id: m.id != null ? String(m.id) : null,\n size: m.fileSize || 0,\n md5: m.md5 || null,\n download: 'http',\n path: m.url || null,\n saveAs: m.saveAs || null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Layout files\n for (const l of json.layouts || []) {\n files.push({\n type: 'layout',\n id: l.id != null ? String(l.id) : null,\n size: l.fileSize || 0,\n md5: l.md5 || null,\n download: 'http',\n path: l.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Widget data files (datasets — dynamic API, not static media)\n for (const w of json.widgets || []) {\n files.push({\n type: 'dataset',\n id: w.id != null ? String(w.id) : null,\n size: 0,\n md5: w.md5 || null,\n download: 'http',\n path: w.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n updateInterval: w.updateInterval || 0,\n });\n }\n\n // Dependencies (fonts, CSS, JS bundles) — pre-classified as 'static'\n for (const d of json.dependencies || []) {\n files.push({\n type: 'static',\n id: d.id != null ? String(d.id) : null,\n size: d.fileSize || 0,\n md5: d.md5 || null,\n download: 'http',\n path: d.url || null,\n saveAs: null,\n fileType: d.type || null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n return { files, purge: [] };\n }\n\n /**\n * Schedule - get layout schedule.\n * GET /displays/{id}/schedule → native JSON (no XML parsing needed!)\n *\n * The v2 server returns the same structure as parseScheduleResponse(),\n * so we return it directly.\n */\n async schedule() {\n return this.restGet(`/displays/${this._displayId}/schedule`);\n }\n\n /**\n * GetResource - get rendered widget HTML.\n * GET /widgets/{layoutId}/{regionId}/{mediaId} → HTML string\n */\n async getResource(layoutId, regionId, mediaId) {\n return this.restGet(`/widgets/${layoutId}/${regionId}/${mediaId}`);\n }\n\n /**\n * NotifyStatus - report current status.\n * PUT /displays/{id}/status → JSON acknowledgement\n */\n async notifyStatus(status) {\n await enrichStatus(status);\n\n return this.restSend('PUT', `/displays/${this._displayId}/status`, {\n statusData: status,\n });\n }\n\n /**\n * MediaInventory - report downloaded files.\n * PUT /displays/{id}/inventory → JSON acknowledgement\n */\n async mediaInventory(inventoryXml) {\n const body = Array.isArray(inventoryXml)\n ? { inventoryItems: inventoryXml }\n : { inventory: inventoryXml };\n return this.restSend('PUT', `/displays/${this._displayId}/inventory`, body);\n }\n\n /**\n * BlackList - report broken media to CMS.\n * Not in v2 API — falls back to v1 behavior (no-op with warning).\n */\n async blackList(mediaId, type, reason) {\n log.warn(`BlackList not available in v2 API (${type}/${mediaId}: ${reason})`);\n return false;\n }\n\n /**\n * SubmitLog - submit player logs to CMS.\n * POST /displays/{id}/logs → JSON acknowledgement\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const body = Array.isArray(logXml) ? { logs: logXml } : { logXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/logs`, body);\n return result?.success === true;\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS.\n * POST /displays/{id}/screenshot → JSON acknowledgement\n */\n async submitScreenShot(base64Image) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/screenshot`, {\n screenshot: base64Image,\n });\n return result?.success === true;\n }\n\n /**\n * SubmitStats - submit proof of play statistics.\n * POST /displays/{id}/stats → JSON acknowledgement\n */\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const body = Array.isArray(statsXml) ? { stats: statsXml } : { statXml: statsXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/stats`, body);\n const success = result?.success === true;\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts.\n * POST /displays/{id}/faults → JSON acknowledgement\n */\n async reportFaults(faultJson) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/faults`, {\n fault: faultJson,\n });\n return result?.success === true;\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria.\n * GET /displays/{id}/weather → JSON weather data\n */\n async getWeather() {\n return this.restGet(`/displays/${this._displayId}/weather`);\n }\n\n // ─── Static helpers ───────────────────────────────────────────\n\n /**\n * Probe whether the CMS supports API v2.\n * GET ${PLAYER_API}/health → { version: 2, status: \"ok\" }\n *\n * @param {string} cmsUrl - CMS base URL\n * @param {Object} [retryOptions] - Retry options for fetch\n * @returns {Promise<boolean>} true if v2 is available\n */\n static async isAvailable(cmsUrl, retryOptions) {\n try {\n // In proxy mode, probe the local proxy's forward route instead of the CMS directly (avoids CORS)\n const isProxy = typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron || window.location.hostname === 'localhost');\n const base = isProxy ? '' : cmsUrl.replace(/\\/+$/, '');\n const url = `${base}${PLAYER_API}/health`;\n const timeoutMs = retryOptions?.timeoutMs || 8000;\n const fetchOptions = { method: 'GET' };\n // Apply timeout via AbortSignal (generous on first probe — TLS cold start\n // from the proxy to the CMS can take 5-6s on first connection)\n if (typeof AbortSignal !== 'undefined' && AbortSignal.timeout) {\n fetchOptions.signal = AbortSignal.timeout(timeoutMs);\n }\n const response = await fetchWithRetry(url, fetchOptions, retryOptions || { maxRetries: 0 });\n if (!response.ok) return false;\n const data = await response.json();\n return data.version === 2 && data.status === 'ok';\n } catch {\n return false;\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Shared schedule XML parser used by both RestClient and XmdsClient.\n *\n * Both transports return the same XML structure for the Schedule endpoint,\n * so the parsing logic lives here to avoid duplication.\n */\n\n/**\n * Parse criteria child elements from a layout/overlay element.\n * Criteria are conditions that must be met for the item to display.\n *\n * XML format: <criteria metric=\"dayOfWeek\" condition=\"equals\" type=\"string\">Monday</criteria>\n *\n * @param {Element} parentEl - Parent XML element containing <criteria> children\n * @returns {Array<{metric: string, condition: string, type: string, value: string}>}\n */\nfunction parseCriteria(parentEl) {\n const criteria = [];\n for (const child of parentEl.children) {\n if (child.tagName !== 'criteria') continue;\n criteria.push({\n metric: child.getAttribute('metric') || '',\n condition: child.getAttribute('condition') || '',\n type: child.getAttribute('type') || 'string',\n value: child.textContent || ''\n });\n }\n return criteria;\n}\n\n/**\n * Parse a `<tags>` child element (if present) into a flat string array.\n *\n * Used by the #236 sync bridge when a schedule response exposes\n * per-layout tags (e.g. `<tag>xp-sync-group:NAME</tag>`). Upstream\n * Xibo CMS does NOT currently emit `<tags>` inside schedule `<layout>`\n * entries — the authoritative source is the XLF file itself, parsed\n * by renderer-lite.parseXlf(). This helper exists so that:\n * 1. A forked CMS that DOES emit per-layout `<tags>` (or future\n * upstream) gets them surfaced for free.\n * 2. Callers can treat `layout.tags` as a stable field (empty array\n * when absent).\n *\n * @param {Element} parentEl - Layout/campaign-layout element\n * @returns {string[]} Tags parsed from a direct <tags> child, or [].\n */\nfunction parseLayoutTags(parentEl) {\n const tags = [];\n for (const child of parentEl.children) {\n if (child.tagName !== 'tags') continue;\n for (const tagEl of child.children) {\n if (tagEl.tagName !== 'tag') continue;\n const text = (tagEl.textContent || '').trim();\n if (text) tags.push(text);\n }\n }\n return tags;\n}\n\n/**\n * Parse Schedule XML response into a normalized schedule object.\n *\n * @param {string} xml - Raw XML string from CMS schedule endpoint\n * @returns {Object} Parsed schedule with default, layouts, campaigns, overlays, actions, commands, dataConnectors\n */\nexport function parseScheduleResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const schedule = {\n default: null,\n defaultDependants: [],\n dependants: [], // Global dependants that gate ALL layouts\n layouts: [],\n campaigns: [],\n overlays: [],\n actions: [],\n commands: [],\n dataConnectors: []\n };\n\n // Parse global dependants (root-level <dependants> — must be cached before any layout plays)\n const scheduleEl = doc.querySelector('schedule');\n if (scheduleEl) {\n const globalDeps = Array.from(scheduleEl.children).filter(\n el => el.tagName === 'dependants'\n );\n for (const depContainer of globalDeps) {\n // Skip if this is nested inside <default>, <layout>, etc.\n if (depContainer.parentElement !== scheduleEl) continue;\n for (const fileEl of depContainer.querySelectorAll('file')) {\n if (fileEl.textContent) schedule.dependants.push(fileEl.textContent);\n }\n }\n }\n\n const defaultEl = doc.querySelector('default');\n if (defaultEl) {\n schedule.default = defaultEl.getAttribute('file');\n // Parse dependants — files that must be cached before this layout plays\n const defaultDeps = defaultEl.querySelectorAll('dependants > file');\n if (defaultDeps.length > 0) {\n schedule.defaultDependants = [...defaultDeps].map(el => el.textContent);\n }\n }\n\n // Parse campaigns (groups of layouts with shared priority)\n for (const campaignEl of doc.querySelectorAll('campaign')) {\n const campaign = {\n id: campaignEl.getAttribute('id'),\n priority: parseInt(campaignEl.getAttribute('priority') || '0'),\n fromdt: campaignEl.getAttribute('fromdt'),\n todt: campaignEl.getAttribute('todt'),\n scheduleid: campaignEl.getAttribute('scheduleid'),\n maxPlaysPerHour: parseInt(campaignEl.getAttribute('maxPlaysPerHour') || '0'),\n shareOfVoice: parseInt(campaignEl.getAttribute('shareOfVoice') || '0'),\n isGeoAware: campaignEl.getAttribute('isGeoAware') === '1',\n geoLocation: campaignEl.getAttribute('geoLocation') || '',\n syncEvent: campaignEl.getAttribute('syncEvent') === '1',\n recurrenceType: campaignEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(campaignEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: campaignEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: campaignEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(campaignEl),\n layouts: []\n };\n\n // Parse layouts within this campaign\n for (const layoutEl of campaignEl.querySelectorAll('layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n campaign.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n // Layouts in campaigns inherit timing from campaign level\n fromdt: layoutEl.getAttribute('fromdt') || campaign.fromdt,\n todt: layoutEl.getAttribute('todt') || campaign.todt,\n scheduleid: campaign.scheduleid,\n priority: campaign.priority, // Priority at campaign level\n campaignId: campaign.id,\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl),\n tags: parseLayoutTags(layoutEl) // #236 sync bridge (currently no-op upstream; forks may emit)\n });\n }\n\n schedule.campaigns.push(campaign);\n }\n\n // Parse standalone layouts (not in campaigns)\n for (const layoutEl of doc.querySelectorAll('schedule > layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n schedule.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n fromdt: layoutEl.getAttribute('fromdt'),\n todt: layoutEl.getAttribute('todt'),\n scheduleid: layoutEl.getAttribute('scheduleid'),\n priority: parseInt(layoutEl.getAttribute('priority') || '0'),\n campaignId: null, // Standalone layout\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n recurrenceType: layoutEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(layoutEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: layoutEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: layoutEl.getAttribute('recurrenceRange') || null,\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl),\n tags: parseLayoutTags(layoutEl) // #236 sync bridge (currently no-op upstream; forks may emit)\n });\n }\n\n // Parse overlay layouts (appear on top of main layouts)\n const overlaysContainer = doc.querySelector('overlays');\n if (overlaysContainer) {\n for (const overlayEl of overlaysContainer.querySelectorAll('overlay')) {\n const fileId = overlayEl.getAttribute('file');\n schedule.overlays.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n duration: parseInt(overlayEl.getAttribute('duration') || '60'),\n file: fileId,\n fromdt: overlayEl.getAttribute('fromdt'),\n todt: overlayEl.getAttribute('todt'),\n priority: parseInt(overlayEl.getAttribute('priority') || '0'),\n scheduleid: overlayEl.getAttribute('scheduleid'),\n isGeoAware: overlayEl.getAttribute('isGeoAware') === '1',\n geoLocation: overlayEl.getAttribute('geoLocation') || '',\n syncEvent: overlayEl.getAttribute('syncEvent') === '1',\n maxPlaysPerHour: parseInt(overlayEl.getAttribute('maxPlaysPerHour') || '0'),\n recurrenceType: overlayEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(overlayEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: overlayEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: overlayEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(overlayEl)\n });\n }\n }\n\n // Parse action events (scheduled triggers)\n const actionsContainer = doc.querySelector('actions');\n if (actionsContainer) {\n for (const actionEl of actionsContainer.querySelectorAll('action')) {\n schedule.actions.push({\n actionType: actionEl.getAttribute('actionType') || '',\n triggerCode: actionEl.getAttribute('triggerCode') || '',\n layoutCode: actionEl.getAttribute('layoutCode') || '',\n commandCode: actionEl.getAttribute('commandCode') || '',\n duration: parseInt(actionEl.getAttribute('duration') || '0'),\n fromdt: actionEl.getAttribute('fromdt'),\n todt: actionEl.getAttribute('todt'),\n priority: parseInt(actionEl.getAttribute('priority') || '0'),\n scheduleid: actionEl.getAttribute('scheduleid'),\n isGeoAware: actionEl.getAttribute('isGeoAware') === '1',\n geoLocation: actionEl.getAttribute('geoLocation') || ''\n });\n }\n }\n\n // Parse server commands (remote control)\n for (const cmdEl of doc.querySelectorAll('schedule > command')) {\n schedule.commands.push({\n code: cmdEl.getAttribute('code') || '',\n date: cmdEl.getAttribute('date') || ''\n });\n }\n\n // Parse data connectors (real-time data sources for widgets)\n // Spec: <dataConnectors><connector dataSetId=\"\" dataParams=\"\" js=\"\"/></dataConnectors>\n const dataConnectorsContainer = doc.querySelector('dataConnectors');\n if (dataConnectorsContainer) {\n for (const dcEl of dataConnectorsContainer.querySelectorAll('connector')) {\n schedule.dataConnectors.push({\n id: dcEl.getAttribute('id') || '',\n dataConnectorId: dcEl.getAttribute('dataConnectorId') || '',\n dataSetId: dcEl.getAttribute('dataSetId') || '',\n dataKey: dcEl.getAttribute('dataKey') || '',\n dataParams: dcEl.getAttribute('dataParams') || '',\n js: dcEl.getAttribute('js') || '',\n url: dcEl.getAttribute('url') || '',\n updateInterval: parseInt(dcEl.getAttribute('updateInterval') || '300', 10)\n });\n }\n }\n\n return schedule;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * XMDS SOAP transport client for Xibo CMS.\n *\n * Uses the traditional SOAP/XML endpoint (xmds.php) for full protocol\n * compatibility with all Xibo CMS versions.\n *\n * Protocol: https://github.com/linuxnow/xibo_players_docs\n */\nimport { createLogger, fetchWithRetry, PLAYER_API } from '@xiboplayer/utils';\nimport { enrichStatus } from './status-enrichment.js';\nimport { parseScheduleResponse } from './schedule-parser.js';\n\nconst log = createLogger('XMDS');\n\nexport class XmdsClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 5;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n }\n\n // ─── SOAP transport helpers ─────────────────────────────────────\n\n /**\n * Build SOAP envelope for a given method and parameters\n */\n buildEnvelope(method, params) {\n const paramElements = Object.entries(params)\n .map(([key, value]) => {\n const escaped = String(value)\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n return `<${key} xsi:type=\"xsd:string\">${escaped}</${key}>`;\n })\n .join('\\n ');\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soap:Envelope\n xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"\n xmlns:tns=\"urn:xmds\"\n xmlns:types=\"urn:xmds/encodedTypes\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <tns:${method}>\n ${paramElements}\n </tns:${method}>\n </soap:Body>\n</soap:Envelope>`;\n }\n\n /**\n * Rewrite XMDS URL for local proxy.\n * If running inside a local wrapper (Electron, Chromium kiosk), use the\n * local proxy to avoid CORS.\n * Detection: preload.js exposes window.electronAPI.isElectron = true,\n * or fallback to checking localhost (any local wrapper port).\n */\n rewriteXmdsUrl(cmsUrl) {\n if (typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost')) {\n const encodedCmsUrl = encodeURIComponent(cmsUrl);\n return `/xmds-proxy?cms=${encodedCmsUrl}`;\n }\n\n return `${cmsUrl}/xmds.php`;\n }\n\n /**\n * Call XMDS SOAP method\n */\n async call(method, params = {}) {\n const xmdsUrl = this.rewriteXmdsUrl(this.config.cmsUrl);\n const url = `${xmdsUrl}${xmdsUrl.includes('?') ? '&' : '?'}v=${this.schemaVersion}&method=${method}`;\n const body = this.buildEnvelope(method, params);\n\n log.debug(`${method}`, params);\n log.debug(`URL: ${url}`);\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'text/xml; charset=utf-8'\n },\n body\n }, this.retryOptions);\n\n if (!response.ok) {\n throw new Error(`XMDS ${method} failed: ${response.status} ${response.statusText}`);\n }\n\n const xml = await response.text();\n return this.parseResponse(xml, method);\n }\n\n /**\n * Parse SOAP response\n */\n parseResponse(xml, method) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n // Check for SOAP fault (handle namespace prefix like soap:Fault)\n let fault = doc.querySelector('Fault');\n if (!fault) {\n fault = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === 'Fault' || el.tagName.endsWith(':Fault')\n );\n }\n if (fault) {\n const faultString = fault.querySelector('faultstring')?.textContent\n || Array.from(fault.querySelectorAll('*')).find(el => el.localName === 'faultstring')?.textContent\n || 'Unknown SOAP fault';\n throw new Error(`SOAP Fault: ${faultString}`);\n }\n\n // Extract response element (handle namespace prefixes like ns1:MethodResponse)\n const responseTag = `${method}Response`;\n let responseEl = doc.querySelector(responseTag);\n if (!responseEl) {\n responseEl = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === responseTag || el.tagName.endsWith(':' + responseTag)\n );\n }\n\n if (!responseEl) {\n throw new Error(`No ${responseTag} element in SOAP response`);\n }\n\n const returnEl = responseEl.firstElementChild;\n if (!returnEl) {\n return null;\n }\n\n return returnEl.textContent;\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings\n */\n async registerDisplay() {\n const os = `${navigator.platform} ${navigator.userAgent}`;\n\n const xml = await this.call('RegisterDisplay', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || '400',\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel || '',\n xmrPubKey: this.config.xmrPubKey || '',\n licenceResult: 'licensed'\n });\n\n return this.parseRegisterDisplayResponse(xml);\n }\n\n /**\n * Parse RegisterDisplay XML response\n */\n parseRegisterDisplayResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const display = doc.querySelector('display');\n if (!display) {\n throw new Error('Invalid RegisterDisplay response: no <display> element');\n }\n\n const code = display.getAttribute('code');\n const message = display.getAttribute('message');\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n const tags = [];\n const commands = [];\n for (const child of display.children) {\n const name = child.tagName.toLowerCase();\n if (name === 'file') continue;\n if (name === 'commands') {\n // Parse <commands><command code=\"xyz\" commandString=\"args\"/></commands>\n for (const cmdEl of child.querySelectorAll('command')) {\n commands.push({\n commandCode: cmdEl.getAttribute('code') || cmdEl.getAttribute('commandCode') || '',\n commandString: cmdEl.getAttribute('commandString') || ''\n });\n }\n continue;\n }\n if (name === 'tags') {\n // Parse <tags><tag>value</tag>...</tags> into array\n for (const tagEl of child.querySelectorAll('tag')) {\n if (tagEl.textContent) tags.push(tagEl.textContent);\n }\n continue;\n }\n settings[child.tagName] = child.textContent;\n }\n\n const checkRf = display.getAttribute('checkRf') || '';\n const checkSchedule = display.getAttribute('checkSchedule') || '';\n\n // Extract display-level attributes from CMS (server time, status, version info)\n const displayAttrs = {\n date: display.getAttribute('date') || null,\n timezone: display.getAttribute('timezone') || null,\n status: display.getAttribute('status') || null,\n localDate: display.getAttribute('localDate') || null,\n version_instructions: display.getAttribute('version_instructions') || null,\n };\n\n // Extract sync group config if present (multi-display sync coordination)\n const syncGroupVal = settings.syncGroup || null;\n const syncConfig = syncGroupVal ? {\n syncGroup: syncGroupVal,\n syncPublisherPort: parseInt(settings.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(settings.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(settings.syncVideoPauseDelay || '100', 10),\n isLead: syncGroupVal === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download\n */\n async requiredFiles() {\n const xml = await this.call('RequiredFiles', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return this.parseRequiredFilesResponse(xml);\n }\n\n /**\n * Parse RequiredFiles XML response\n */\n parseRequiredFilesResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const files = [];\n for (const fileEl of doc.querySelectorAll('file')) {\n const file = {\n type: fileEl.getAttribute('type'),\n id: fileEl.getAttribute('id'),\n size: parseInt(fileEl.getAttribute('size') || '0'),\n md5: fileEl.getAttribute('md5'),\n download: fileEl.getAttribute('download'),\n path: fileEl.getAttribute('path'),\n saveAs: fileEl.getAttribute('saveAs') || null,\n fileType: fileEl.getAttribute('fileType') || null,\n code: fileEl.getAttribute('code'),\n layoutid: fileEl.getAttribute('layoutid'),\n regionid: fileEl.getAttribute('regionid'),\n mediaid: fileEl.getAttribute('mediaid')\n };\n\n // Rewrite XMDS download URLs to local proxy cache-through paths.\n // Store the original CMS URL so the proxy can fetch on cache miss.\n if (file.path && file.path.includes('xmds.php')) {\n file.cmsDownloadUrl = file.path;\n const xmdsType = file.fileType; // L=layout, M=media, P=resource\n if (xmdsType === 'L' || file.type === 'layout') {\n file.path = `${PLAYER_API}/layouts/${file.id}`;\n } else if (xmdsType === 'P') {\n file.path = `${PLAYER_API}/dependencies/${file.saveAs || file.id}`;\n } else {\n file.path = `${PLAYER_API}/media/file/${file.saveAs || file.id}`;\n }\n }\n\n files.push(file);\n }\n\n // Parse purge block — files CMS wants the player to delete\n const purgeItems = [];\n const purgeEl = doc.querySelector('purge');\n if (purgeEl) {\n for (const itemEl of purgeEl.querySelectorAll('item')) {\n purgeItems.push({\n id: itemEl.getAttribute('id'),\n storedAs: itemEl.getAttribute('storedAs')\n });\n }\n }\n\n return { files, purge: purgeItems };\n }\n\n /**\n * Schedule - get layout schedule\n */\n async schedule() {\n const xml = await this.call('Schedule', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return parseScheduleResponse(xml);\n }\n\n /**\n * GetResource - get rendered widget HTML\n */\n async getResource(layoutId, regionId, mediaId) {\n const xml = await this.call('GetResource', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n layoutId: String(layoutId),\n regionId: String(regionId),\n mediaId: String(mediaId)\n });\n\n return xml;\n }\n\n /**\n * NotifyStatus - report current status\n * @param {Object} status - Status object with currentLayoutId, deviceName, etc.\n */\n async notifyStatus(status) {\n await enrichStatus(status);\n\n return await this.call('NotifyStatus', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n status: JSON.stringify(status)\n });\n }\n\n /**\n * MediaInventory - report downloaded files\n */\n async mediaInventory(inventoryXml) {\n return await this.call('MediaInventory', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaInventory: inventoryXml\n });\n }\n\n /**\n * BlackList - report broken media to CMS\n * @param {string} mediaId - The media file ID\n * @param {string} type - File type ('media' or 'layout')\n * @param {string} reason - Reason for blacklisting\n * @returns {Promise<boolean>}\n */\n async blackList(mediaId, type, reason) {\n try {\n const xml = await this.call('BlackList', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaId: String(mediaId),\n type: type || 'media',\n reason: reason || 'Failed to render'\n });\n log.info(`BlackListed ${type}/${mediaId}: ${reason}`);\n return xml === 'true';\n } catch (error) {\n log.warn('BlackList failed:', error);\n return false;\n }\n }\n\n /**\n * SubmitLog - submit player logs to CMS for remote debugging\n * @param {string} logXml - XML string containing log entries\n * @returns {Promise<boolean>} - true if logs were successfully submitted\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const xml = await this.call('SubmitLog', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n logXml: logXml\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS for display verification\n * @param {string} base64Image - Base64-encoded PNG image data\n * @returns {Promise<boolean>} - true if screenshot was successfully submitted\n */\n async submitScreenShot(base64Image) {\n const xml = await this.call('SubmitScreenShot', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n screenShot: base64Image\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitStats - submit proof of play statistics\n * @param {string} statsXml - XML-encoded stats string\n * @returns {Promise<boolean>} - true if stats were successfully submitted\n */\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts\n * @param {string} faultJson - JSON-encoded fault data\n * @returns {Promise<boolean>}\n */\n async reportFaults(faultJson) {\n return this.call('ReportFaults', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n fault: faultJson\n });\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria\n * @returns {Promise<string>} Weather data XML from CMS\n */\n async getWeather() {\n return this.call('GetWeather', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n }\n\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const xml = await this.call('SubmitStats', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n statXml: statsXml\n });\n\n const success = xml === 'true';\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CmsClient interface definition — the unified contract for CMS communication.\n *\n * Both RestClient and XmdsClient implement this interface identically.\n * PlayerCore calls these methods without knowing which transport is underneath.\n * ProtocolDetector selects the implementation at startup.\n *\n * This file provides:\n * 1. JSDoc type definitions for the interface\n * 2. CMS_CLIENT_METHODS — canonical list of required methods\n * 3. assertCmsClient() — runtime conformance check\n *\n * @example\n * import { ProtocolDetector, RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(cmsUrl, RestClient, XmdsClient);\n * const { client } = await detector.detect(config);\n * // client implements CmsClient — PlayerCore doesn't care which one\n */\n\n/**\n * @typedef {Object} RegisterDisplayResult\n * @property {string} code - 'READY' or error code\n * @property {string} message - Human-readable status message\n * @property {Object|null} settings - Display settings (null if not READY)\n * @property {string[]} tags - Display tags\n * @property {Array<{commandCode: string, commandString: string}>} commands - Scheduled commands\n * @property {Object} displayAttrs - Server-provided attributes (date, timezone, status)\n * @property {string} checkRf - CRC checksum for RequiredFiles (skip if unchanged)\n * @property {string} checkSchedule - CRC checksum for Schedule (skip if unchanged)\n * @property {Object|null} syncConfig - Multi-display sync configuration\n */\n\n/**\n * @typedef {Object} RequiredFilesResult\n * @property {Array<{type: string, id: string, size: number, md5: string, download: string, path: string, saveAs: string|null}>} files\n * @property {Array<{id: string, storedAs: string}>} purge - Files to delete\n */\n\n/**\n * @typedef {Object} CmsClient\n * @property {() => Promise<RegisterDisplayResult>} registerDisplay\n * @property {() => Promise<RequiredFilesResult>} requiredFiles\n * @property {() => Promise<Object>} schedule\n * @property {(layoutId: string, regionId: string, mediaId: string) => Promise<string>} getResource\n * @property {(status: Object) => Promise<any>} notifyStatus\n * @property {(inventoryXml: string|Array) => Promise<any>} mediaInventory\n * @property {(mediaId: string, type: string, reason: string) => Promise<boolean>} blackList\n * @property {(logXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitLog\n * @property {(base64Image: string) => Promise<boolean>} submitScreenShot\n * @property {(statsXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitStats\n * @property {(faultJson: string|Object) => Promise<boolean>} reportFaults\n * @property {() => Promise<Object>} getWeather\n */\n\n/**\n * Canonical list of methods that every CmsClient implementation must provide.\n * Used for runtime conformance checks and test assertions.\n */\nexport const CMS_CLIENT_METHODS = [\n 'registerDisplay',\n 'requiredFiles',\n 'schedule',\n 'getResource',\n 'notifyStatus',\n 'mediaInventory',\n 'blackList',\n 'submitLog',\n 'submitScreenShot',\n 'submitStats',\n 'reportFaults',\n 'getWeather',\n];\n\n/**\n * Verify that an object implements the CmsClient interface.\n * Throws if any required method is missing or not a function.\n *\n * @param {any} client - Object to check\n * @param {string} [label] - Label for error messages (e.g. 'RestClient')\n * @throws {Error} If the client doesn't conform\n */\nexport function assertCmsClient(client, label = 'client') {\n for (const method of CMS_CLIENT_METHODS) {\n if (typeof client[method] !== 'function') {\n throw new Error(`${label} missing CmsClient method: ${method}()`);\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CMS Protocol Auto-Detector\n *\n * Probes the CMS to determine which communication protocol to use:\n * - REST/PlayerRestApi — optimized JSON protocol (custom CMS image)\n * - SOAP/XMDS — universal XML protocol (any vanilla Xibo CMS)\n *\n * Detection logic:\n * 1. GET {cmsUrl}${PLAYER_API}/health with a generous timeout\n * 2. If 200 + valid JSON → REST\n * 3. If 404/error/timeout → SOAP (fallback)\n *\n * After a fallback to XMDS, the detector can run an automatic background\n * re-probe loop with exponential backoff so the player promotes back to\n * REST as soon as the CMS recovers. The re-probe loop also acts as a\n * visibility signal: each failed probe emits a warning that names the\n * next attempt, so it's obvious at a glance that the player is still\n * running on the wrong transport.\n *\n * @example\n * import { ProtocolDetector, RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(config.cmsUrl, RestClient, XmdsClient);\n * const { client, protocol } = await detector.detect(config);\n * let xmds = client;\n *\n * if (protocol === 'xmds') {\n * detector.startAutoReprobe(config, (newClient) => {\n * // REST recovered — swap the live client pointer\n * xmds = newClient;\n * });\n * }\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { assertCmsClient } from './cms-client.js';\n\nconst log = createLogger('Protocol');\n\n/**\n * Default timeout for the FIRST probe at startup.\n * Intentionally generous: a cold CMS has to warm up PHP-FPM workers,\n * negotiate TLS, populate OpCache, and possibly fill MariaDB query plan\n * caches. Empirically a healthy cold CMS can take 5-6 seconds on the\n * very first request after a restart — the old 3000ms default was too\n * tight and would lock the player into XMDS fallback on cold start.\n */\nconst FIRST_PROBE_TIMEOUT_MS = 10000;\n\n/**\n * Default timeout for re-probes after fallback is engaged.\n * Shorter than the first probe because by the time we're re-probing we\n * already know the CMS was reachable at some point — either it's up\n * now or it isn't.\n */\nconst REPROBE_TIMEOUT_MS = 5000;\n\n/** Starting delay before the first auto-reprobe after XMDS fallback. */\nconst REPROBE_MIN_DELAY_MS = 5000;\n/** Ceiling delay for the backoff — we re-probe at least this often forever. */\nconst REPROBE_MAX_DELAY_MS = 120000;\n/** Exponential factor applied after each failed reprobe. */\nconst REPROBE_BACKOFF_FACTOR = 2;\n\nexport class ProtocolDetector {\n /**\n * @param {string} cmsUrl - CMS base URL\n * @param {typeof import('./rest-client.js').RestClient} RestClientClass - RestClient constructor\n * @param {typeof import('./xmds-client.js').XmdsClient} XmdsClientClass - XmdsClient constructor\n * @param {Object} [options]\n * @param {number} [options.firstProbeTimeoutMs=10000] - Timeout for the initial probe\n * @param {number} [options.reprobeTimeoutMs=5000] - Timeout for re-probes after fallback\n * @param {number} [options.probeTimeoutMs] - Back-compat: sets BOTH first and reprobe timeouts to the same value\n * @param {number} [options.reprobeMinDelayMs=5000] - Initial delay before the first auto-reprobe\n * @param {number} [options.reprobeMaxDelayMs=120000] - Ceiling delay between auto-reprobes\n */\n constructor(cmsUrl, RestClientClass, XmdsClientClass, options = {}) {\n this.cmsUrl = cmsUrl;\n this.RestClient = RestClientClass;\n this.XmdsClient = XmdsClientClass;\n\n // Back-compat: if a single probeTimeoutMs is provided, use it for both\n // first and reprobe. New callers should pass the split options.\n const legacy = options.probeTimeoutMs;\n this.firstProbeTimeoutMs = options.firstProbeTimeoutMs ?? legacy ?? FIRST_PROBE_TIMEOUT_MS;\n this.reprobeTimeoutMs = options.reprobeTimeoutMs ?? legacy ?? REPROBE_TIMEOUT_MS;\n\n this.reprobeMinDelayMs = options.reprobeMinDelayMs ?? REPROBE_MIN_DELAY_MS;\n this.reprobeMaxDelayMs = options.reprobeMaxDelayMs ?? REPROBE_MAX_DELAY_MS;\n\n /** @type {'rest'|'xmds'|null} Detected protocol (null = not yet probed) */\n this.protocol = null;\n\n /** @type {number} Timestamp of last probe attempt */\n this.lastProbeTime = 0;\n\n /** @type {ReturnType<typeof setTimeout>|null} Scheduled auto-reprobe timer */\n this._reprobeTimer = null;\n\n /** @type {number} Current backoff delay (ms) — resets on successful probe or stop */\n this._reprobeDelay = this.reprobeMinDelayMs;\n }\n\n /**\n * Probe the CMS health endpoint to determine protocol availability.\n * @param {Object} [opts]\n * @param {boolean} [opts.first=false] - Use the longer first-probe timeout\n * @returns {Promise<boolean>} true if REST/PlayerRestApi is available\n */\n async probe(opts = {}) {\n const timeoutMs = opts.first ? this.firstProbeTimeoutMs : this.reprobeTimeoutMs;\n const available = await this.RestClient.isAvailable(this.cmsUrl, {\n maxRetries: 0,\n timeoutMs,\n });\n this.lastProbeTime = Date.now();\n return available;\n }\n\n /**\n * Detect the best protocol and create the appropriate client.\n * On first call, probes the CMS with the generous first-probe timeout.\n * On subsequent calls, returns the cached protocol unless reprobe() is called.\n *\n * @param {Object} config - Player configuration (passed to client constructor)\n * @param {string} [forceProtocol] - 'rest'|'xmds' to skip detection\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds'}>}\n */\n async detect(config, forceProtocol) {\n if (forceProtocol === 'rest') {\n this.protocol = 'rest';\n log.info('Using REST transport (forced)');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n if (forceProtocol === 'xmds') {\n this.protocol = 'xmds';\n log.info('Using XMDS/SOAP transport (forced)');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n // Auto-detect\n log.info(`Probing CMS for REST API availability (timeout ${this.firstProbeTimeoutMs}ms)...`);\n let isRest = false;\n try {\n isRest = await this.probe({ first: true });\n } catch (e) {\n log.warn('REST probe failed:', e?.message || e);\n }\n\n if (isRest) {\n this.protocol = 'rest';\n log.info('REST transport detected — using PlayerRestApi');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n this.protocol = 'xmds';\n log.warn('REST unavailable — falling back to XMDS/SOAP transport');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n /**\n * Re-probe the CMS once and potentially switch protocols.\n * Called either externally on connection errors, or internally by the\n * auto-reprobe loop.\n *\n * @param {Object} config - Player configuration\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds', changed: boolean}>}\n */\n async reprobe(config) {\n const previousProtocol = this.protocol;\n\n let isRest = false;\n try {\n isRest = await this.probe({ first: false });\n } catch (e) {\n log.warn('Re-probe failed:', e?.message || e);\n }\n\n const newProtocol = isRest ? 'rest' : 'xmds';\n const changed = newProtocol !== previousProtocol;\n\n if (changed) {\n log.info(`Protocol changed: ${previousProtocol} → ${newProtocol}`);\n this.protocol = newProtocol;\n const client = isRest ? new this.RestClient(config) : new this.XmdsClient(config);\n assertCmsClient(client, isRest ? 'RestClient' : 'XmdsClient');\n return { client, protocol: newProtocol, changed: true };\n }\n\n return { client: null, protocol: newProtocol, changed: false };\n }\n\n /**\n * Start an automatic background re-probe loop while on XMDS fallback.\n * Uses exponential backoff from reprobeMinDelayMs up to reprobeMaxDelayMs\n * (defaults: 5s → 2min). Each failed reprobe logs a visibility warning\n * that names the current fallback state and the next probe time, so an\n * operator reading the log after any interval can see at a glance that\n * the player is still running on the wrong transport.\n *\n * When a reprobe succeeds (detects REST is back), the callback is invoked\n * with the new client and the loop stops. No-op if the current protocol\n * is not 'xmds'.\n *\n * @param {Object} config - Player configuration passed to reprobe()\n * @param {(client: any) => void} onRestPromoted - Called when REST recovers\n */\n startAutoReprobe(config, onRestPromoted) {\n if (this.protocol !== 'xmds') {\n // Only meaningful while in fallback\n return;\n }\n // Cancel any existing timer before scheduling a fresh one\n this.stopAutoReprobe();\n this._reprobeDelay = this.reprobeMinDelayMs;\n\n const schedule = () => {\n const nextInMs = this._reprobeDelay;\n this._reprobeTimer = setTimeout(async () => {\n this._reprobeTimer = null;\n let result;\n try {\n result = await this.reprobe(config);\n } catch (e) {\n log.warn('Auto-reprobe error:', e?.message || e);\n result = { changed: false, protocol: 'xmds', client: null };\n }\n\n if (result.changed && result.protocol === 'rest') {\n log.info('REST recovered — promoting back from XMDS fallback');\n this._reprobeDelay = this.reprobeMinDelayMs;\n try {\n onRestPromoted(result.client);\n } catch (e) {\n log.warn('onRestPromoted callback threw:', e?.message || e);\n }\n return; // stop — we're back on REST\n }\n\n // Still on XMDS — back off and try again\n const nextDelay = Math.min(\n this._reprobeDelay * REPROBE_BACKOFF_FACTOR,\n this.reprobeMaxDelayMs,\n );\n log.warn(\n `Still on XMDS fallback — REST probe failed, next attempt in ${Math.round(nextDelay / 1000)}s`,\n );\n this._reprobeDelay = nextDelay;\n schedule();\n }, nextInMs);\n };\n\n log.info(\n `Auto-reprobe scheduled — first attempt in ${Math.round(this._reprobeDelay / 1000)}s (backoff up to ${Math.round(this.reprobeMaxDelayMs / 1000)}s)`,\n );\n schedule();\n }\n\n /**\n * Cancel any pending auto-reprobe timer. Safe to call multiple times.\n * Call this when the player is shutting down, or when the protocol is\n * swapped back to REST by an external caller.\n */\n stopAutoReprobe() {\n if (this._reprobeTimer) {\n clearTimeout(this._reprobeTimer);\n this._reprobeTimer = null;\n }\n this._reprobeDelay = this.reprobeMinDelayMs;\n }\n\n /**\n * Get the currently detected protocol.\n * @returns {'rest'|'xmds'|null}\n */\n getProtocol() {\n return this.protocol;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n// @xiboplayer/xmds - XMDS clients (REST and SOAP)\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\nexport { RestClient } from './rest-client.js';\nexport { XmdsClient } from './xmds-client.js';\nexport { ProtocolDetector } from './protocol-detector.js';\nexport { CMS_CLIENT_METHODS, assertCmsClient } from './cms-client.js';\nexport { parseScheduleResponse } from './schedule-parser.js';\n"],"mappings":"2yBCSA,eAAsB,EAAa,EAAQ,CAEzC,GAAI,OAAO,UAAc,KAAe,UAAU,SAAS,SACzD,GAAI,CACF,IAAM,EAAW,MAAM,UAAU,QAAQ,UAAU,CACnD,EAAO,eAAiB,EAAS,MAAQ,EAAS,MAClD,EAAO,WAAa,EAAS,WACnB,EAIV,CAAC,EAAO,UAAY,OAAO,KAAS,MACtC,EAAO,SAAW,KAAK,gBAAgB,CAAC,iBAAiB,CAAC,UAI5D,AACE,EAAO,eAAe,mBAAmB,EAAO,iBAAmB,SCPvE,IAAMA,EAAM,EAAa,OAAO,CAEnB,EAAb,KAAwB,CACtB,YAAY,EAAQ,CAClB,KAAK,OAAS,EACd,KAAK,cAAgB,EACrB,KAAK,aAAe,EAAO,cAAgB,CAAE,WAAY,EAAG,YAAa,IAAM,CAG/E,KAAK,OAAS,KACd,KAAK,gBAAkB,EACvB,KAAK,WAAa,KAGlB,KAAK,OAAS,IAAI,IAClB,KAAK,eAAiB,IAAI,IAC1B,KAA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"}
@@ -1,2 +1,2 @@
1
- import{c as e,u as t}from"./src-BtVLiVYZ.js";var n={name:`@xiboplayer/settings`,version:`0.7.21`,description:`CMS settings management and application for xiboplayer`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./manager":`./src/settings.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`},devDependencies:{jsdom:`^29.0.2`,vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`settings`,`configuration`,`display-settings`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/settings`},homepage:`https://xiboplayer.org`},r=t(`DisplaySettings`),i=class extends e{constructor(){super(),this.settings={collectInterval:300,displayName:`Unknown Display`,sizeX:1920,sizeY:1080,statsEnabled:!1,aggregationLevel:`Individual`,logLevel:`error`,xmrNetworkAddress:null,xmrWebSocketAddress:null,xmrCmsKey:null,preventSleep:!0,embeddedServerPort:9696,screenshotInterval:120,downloadStartWindow:null,downloadEndWindow:null,licenceCode:null,isSspEnabled:!1}}applySettings(e){if(!e)return r.warn(`No settings provided`),{changed:[],settings:this.settings};let t=[],n=this.settings.collectInterval;return this.settings.collectInterval=this.parseCollectInterval(e.collectInterval||e.CollectInterval),this.settings.displayName=e.displayName||e.DisplayName||this.settings.displayName,this.settings.sizeX=parseInt(e.sizeX||e.SizeX||this.settings.sizeX),this.settings.sizeY=parseInt(e.sizeY||e.SizeY||this.settings.sizeY),this.settings.statsEnabled=this.parseBoolean(e.statsEnabled||e.StatsEnabled),this.settings.aggregationLevel=e.aggregationLevel||e.AggregationLevel||this.settings.aggregationLevel,this.settings.logLevel=e.logLevel||e.LogLevel||this.settings.logLevel,this.settings.xmrNetworkAddress=e.xmrNetworkAddress||e.XmrNetworkAddress||this.settings.xmrNetworkAddress,this.settings.xmrWebSocketAddress=e.xmrWebSocketAddress||e.XmrWebSocketAddress||this.settings.xmrWebSocketAddress,this.settings.xmrCmsKey=e.xmrCmsKey||e.XmrCmsKey||this.settings.xmrCmsKey,this.settings.preventSleep=this.parseBoolean(e.preventSleep||e.PreventSleep,!0),this.settings.embeddedServerPort=parseInt(e.embeddedServerPort||e.EmbeddedServerPort||this.settings.embeddedServerPort),this.settings.screenshotInterval=parseInt(e.screenshotInterval||e.ScreenshotInterval||this.settings.screenshotInterval),this.settings.downloadStartWindow=e.downloadStartWindow||e.DownloadStartWindow||this.settings.downloadStartWindow,this.settings.downloadEndWindow=e.downloadEndWindow||e.DownloadEndWindow||this.settings.downloadEndWindow,this.settings.licenceCode=e.licenceCode||e.LicenceCode||this.settings.licenceCode,this.settings.isSspEnabled=this.parseBoolean(e.isAdspaceEnabled||e.IsAdspaceEnabled),n!==this.settings.collectInterval&&(t.push(`collectInterval`),this.emit(`interval-changed`,this.settings.collectInterval)),this.emit(`settings-applied`,this.settings,t),r.info(`Applied settings:`,{collectInterval:this.settings.collectInterval,displayName:this.settings.displayName,statsEnabled:this.settings.statsEnabled,changes:t}),{changed:t,settings:this.settings}}parseCollectInterval(e){let t=parseInt(e,10);return isNaN(t)||t<60?300:t>86400?86400:t}parseBoolean(e,t=!1){return e===!0||e===!1?e:e===`1`||e===1?!0:e===`0`||e===0?!1:t}getCollectInterval(){return this.settings.collectInterval}getDisplayName(){return this.settings.displayName}getDisplaySize(){return{width:this.settings.sizeX,height:this.settings.sizeY}}isStatsEnabled(){return this.settings.statsEnabled}getAllSettings(){return{...this.settings}}getSetting(e,t=null){return this.settings[e]===void 0?t:this.settings[e]}isInDownloadWindow(){if(!this.settings.downloadStartWindow||!this.settings.downloadEndWindow||this.settings.downloadStartWindow===`:`||this.settings.downloadEndWindow===`:`)return!0;try{let e=new Date,t=e.getHours()*60+e.getMinutes(),n=this.parseTimeWindow(this.settings.downloadStartWindow),r=this.parseTimeWindow(this.settings.downloadEndWindow);return n>r?t>=n||t<r:t>=n&&t<r}catch(e){return r.warn(`Failed to parse download window:`,e),!0}}parseTimeWindow(e){if(!e||typeof e!=`string`)throw Error(`Invalid time window format`);let t=e.split(`:`);if(t.length!==2)throw Error(`Invalid time window format (expected HH:MM)`);let n=parseInt(t[0],10),r=parseInt(t[1],10);if(isNaN(n)||isNaN(r)||n<0||n>23||r<0||r>59)throw Error(`Invalid time window values`);return n*60+r}getNextDownloadWindow(){if(!this.settings.downloadStartWindow||!this.settings.downloadEndWindow||this.settings.downloadStartWindow===`:`||this.settings.downloadEndWindow===`:`)return null;try{let e=new Date,t=e.getHours()*60+e.getMinutes(),n=this.parseTimeWindow(this.settings.downloadStartWindow),r=new Date(e);return t<n||r.setDate(r.getDate()+1),r.setHours(Math.floor(n/60),n%60,0,0),r}catch(e){return r.warn(`Failed to calculate next download window:`,e),null}}shouldTakeScreenshot(e){return e?(Date.now()-e.getTime())/1e3>=this.settings.screenshotInterval:!0}},a=n.version;export{i as DisplaySettings,a as VERSION};
2
- //# sourceMappingURL=src-C_Lx4lXp.js.map
1
+ import{h as e,v as t}from"./src-CCAyzQUp.js";var n={name:`@xiboplayer/settings`,version:`0.7.23`,description:`CMS settings management and application for xiboplayer`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./manager":`./src/settings.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`},devDependencies:{jsdom:`^29.0.2`,vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`settings`,`configuration`,`display-settings`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/settings`},homepage:`https://xiboplayer.org`},r=t(`DisplaySettings`),i=class extends e{constructor(){super(),this.settings={collectInterval:300,displayName:`Unknown Display`,sizeX:1920,sizeY:1080,statsEnabled:!1,aggregationLevel:`Individual`,logLevel:`error`,xmrNetworkAddress:null,xmrWebSocketAddress:null,xmrCmsKey:null,preventSleep:!0,embeddedServerPort:9696,screenshotInterval:120,downloadStartWindow:null,downloadEndWindow:null,licenceCode:null,isSspEnabled:!1}}applySettings(e){if(!e)return r.warn(`No settings provided`),{changed:[],settings:this.settings};let t=[],n=this.settings.collectInterval;return this.settings.collectInterval=this.parseCollectInterval(e.collectInterval||e.CollectInterval),this.settings.displayName=e.displayName||e.DisplayName||this.settings.displayName,this.settings.sizeX=parseInt(e.sizeX||e.SizeX||this.settings.sizeX),this.settings.sizeY=parseInt(e.sizeY||e.SizeY||this.settings.sizeY),this.settings.statsEnabled=this.parseBoolean(e.statsEnabled||e.StatsEnabled),this.settings.aggregationLevel=e.aggregationLevel||e.AggregationLevel||this.settings.aggregationLevel,this.settings.logLevel=e.logLevel||e.LogLevel||this.settings.logLevel,this.settings.xmrNetworkAddress=e.xmrNetworkAddress||e.XmrNetworkAddress||this.settings.xmrNetworkAddress,this.settings.xmrWebSocketAddress=e.xmrWebSocketAddress||e.XmrWebSocketAddress||this.settings.xmrWebSocketAddress,this.settings.xmrCmsKey=e.xmrCmsKey||e.XmrCmsKey||this.settings.xmrCmsKey,this.settings.preventSleep=this.parseBoolean(e.preventSleep||e.PreventSleep,!0),this.settings.embeddedServerPort=parseInt(e.embeddedServerPort||e.EmbeddedServerPort||this.settings.embeddedServerPort),this.settings.screenshotInterval=parseInt(e.screenshotInterval||e.ScreenshotInterval||this.settings.screenshotInterval),this.settings.downloadStartWindow=e.downloadStartWindow||e.DownloadStartWindow||this.settings.downloadStartWindow,this.settings.downloadEndWindow=e.downloadEndWindow||e.DownloadEndWindow||this.settings.downloadEndWindow,this.settings.licenceCode=e.licenceCode||e.LicenceCode||this.settings.licenceCode,this.settings.isSspEnabled=this.parseBoolean(e.isAdspaceEnabled||e.IsAdspaceEnabled),n!==this.settings.collectInterval&&(t.push(`collectInterval`),this.emit(`interval-changed`,this.settings.collectInterval)),this.emit(`settings-applied`,this.settings,t),r.info(`Applied settings:`,{collectInterval:this.settings.collectInterval,displayName:this.settings.displayName,statsEnabled:this.settings.statsEnabled,changes:t}),{changed:t,settings:this.settings}}parseCollectInterval(e){let t=parseInt(e,10);return isNaN(t)||t<60?300:t>86400?86400:t}parseBoolean(e,t=!1){return e===!0||e===!1?e:e===`1`||e===1?!0:e===`0`||e===0?!1:t}getCollectInterval(){return this.settings.collectInterval}getDisplayName(){return this.settings.displayName}getDisplaySize(){return{width:this.settings.sizeX,height:this.settings.sizeY}}isStatsEnabled(){return this.settings.statsEnabled}getAllSettings(){return{...this.settings}}getSetting(e,t=null){return this.settings[e]===void 0?t:this.settings[e]}isInDownloadWindow(){if(!this.settings.downloadStartWindow||!this.settings.downloadEndWindow||this.settings.downloadStartWindow===`:`||this.settings.downloadEndWindow===`:`)return!0;try{let e=new Date,t=e.getHours()*60+e.getMinutes(),n=this.parseTimeWindow(this.settings.downloadStartWindow),r=this.parseTimeWindow(this.settings.downloadEndWindow);return n>r?t>=n||t<r:t>=n&&t<r}catch(e){return r.warn(`Failed to parse download window:`,e),!0}}parseTimeWindow(e){if(!e||typeof e!=`string`)throw Error(`Invalid time window format`);let t=e.split(`:`);if(t.length!==2)throw Error(`Invalid time window format (expected HH:MM)`);let n=parseInt(t[0],10),r=parseInt(t[1],10);if(isNaN(n)||isNaN(r)||n<0||n>23||r<0||r>59)throw Error(`Invalid time window values`);return n*60+r}getNextDownloadWindow(){if(!this.settings.downloadStartWindow||!this.settings.downloadEndWindow||this.settings.downloadStartWindow===`:`||this.settings.downloadEndWindow===`:`)return null;try{let e=new Date,t=e.getHours()*60+e.getMinutes(),n=this.parseTimeWindow(this.settings.downloadStartWindow),r=new Date(e);return t<n||r.setDate(r.getDate()+1),r.setHours(Math.floor(n/60),n%60,0,0),r}catch(e){return r.warn(`Failed to calculate next download window:`,e),null}}shouldTakeScreenshot(e){return e?(Date.now()-e.getTime())/1e3>=this.settings.screenshotInterval:!0}},a=n.version;export{i as DisplaySettings,a as VERSION};
2
+ //# sourceMappingURL=src-CtjjclS4.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"src-C_Lx4lXp.js","names":["pkg"],"sources":["../../../settings/package.json","../../../settings/src/settings.js","../../../settings/src/index.js"],"sourcesContent":["{\n \"name\": \"@xiboplayer/settings\",\n \"version\": \"0.7.21\",\n \"description\": \"CMS settings management and application for xiboplayer\",\n \"type\": \"module\",\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./manager\": \"./src/settings.js\"\n },\n \"scripts\": {\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@xiboplayer/utils\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"jsdom\": \"^29.0.2\",\n \"vitest\": \"^4.1.2\"\n },\n \"keywords\": [\n \"xibo\",\n \"digital-signage\",\n \"settings\",\n \"configuration\",\n \"display-settings\"\n ],\n \"author\": \"Pau Aliagas <linuxnow@gmail.com>\",\n \"license\": \"AGPL-3.0-or-later\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/xibo-players/xiboplayer.git\",\n \"directory\": \"packages/settings\"\n },\n \"homepage\": \"https://xiboplayer.org\"\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * DisplaySettings - CMS display settings management\n *\n * Parses and applies configuration from RegisterDisplay response.\n * Based on upstream electron-player implementation.\n *\n * Architecture:\n * ┌─────────────────────────────────────────────────────┐\n * │ PlayerCore │\n * │ - Receives RegisterDisplay response │\n * │ - Passes to DisplaySettings.applySettings() │\n * └─────────────────────────────────────────────────────┘\n * ↓\n * ┌─────────────────────────────────────────────────────┐\n * │ DisplaySettings (this module) │\n * │ - Parse all CMS settings │\n * │ - Validate and normalize values │\n * │ - Apply collection interval │\n * │ - Check download windows │\n * │ - Handle screenshot requests │\n * │ - Emit events on changes │\n * └─────────────────────────────────────────────────────┘\n * ↓\n * ┌─────────────────────────────────────────────────────┐\n * │ Platform Layer (PWA/Electron/Mobile) │\n * │ - Listen for setting change events │\n * │ - Update UI with display name │\n * │ - Handle screenshot requests │\n * │ - Respect download windows │\n * └─────────────────────────────────────────────────────┘\n *\n * Usage:\n * const settings = new DisplaySettings();\n * settings.applySettings(regResult.settings);\n *\n * // Get settings\n * const collectInterval = settings.getCollectInterval();\n * const canDownload = settings.isInDownloadWindow();\n *\n * // Listen for changes\n * settings.on('interval-changed', (newInterval) => { ... });\n */\n\nimport { EventEmitter, createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('DisplaySettings');\n\nexport class DisplaySettings extends EventEmitter {\n constructor() {\n super();\n\n // Current settings (with defaults)\n this.settings = {\n // Collection\n collectInterval: 300, // seconds (5 minutes default)\n\n // Display info\n displayName: 'Unknown Display',\n sizeX: 1920,\n sizeY: 1080,\n\n // Stats\n statsEnabled: false,\n aggregationLevel: 'Individual', // or 'Aggregate'\n\n // Logging\n logLevel: 'error', // 'error', 'audit', 'info', 'debug'\n\n // XMR\n xmrNetworkAddress: null,\n xmrWebSocketAddress: null,\n xmrCmsKey: null,\n\n // Features\n preventSleep: true,\n embeddedServerPort: 9696,\n screenshotInterval: 120, // seconds\n\n // Download windows\n downloadStartWindow: null,\n downloadEndWindow: null,\n\n // License\n licenceCode: null,\n\n // SSP (ad space)\n isSspEnabled: false,\n };\n }\n\n /**\n * Apply settings from RegisterDisplay response\n * @param {Object} settings - Raw settings from CMS\n * @returns {Object} Applied settings with changes\n */\n applySettings(settings) {\n if (!settings) {\n log.warn('No settings provided');\n return { changed: [], settings: this.settings };\n }\n\n const changes = [];\n const oldInterval = this.settings.collectInterval;\n\n // Parse all settings with defaults\n // Handle both lowercase and CamelCase (uppercase first letter)\n this.settings.collectInterval = this.parseCollectInterval(settings.collectInterval || settings.CollectInterval);\n this.settings.displayName = settings.displayName || settings.DisplayName || this.settings.displayName;\n this.settings.sizeX = parseInt(settings.sizeX || settings.SizeX || this.settings.sizeX);\n this.settings.sizeY = parseInt(settings.sizeY || settings.SizeY || this.settings.sizeY);\n\n // Stats\n this.settings.statsEnabled = this.parseBoolean(settings.statsEnabled || settings.StatsEnabled);\n this.settings.aggregationLevel = settings.aggregationLevel || settings.AggregationLevel || this.settings.aggregationLevel;\n\n // Logging\n this.settings.logLevel = settings.logLevel || settings.LogLevel || this.settings.logLevel;\n\n // XMR\n this.settings.xmrNetworkAddress = settings.xmrNetworkAddress || settings.XmrNetworkAddress || this.settings.xmrNetworkAddress;\n this.settings.xmrWebSocketAddress = settings.xmrWebSocketAddress || settings.XmrWebSocketAddress || this.settings.xmrWebSocketAddress;\n this.settings.xmrCmsKey = settings.xmrCmsKey || settings.XmrCmsKey || this.settings.xmrCmsKey;\n\n // Features\n this.settings.preventSleep = this.parseBoolean(settings.preventSleep || settings.PreventSleep, true);\n this.settings.embeddedServerPort = parseInt(settings.embeddedServerPort || settings.EmbeddedServerPort || this.settings.embeddedServerPort);\n this.settings.screenshotInterval = parseInt(settings.screenshotInterval || settings.ScreenshotInterval || this.settings.screenshotInterval);\n\n // Download windows\n this.settings.downloadStartWindow = settings.downloadStartWindow || settings.DownloadStartWindow || this.settings.downloadStartWindow;\n this.settings.downloadEndWindow = settings.downloadEndWindow || settings.DownloadEndWindow || this.settings.downloadEndWindow;\n\n // License\n this.settings.licenceCode = settings.licenceCode || settings.LicenceCode || this.settings.licenceCode;\n\n // SSP\n this.settings.isSspEnabled = this.parseBoolean(settings.isAdspaceEnabled || settings.IsAdspaceEnabled);\n\n // Detect changes\n if (oldInterval !== this.settings.collectInterval) {\n changes.push('collectInterval');\n this.emit('interval-changed', this.settings.collectInterval);\n }\n\n // Emit generic settings-applied event\n this.emit('settings-applied', this.settings, changes);\n\n log.info('Applied settings:', {\n collectInterval: this.settings.collectInterval,\n displayName: this.settings.displayName,\n statsEnabled: this.settings.statsEnabled,\n changes\n });\n\n return { changed: changes, settings: this.settings };\n }\n\n /**\n * Parse collection interval (seconds)\n * @param {*} value - Raw value from CMS\n * @returns {number} Collection interval in seconds\n */\n parseCollectInterval(value) {\n const interval = parseInt(value, 10);\n\n // Validate range (minimum 60s, maximum 86400s = 24h)\n if (isNaN(interval) || interval < 60) {\n return 300; // 5 minutes default\n }\n\n if (interval > 86400) {\n return 86400; // 24 hours max\n }\n\n return interval;\n }\n\n /**\n * Parse boolean setting\n * @param {*} value - Raw value from CMS (string '1' or '0', or boolean)\n * @param {boolean} defaultValue - Default if not set\n * @returns {boolean}\n */\n parseBoolean(value, defaultValue = false) {\n if (value === true || value === false) {\n return value;\n }\n\n if (value === '1' || value === 1) {\n return true;\n }\n\n if (value === '0' || value === 0) {\n return false;\n }\n\n return defaultValue;\n }\n\n /**\n * Get collection interval in seconds\n * @returns {number}\n */\n getCollectInterval() {\n return this.settings.collectInterval;\n }\n\n /**\n * Get display name\n * @returns {string}\n */\n getDisplayName() {\n return this.settings.displayName;\n }\n\n /**\n * Get display size\n * @returns {{ width: number, height: number }}\n */\n getDisplaySize() {\n return {\n width: this.settings.sizeX,\n height: this.settings.sizeY\n };\n }\n\n /**\n * Check if stats are enabled\n * @returns {boolean}\n */\n isStatsEnabled() {\n return this.settings.statsEnabled;\n }\n\n /**\n * Get all settings\n * @returns {Object}\n */\n getAllSettings() {\n return { ...this.settings };\n }\n\n /**\n * Get a specific setting by key\n * @param {string} key - Setting key\n * @param {*} defaultValue - Default value if not set\n * @returns {*}\n */\n getSetting(key, defaultValue = null) {\n return this.settings[key] !== undefined ? this.settings[key] : defaultValue;\n }\n\n /**\n * Check if current time is within download window\n * @returns {boolean}\n */\n isInDownloadWindow() {\n // If no download window configured, always allow\n // CMS sends \":\" when unconfigured, treat as empty\n if (!this.settings.downloadStartWindow || !this.settings.downloadEndWindow ||\n this.settings.downloadStartWindow === ':' || this.settings.downloadEndWindow === ':') {\n return true;\n }\n\n try {\n const now = new Date();\n const currentTime = now.getHours() * 60 + now.getMinutes();\n\n const start = this.parseTimeWindow(this.settings.downloadStartWindow);\n const end = this.parseTimeWindow(this.settings.downloadEndWindow);\n\n // Handle overnight window (e.g., 22:00 - 06:00)\n if (start > end) {\n // Overnight: allow if AFTER start OR BEFORE end\n return currentTime >= start || currentTime < end;\n } else {\n // Same day: allow if AFTER start AND BEFORE end\n return currentTime >= start && currentTime < end;\n }\n } catch (error) {\n log.warn('Failed to parse download window:', error);\n return true; // Allow downloads if parsing fails\n }\n }\n\n /**\n * Parse time window string to minutes since midnight\n * @param {string} timeStr - Time string (e.g., \"14:30\", \"22:00\")\n * @returns {number} Minutes since midnight\n */\n parseTimeWindow(timeStr) {\n if (!timeStr || typeof timeStr !== 'string') {\n throw new Error('Invalid time window format');\n }\n\n const parts = timeStr.split(':');\n if (parts.length !== 2) {\n throw new Error('Invalid time window format (expected HH:MM)');\n }\n\n const hours = parseInt(parts[0], 10);\n const minutes = parseInt(parts[1], 10);\n\n if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {\n throw new Error('Invalid time window values');\n }\n\n return hours * 60 + minutes;\n }\n\n /**\n * Get next download window start time\n * @returns {Date|null} Next window start, or null if always allowed\n */\n getNextDownloadWindow() {\n if (!this.settings.downloadStartWindow || !this.settings.downloadEndWindow ||\n this.settings.downloadStartWindow === ':' || this.settings.downloadEndWindow === ':') {\n return null;\n }\n\n try {\n const now = new Date();\n const currentTime = now.getHours() * 60 + now.getMinutes();\n const start = this.parseTimeWindow(this.settings.downloadStartWindow);\n\n const nextWindow = new Date(now);\n\n if (currentTime < start) {\n // Window is later today\n nextWindow.setHours(Math.floor(start / 60), start % 60, 0, 0);\n } else {\n // Window is tomorrow\n nextWindow.setDate(nextWindow.getDate() + 1);\n nextWindow.setHours(Math.floor(start / 60), start % 60, 0, 0);\n }\n\n return nextWindow;\n } catch (error) {\n log.warn('Failed to calculate next download window:', error);\n return null;\n }\n }\n\n /**\n * Check if screenshot interval has elapsed\n * @param {Date} lastScreenshot - Last screenshot timestamp\n * @returns {boolean}\n */\n shouldTakeScreenshot(lastScreenshot) {\n if (!lastScreenshot) {\n return true;\n }\n\n const elapsed = (Date.now() - lastScreenshot.getTime()) / 1000;\n return elapsed >= this.settings.screenshotInterval;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n// @xiboplayer/settings - CMS settings management\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\n\n/**\n * Settings manager for xiboplayer\n * @module @xiboplayer/settings\n */\nexport { DisplaySettings } from './settings.js';\n"],"mappings":"ywBC+CM,EAAM,EAAa,kBAAkB,CAE9B,EAAb,cAAqC,CAAa,CAChD,aAAc,CACZ,OAAO,CAGP,KAAK,SAAW,CAEd,gBAAiB,IAGjB,YAAa,kBACb,MAAO,KACP,MAAO,KAGP,aAAc,GACd,iBAAkB,aAGlB,SAAU,QAGV,kBAAmB,KACnB,oBAAqB,KACrB,UAAW,KAGX,aAAc,GACd,mBAAoB,KACpB,mBAAoB,IAGpB,oBAAqB,KACrB,kBAAmB,KAGnB,YAAa,KAGb,aAAc,GACf,CAQH,cAAc,EAAU,CACtB,GAAI,CAAC,EAEH,OADA,EAAI,KAAK,uBAAuB,CACzB,CAAE,QAAS,EAAE,CAAE,SAAU,KAAK,SAAU,CAGjD,IAAM,EAAU,EAAE,CACZ,EAAc,KAAK,SAAS,gBAoDlC,MAhDA,MAAK,SAAS,gBAAkB,KAAK,qBAAqB,EAAS,iBAAmB,EAAS,gBAAgB,CAC/G,KAAK,SAAS,YAAc,EAAS,aAAe,EAAS,aAAe,KAAK,SAAS,YAC1F,KAAK,SAAS,MAAQ,SAAS,EAAS,OAAS,EAAS,OAAS,KAAK,SAAS,MAAM,CACvF,KAAK,SAAS,MAAQ,SAAS,EAAS,OAAS,EAAS,OAAS,KAAK,SAAS,MAAM,CAGvF,KAAK,SAAS,aAAe,KAAK,aAAa,EAAS,cAA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,GAAI,MAAM,EAAM,EAAI,MAAM,EAAQ,EAAI,EAAQ,GAAK,EAAQ,IAAM,EAAU,GAAK,EAAU,GACxF,MAAU,MAAM,6BAA6B,CAG/C,OAAO,EAAQ,GAAK,EAOtB,uBAAwB,CACtB,GAAI,CAAC,KAAK,SAAS,qBAAuB,CAAC,KAAK,SAAS,mBACrD,KAAK,SAAS,sBAAwB,KAAO,KAAK,SAAS,oBAAsB,IACnF,OAAO,KAGT,GAAI,CACF,IAAM,EAAM,IAAI,KACV,EAAc,EAAI,UAAU,CAAG,GAAK,EAAI,YAAY,CACpD,EAAQ,KAAK,gBAAgB,KAAK,SAAS,oBAAoB,CAE/D,EAAa,IAAI,KAAK,EAAI,CAWhC,OATI,EAAc,GAKhB,EAAW,QAAQ,EAAW,SAAS,CAAG,EAAE,CAH5C,EAAW,SAAS,KAAK,MAAM,EAAQ,GAAG,CAAE,EAAQ,GAAI,EAAG,EAAE,CAOxD,QACA,EAAO,CAEd,OADA,EAAI,KAAK,4CAA6C,EAAM,CACrD,MASX,qBAAqB,EAAgB,CAMnC,OALK,GAIY,KAAK,KAAK,CAAG,EAAe,SAAS,EAAI,KACxC,KAAK,SAAS,mBAJvB,KC5VA,EAAUA,EAAI"}
1
+ {"version":3,"file":"src-CtjjclS4.js","names":["pkg"],"sources":["../../../settings/package.json","../../../settings/src/settings.js","../../../settings/src/index.js"],"sourcesContent":["{\n \"name\": \"@xiboplayer/settings\",\n \"version\": \"0.7.23\",\n \"description\": \"CMS settings management and application for xiboplayer\",\n \"type\": \"module\",\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./manager\": \"./src/settings.js\"\n },\n \"scripts\": {\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@xiboplayer/utils\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"jsdom\": \"^29.0.2\",\n \"vitest\": \"^4.1.2\"\n },\n \"keywords\": [\n \"xibo\",\n \"digital-signage\",\n \"settings\",\n \"configuration\",\n \"display-settings\"\n ],\n \"author\": \"Pau Aliagas <linuxnow@gmail.com>\",\n \"license\": \"AGPL-3.0-or-later\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/xibo-players/xiboplayer.git\",\n \"directory\": \"packages/settings\"\n },\n \"homepage\": \"https://xiboplayer.org\"\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * DisplaySettings - CMS display settings management\n *\n * Parses and applies configuration from RegisterDisplay response.\n * Based on upstream electron-player implementation.\n *\n * Architecture:\n * ┌─────────────────────────────────────────────────────┐\n * │ PlayerCore │\n * │ - Receives RegisterDisplay response │\n * │ - Passes to DisplaySettings.applySettings() │\n * └─────────────────────────────────────────────────────┘\n * ↓\n * ┌─────────────────────────────────────────────────────┐\n * │ DisplaySettings (this module) │\n * │ - Parse all CMS settings │\n * │ - Validate and normalize values │\n * │ - Apply collection interval │\n * │ - Check download windows │\n * │ - Handle screenshot requests │\n * │ - Emit events on changes │\n * └─────────────────────────────────────────────────────┘\n * ↓\n * ┌─────────────────────────────────────────────────────┐\n * │ Platform Layer (PWA/Electron/Mobile) │\n * │ - Listen for setting change events │\n * │ - Update UI with display name │\n * │ - Handle screenshot requests │\n * │ - Respect download windows │\n * └─────────────────────────────────────────────────────┘\n *\n * Usage:\n * const settings = new DisplaySettings();\n * settings.applySettings(regResult.settings);\n *\n * // Get settings\n * const collectInterval = settings.getCollectInterval();\n * const canDownload = settings.isInDownloadWindow();\n *\n * // Listen for changes\n * settings.on('interval-changed', (newInterval) => { ... });\n */\n\nimport { EventEmitter, createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('DisplaySettings');\n\nexport class DisplaySettings extends EventEmitter {\n constructor() {\n super();\n\n // Current settings (with defaults)\n this.settings = {\n // Collection\n collectInterval: 300, // seconds (5 minutes default)\n\n // Display info\n displayName: 'Unknown Display',\n sizeX: 1920,\n sizeY: 1080,\n\n // Stats\n statsEnabled: false,\n aggregationLevel: 'Individual', // or 'Aggregate'\n\n // Logging\n logLevel: 'error', // 'error', 'audit', 'info', 'debug'\n\n // XMR\n xmrNetworkAddress: null,\n xmrWebSocketAddress: null,\n xmrCmsKey: null,\n\n // Features\n preventSleep: true,\n embeddedServerPort: 9696,\n screenshotInterval: 120, // seconds\n\n // Download windows\n downloadStartWindow: null,\n downloadEndWindow: null,\n\n // License\n licenceCode: null,\n\n // SSP (ad space)\n isSspEnabled: false,\n };\n }\n\n /**\n * Apply settings from RegisterDisplay response\n * @param {Object} settings - Raw settings from CMS\n * @returns {Object} Applied settings with changes\n */\n applySettings(settings) {\n if (!settings) {\n log.warn('No settings provided');\n return { changed: [], settings: this.settings };\n }\n\n const changes = [];\n const oldInterval = this.settings.collectInterval;\n\n // Parse all settings with defaults\n // Handle both lowercase and CamelCase (uppercase first letter)\n this.settings.collectInterval = this.parseCollectInterval(settings.collectInterval || settings.CollectInterval);\n this.settings.displayName = settings.displayName || settings.DisplayName || this.settings.displayName;\n this.settings.sizeX = parseInt(settings.sizeX || settings.SizeX || this.settings.sizeX);\n this.settings.sizeY = parseInt(settings.sizeY || settings.SizeY || this.settings.sizeY);\n\n // Stats\n this.settings.statsEnabled = this.parseBoolean(settings.statsEnabled || settings.StatsEnabled);\n this.settings.aggregationLevel = settings.aggregationLevel || settings.AggregationLevel || this.settings.aggregationLevel;\n\n // Logging\n this.settings.logLevel = settings.logLevel || settings.LogLevel || this.settings.logLevel;\n\n // XMR\n this.settings.xmrNetworkAddress = settings.xmrNetworkAddress || settings.XmrNetworkAddress || this.settings.xmrNetworkAddress;\n this.settings.xmrWebSocketAddress = settings.xmrWebSocketAddress || settings.XmrWebSocketAddress || this.settings.xmrWebSocketAddress;\n this.settings.xmrCmsKey = settings.xmrCmsKey || settings.XmrCmsKey || this.settings.xmrCmsKey;\n\n // Features\n this.settings.preventSleep = this.parseBoolean(settings.preventSleep || settings.PreventSleep, true);\n this.settings.embeddedServerPort = parseInt(settings.embeddedServerPort || settings.EmbeddedServerPort || this.settings.embeddedServerPort);\n this.settings.screenshotInterval = parseInt(settings.screenshotInterval || settings.ScreenshotInterval || this.settings.screenshotInterval);\n\n // Download windows\n this.settings.downloadStartWindow = settings.downloadStartWindow || settings.DownloadStartWindow || this.settings.downloadStartWindow;\n this.settings.downloadEndWindow = settings.downloadEndWindow || settings.DownloadEndWindow || this.settings.downloadEndWindow;\n\n // License\n this.settings.licenceCode = settings.licenceCode || settings.LicenceCode || this.settings.licenceCode;\n\n // SSP\n this.settings.isSspEnabled = this.parseBoolean(settings.isAdspaceEnabled || settings.IsAdspaceEnabled);\n\n // Detect changes\n if (oldInterval !== this.settings.collectInterval) {\n changes.push('collectInterval');\n this.emit('interval-changed', this.settings.collectInterval);\n }\n\n // Emit generic settings-applied event\n this.emit('settings-applied', this.settings, changes);\n\n log.info('Applied settings:', {\n collectInterval: this.settings.collectInterval,\n displayName: this.settings.displayName,\n statsEnabled: this.settings.statsEnabled,\n changes\n });\n\n return { changed: changes, settings: this.settings };\n }\n\n /**\n * Parse collection interval (seconds)\n * @param {*} value - Raw value from CMS\n * @returns {number} Collection interval in seconds\n */\n parseCollectInterval(value) {\n const interval = parseInt(value, 10);\n\n // Validate range (minimum 60s, maximum 86400s = 24h)\n if (isNaN(interval) || interval < 60) {\n return 300; // 5 minutes default\n }\n\n if (interval > 86400) {\n return 86400; // 24 hours max\n }\n\n return interval;\n }\n\n /**\n * Parse boolean setting\n * @param {*} value - Raw value from CMS (string '1' or '0', or boolean)\n * @param {boolean} defaultValue - Default if not set\n * @returns {boolean}\n */\n parseBoolean(value, defaultValue = false) {\n if (value === true || value === false) {\n return value;\n }\n\n if (value === '1' || value === 1) {\n return true;\n }\n\n if (value === '0' || value === 0) {\n return false;\n }\n\n return defaultValue;\n }\n\n /**\n * Get collection interval in seconds\n * @returns {number}\n */\n getCollectInterval() {\n return this.settings.collectInterval;\n }\n\n /**\n * Get display name\n * @returns {string}\n */\n getDisplayName() {\n return this.settings.displayName;\n }\n\n /**\n * Get display size\n * @returns {{ width: number, height: number }}\n */\n getDisplaySize() {\n return {\n width: this.settings.sizeX,\n height: this.settings.sizeY\n };\n }\n\n /**\n * Check if stats are enabled\n * @returns {boolean}\n */\n isStatsEnabled() {\n return this.settings.statsEnabled;\n }\n\n /**\n * Get all settings\n * @returns {Object}\n */\n getAllSettings() {\n return { ...this.settings };\n }\n\n /**\n * Get a specific setting by key\n * @param {string} key - Setting key\n * @param {*} defaultValue - Default value if not set\n * @returns {*}\n */\n getSetting(key, defaultValue = null) {\n return this.settings[key] !== undefined ? this.settings[key] : defaultValue;\n }\n\n /**\n * Check if current time is within download window\n * @returns {boolean}\n */\n isInDownloadWindow() {\n // If no download window configured, always allow\n // CMS sends \":\" when unconfigured, treat as empty\n if (!this.settings.downloadStartWindow || !this.settings.downloadEndWindow ||\n this.settings.downloadStartWindow === ':' || this.settings.downloadEndWindow === ':') {\n return true;\n }\n\n try {\n const now = new Date();\n const currentTime = now.getHours() * 60 + now.getMinutes();\n\n const start = this.parseTimeWindow(this.settings.downloadStartWindow);\n const end = this.parseTimeWindow(this.settings.downloadEndWindow);\n\n // Handle overnight window (e.g., 22:00 - 06:00)\n if (start > end) {\n // Overnight: allow if AFTER start OR BEFORE end\n return currentTime >= start || currentTime < end;\n } else {\n // Same day: allow if AFTER start AND BEFORE end\n return currentTime >= start && currentTime < end;\n }\n } catch (error) {\n log.warn('Failed to parse download window:', error);\n return true; // Allow downloads if parsing fails\n }\n }\n\n /**\n * Parse time window string to minutes since midnight\n * @param {string} timeStr - Time string (e.g., \"14:30\", \"22:00\")\n * @returns {number} Minutes since midnight\n */\n parseTimeWindow(timeStr) {\n if (!timeStr || typeof timeStr !== 'string') {\n throw new Error('Invalid time window format');\n }\n\n const parts = timeStr.split(':');\n if (parts.length !== 2) {\n throw new Error('Invalid time window format (expected HH:MM)');\n }\n\n const hours = parseInt(parts[0], 10);\n const minutes = parseInt(parts[1], 10);\n\n if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {\n throw new Error('Invalid time window values');\n }\n\n return hours * 60 + minutes;\n }\n\n /**\n * Get next download window start time\n * @returns {Date|null} Next window start, or null if always allowed\n */\n getNextDownloadWindow() {\n if (!this.settings.downloadStartWindow || !this.settings.downloadEndWindow ||\n this.settings.downloadStartWindow === ':' || this.settings.downloadEndWindow === ':') {\n return null;\n }\n\n try {\n const now = new Date();\n const currentTime = now.getHours() * 60 + now.getMinutes();\n const start = this.parseTimeWindow(this.settings.downloadStartWindow);\n\n const nextWindow = new Date(now);\n\n if (currentTime < start) {\n // Window is later today\n nextWindow.setHours(Math.floor(start / 60), start % 60, 0, 0);\n } else {\n // Window is tomorrow\n nextWindow.setDate(nextWindow.getDate() + 1);\n nextWindow.setHours(Math.floor(start / 60), start % 60, 0, 0);\n }\n\n return nextWindow;\n } catch (error) {\n log.warn('Failed to calculate next download window:', error);\n return null;\n }\n }\n\n /**\n * Check if screenshot interval has elapsed\n * @param {Date} lastScreenshot - Last screenshot timestamp\n * @returns {boolean}\n */\n shouldTakeScreenshot(lastScreenshot) {\n if (!lastScreenshot) {\n return true;\n }\n\n const elapsed = (Date.now() - lastScreenshot.getTime()) / 1000;\n return elapsed >= this.settings.screenshotInterval;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n// @xiboplayer/settings - CMS settings management\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\n\n/**\n * Settings manager for xiboplayer\n * @module @xiboplayer/settings\n */\nexport { DisplaySettings } from './settings.js';\n"],"mappings":"ywBC+CM,EAAM,EAAa,kBAAkB,CAE9B,EAAb,cAAqC,CAAa,CAChD,aAAc,CACZ,OAAO,CAGP,KAAK,SAAW,CAEd,gBAAiB,IAGjB,YAAa,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,MAAM,EAAQ,GAAG,CAAE,EAAQ,GAAI,EAAG,EAAE,CAOxD,QACA,EAAO,CAEd,OADA,EAAI,KAAK,4CAA6C,EAAM,CACrD,MASX,qBAAqB,EAAgB,CAMnC,OALK,GAIY,KAAK,KAAK,CAAG,EAAe,SAAS,EAAI,KACxC,KAAK,SAAS,mBAJvB,KC5VA,EAAUA,EAAI"}
@@ -0,0 +1,2 @@
1
+ import{t as e,v as t}from"./src-CCAyzQUp.js";var n={name:`@xiboplayer/cache`,version:`0.7.23`,description:`Offline caching and download management with parallel chunk downloads`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./cache":`./src/cache.js`,"./store-client":`./src/store-client.js`,"./download-manager":`./src/download-manager.js`,"./cache-analyzer":`./src/cache-analyzer.js`,"./widget-html":`./src/widget-html.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`,"spark-md5":`^3.0.2`},devDependencies:{jsdom:`^29.0.2`,vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`cache`,`offline`,`download`,`indexeddb`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/cache`},homepage:`https://xiboplayer.org`},r=t(`Cache`),i=class{constructor(){this.dependants=new Map}addDependant(e,t){let n=String(e);this.dependants.has(n)||this.dependants.set(n,new Set),this.dependants.get(n).add(String(t))}removeLayoutDependants(e){let t=String(e),n=[];for(let[e,r]of this.dependants)r.delete(t),r.size===0&&(this.dependants.delete(e),n.push(e));return n.length>0&&r.info(`${n.length} media files orphaned after layout ${e} removed:`,n),n}isMediaReferenced(e){let t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){this.dependants.clear()}},a=new i,o=t(`StoreClient`),s=class{async has(e,t){try{let n=await fetch(`/store/${e}/${t}`,{method:`HEAD`});if(n.status===204)return!1;if(n.status===200)return n.headers.get(`X-Store-Complete`)!==`false`;if(n.status===404)return!1;let r=Error(`Store error: ${n.status}`);throw r.status=n.status,o.warn(`has(${e}/${t}): unexpected status ${n.status}`),r}catch(n){throw n.status||n.name===`AbortError`||n.name===`TimeoutError`||o.warn(`has(${e}/${t}): network error — ${n.message}`),n}}async get(e,t){try{let n=await fetch(`/store/${e}/${t}`);if(n.status===204||n.status===404)return n.body?.cancel(),null;if(!n.ok)throw n.body?.cancel(),Error(`Failed to get file: ${n.status}`);return await n.blob()}catch(e){return o.error(`get error:`,e.message),null}}async put(e,t,n,r=`application/octet-stream`){try{let i=await fetch(`/store/${e}/${t}`,{method:`PUT`,headers:{"Content-Type":r},body:n});return i.body?.cancel(),i.ok}catch(e){return o.error(`put error:`,e.message),!1}}async remove(e){try{let t=await(await fetch(`/store/delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({files:e})})).json();return{deleted:t.deleted||0,total:t.total||e.length}}catch(t){return o.error(`remove error:`,t.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch(`/store/list`)).json()).files||[]}catch(e){return o.error(`list error:`,e.message),[]}}},c={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function l(e){return c[e]||c.media}var u=t(`Download`),d=6,f=50*1024*1024,p=3,m=100*1024*1024,h=2,g=6e5,_=15e3;function v(e){return{mp4:`video/mp4`,webm:`video/webm`,mp3:`audio/mpeg`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,svg:`image/svg+xml`,webp:`image/webp`,css:`text/css`,js:`application/javascript`,ttf:`font/ttf`,otf:`font/otf`,woff:`font/woff`,woff2:`font/woff2`,xml:`application/xml`,xlf:`application/xml`}[(e.path||e.code||``).split(`.`).pop()?.split(`?`)[0]?.toLowerCase()]||`application/octet-stream`}var y={normal:0,layout:1,high:2,urgent:3},b=Symbol(`BARRIER`);function x(e){try{let t=new URL(e,`http://localhost`),n=t.searchParams.get(`X-Amz-Date`),r=t.searchParams.get(`X-Amz-Expires`);if(n&&r){let e=n.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/,`$1-$2-$3T$4:$5:$6Z`),t=new Date(e).getTime()/1e3;return isNaN(t)?1/0:t+parseInt(r,10)}return 1/0}catch{return 1/0}}function S(e,t=30){let n=x(e);return n===1/0?!1:Date.now()/1e3>=n-t}var C=class{constructor(e,t={}){this.fileInfo=e,this.chunkIndex=t.chunkIndex??null,this.rangeStart=t.rangeStart??null,this.rangeEnd=t.rangeEnd??null,this.state=`pending`,this.blob=null,this._parentFile=null,this._priority=y.normal,this._typeConfig=l(e.type)}getUrl(){let e=this.fileInfo.path;if(S(e))throw Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){this.state=`downloading`;let e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e[`X-Store-Chunk-Index`]=String(this.chunkIndex),this._parentFile&&(e[`X-Store-Num-Chunks`]=String(this._parentFile.totalChunks),e[`X-Store-Chunk-Size`]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e[`X-Store-MD5`]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e[`X-Cache-TTL`]=String(this.fileInfo.updateInterval)),this.fileInfo.cmsDownloadUrl&&(e[`X-Cms-Download-Url`]=this.fileInfo.cmsDownloadUrl);let t=this._typeConfig.maxRetries;for(let n=1;n<=t;n++){let r=new AbortController,i=setTimeout(()=>r.abort(),g);try{let t=this.getUrl(),n={signal:r.signal};Object.keys(e).length>0&&(n.headers=e);let i=await fetch(t,n);if(!i.ok&&i.status!==206)throw Error(`Fetch failed: ${i.status}`);return this.blob=await i.blob(),this.state=`complete`,this.blob}catch(e){let i=r.signal.aborted?`Timeout after ${g/1e3}s`:e.message;if(n<t){let e=this._typeConfig.retryDelays?.[n-1]??this._typeConfig.retryDelayMs*n,r=this.chunkIndex==null?``:` chunk ${this.chunkIndex}`;u.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${r} attempt ${n}/${t} failed: ${i}. Retrying in ${e/1e3}s...`),await new Promise(t=>setTimeout(t,e))}else throw this.state=`failed`,r.signal.aborted?Error(i):e}finally{clearTimeout(i)}}}},w=class{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state=`pending`,this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType=`application/octet-stream`,this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t}),this._promise.catch(()=>{})}getUrl(){let e=this.fileInfo.path;if(S(e))throw Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state=`preparing`;let{id:t,type:n,size:r}=this.fileInfo;u.info(`[FileDownload] Starting:`,`${n}/${t}`),this.totalBytes=r&&r>0?parseInt(r):0,this._contentType=v(this.fileInfo);let i=l(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!i){let e=this.getUrl(),t=new AbortController,n=setTimeout(()=>t.abort(),_);try{let n=await fetch(e,{method:`HEAD`,signal:t.signal});n.ok&&(this.totalBytes=parseInt(n.headers.get(`Content-Length`)||`0`),this._contentType=n.headers.get(`Content-Type`)||this._contentType)}finally{clearTimeout(n)}}u.info(`[FileDownload] File size:`,(this.totalBytes/1024/1024).toFixed(1),`MB`);let a=this.options.chunkSize||f;if(this.totalBytes>m){let e=[];for(let t=0;t<this.totalBytes;t+=a)e.push({start:t,end:Math.min(t+a-1,this.totalBytes-1),index:e.length});this.totalChunks=e.length;let r=e.filter(e=>!this.skipChunks.has(e.index)),i=e.length-r.length;for(let t of e)this.skipChunks.has(t.index)&&(this.downloadedBytes+=t.end-t.start+1);if(r.length===0){u.info(`[FileDownload] All chunks already cached, nothing to download`),this.state=`complete`,this._resolve(new Blob([],{type:this._contentType}));return}i>0&&u.info(`[FileDownload] Resuming: ${i} chunks cached, ${r.length} to download`);let o=i>0;if(o){let e=r.sort((e,t)=>e.index-t.index);for(let t of e){let e=new C(this.fileInfo,{chunkIndex:t.index,rangeStart:t.start,rangeEnd:t.end});e._parentFile=this,e._priority=y.normal,this.tasks.push(e)}}else for(let t of r){let n=new C(this.fileInfo,{chunkIndex:t.index,rangeStart:t.start,rangeEnd:t.end});n._parentFile=this,n._priority=t.index===0||t.index===e.length-1?y.high:y.normal,this.tasks.push(n)}let s=this.tasks.filter(e=>e._priority>=y.high).length;u.info(`[FileDownload] ${n}/${t}: ${this.tasks.length} chunks`+(s>0?` (${s} priority)`:``)+(o?` (resume)`:``))}else{this.totalChunks=1;let e=new C(this.fileInfo,{});e._parentFile=this,this.tasks.push(e)}e.enqueueChunkTasks(this.tasks),this.state=`downloading`}catch(e){u.error(`[FileDownload] Prepare failed:`,`${this.fileInfo.type}/${this.fileInfo.id}`,e),this.state=`failed`,this._reject(e)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(e){u.warn(`[FileDownload] onChunkDownloaded callback error:`,e)}if(this.completedChunks===this.tasks.length&&this.state!==`complete`){this.state=`complete`;let{type:t,id:n}=this.fileInfo;if(e.chunkIndex==null)u.info(`[FileDownload] Complete:`,`${t}/${n}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)u.info(`[FileDownload] Complete:`,`${t}/${n}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{let e=[];for(let t=0;t<this.totalChunks;t++){let n=this._chunkBlobs.get(t);n&&e.push(n)}let r=new Blob(e,{type:this._contentType});u.info(`[FileDownload] Complete:`,`${t}/${n}`,`(${r.size} bytes, reassembled)`),this._resolve(r)}this._chunkBlobs.clear()}}onTaskFailed(e,t){if(!(this.state===`complete`||this.state===`failed`)){if(t.message?.includes(`URL expired`)){let t=e.chunkIndex==null?``:` chunk ${e.chunkIndex}`;u.warn(`[FileDownload] URL expired, dropping${t}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(t=>t!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state=`complete`,this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}u.error(`[FileDownload] Failed:`,`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state=`failed`,this._reject(t)}}},T=class{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){let t=E.stableKey(e);if(this.queue.active.has(t)){let n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){let t=x(n.fileInfo.path);x(e.path)>t&&(n.fileInfo.path=e.path)}return n}let n=new w(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,n),this._filesToPrepare.push(n),n}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,n=0,r=()=>{for(;t<this._maxPreparing&&n<this._filesToPrepare.length;){let i=this._filesToPrepare[n++];t++,i.prepare(this).finally(()=>{t--,n>=this._filesToPrepare.length&&t===0?e():r()})}};this._filesToPrepare.length===0?e():r()})}_sortWithBarriers(){let e=[],t=[],n=[],r=[];for(let i of this._tasks)if(i.chunkIndex==null)e.push(i);else if(i.chunkIndex===0)t.push(i);else{let e=i._parentFile?.totalChunks||0;e>1&&i.chunkIndex===e-1?n.push(i):r.push(i)}e.sort((e,t)=>(e._parentFile?.totalBytes||0)-(t._parentFile?.totalBytes||0)),r.sort((e,t)=>e.chunkIndex-t.chunkIndex);let i=[...e,...t,...n];return r.length>0&&i.push(b,...r),i}},E=class e{constructor(e={}){this.concurrency=e.concurrency||d,this.chunkSize=e.chunkSize||f,this.maxChunksPerFile=e.chunksPerFile||p,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(t){let n=e.stableKey(t);if(this.active.has(n)){let e=this.active.get(n);if(t.path&&t.path!==e.fileInfo.path){let r=x(e.fileInfo.path);x(t.path)>r&&(u.info(`[DownloadQueue] Refreshing URL for`,n),e.fileInfo.path=t.path)}return e}let r=new w(t,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(n,r),u.info(`[DownloadQueue] Enqueued:`,n),this._schedulePrepare(r),r}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){let e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(let t of e)this.queue.push(t);this._sortQueue(),u.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,n=0;for(let r of e)r===b?(this.queue.push(b),n++):(this.queue.push(r),t++);u.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${n} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritizeLayoutFiles(e,t=y.high){let n=new Set(e.map(String)),r=0;for(let e of this.queue){let i=e._parentFile?.fileInfo.saveAs||String(e._parentFile?.fileInfo.id);n.has(i)&&e._priority<t&&(e._priority=t,r++)}for(let e of this._activeTasks){let r=e._parentFile?.fileInfo.saveAs||String(e._parentFile?.fileInfo.id);n.has(r)&&e._priority<t&&(e._priority=t)}this._sortQueue(),u.info(`[DownloadQueue] Layout files prioritized:`,n.size,`files,`,r,`tasks boosted to`,t)}urgentChunk(e,t,n){let r=`${e}/${t}`,i=this.active.get(r);if(!i)return u.info(`[DownloadQueue] urgentChunk: file not active:`,r,`chunk`,n),!1;if(this._activeTasks.some(e=>e._parentFile===i&&e.chunkIndex===n&&e.state===`downloading`)){let e=this._activeTasks.find(e=>e._parentFile===i&&e.chunkIndex===n);return e&&e._priority<y.urgent?(e._priority=y.urgent,u.info(`[DownloadQueue] URGENT: ${r} chunk ${n} (already in-flight, limiting slots)`),!0):(u.info(`[DownloadQueue] urgentChunk: already urgent:`,r,`chunk`,n),!1)}let a=this.queue.findIndex(e=>e!==b&&e._parentFile===i&&e.chunkIndex===n);if(a===-1)return u.info(`[DownloadQueue] urgentChunk: chunk not in queue:`,r,`chunk`,n),!1;let o=this.queue.splice(a,1)[0];return o._priority=y.urgent,this.queue.unshift(o),u.info(`[DownloadQueue] URGENT: ${r} chunk ${n} (moved to front)`),this.processQueue(),!0}processQueue(){if(this.paused)return;let e=this.queue.some(e=>e!==b&&e._priority>=y.urgent)||this._activeTasks?.some(e=>e._priority>=y.urgent&&e.state===`downloading`),t=e?h:this.concurrency,n=e?y.urgent:0;for(;this.running<t&&this.queue.length>0;){let e=this.queue[0];if(e===b){if(this.running>0)break;this.queue.shift();continue}if(e._priority<n||!this._canStartTask(e)){let e=!1;for(let t=1;t<this.queue.length&&this.queue[t]!==b;t++){let r=this.queue[t];if(r._priority>=n&&this._canStartTask(r)){this.queue.splice(t,1),this._startTask(r),e=!0;break}}if(!e)break;continue}this.queue.shift(),this._startTask(e)}this.queue.length===0&&this.running===0&&u.info(`[DownloadQueue] All downloads complete`)}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);let t=`${e.fileInfo.type}/${e.fileInfo.id}`,n=e.chunkIndex==null?``:` chunk ${e.chunkIndex}`;u.info(`[DownloadQueue] Starting: ${t}${n} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(t=>t!==e),u.info(`[DownloadQueue] Fetched: ${t}${n} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(n=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(t=>t!==e);let{maxReenqueues:r,reenqueueDelayMs:i}=e._typeConfig;if(r>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>r){u.error(`[DownloadQueue] ${t} exceeded ${r} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,n);return}u.warn(`[DownloadQueue] ${t} failed all retries (attempt ${e._reenqueueCount}/${r}), scheduling re-enqueue in ${i/1e3}s`);let a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state=`pending`,e._parentFile.state=`downloading`,this.queue.push(e),u.info(`[DownloadQueue] ${t} re-enqueued for retry`),this.processQueue()},i);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,n)})}removeCompleted(e){let t=this.active.get(e);t&&(t.state===`complete`||t.state===`failed`)&&(this.queue=this.queue.filter(e=>e===b||e._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){let e={};for(let[t,n]of this.active.entries())n.state===`complete`||n.state===`failed`||(e[t]={downloaded:n.downloadedBytes,total:n.totalBytes,percent:n.totalBytes>0?(n.downloadedBytes/n.totalBytes*100).toFixed(1):0,state:n.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(let e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}},D=class{constructor(e={}){this.queue=new E(e)}enqueue(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,t){this.queue.prioritizeLayoutFiles(e,t),this.queue.processQueue()}urgentChunk(e,t,n){return this.queue.urgentChunk(e,t,n)}createTaskBuilder(){return new T(this.queue)}enqueueOrderedTasks(e){this.queue.enqueueOrderedTasks(e)}removeCompleted(e){this.queue.removeCompleted(e)}get running(){return this.queue.running}get queued(){return this.queue.queue.length}clear(){this.queue.clear()}},O=t(`CacheAnalyzer`);function k(e){if(e===0)return`0 B`;if(!Number.isFinite(e))return`∞`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**n).toFixed(+(n>0))} ${t[n]}`}var A=class{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){let t=await this.cache.list(),n=await this._getStorageEstimate(),r=new Set(e.map(e=>String(e.id))),i=[],a=[];for(let e of t)if(r.has(String(e.id)))i.push(e);else if(e.type===`widget`){let t=String(e.id).split(`/`)[0];r.has(t)?i.push(e):a.push(e)}else e.type===`static`?i.push(e):a.push(e);a.sort((e,t)=>(e.cachedAt||0)-(t.cachedAt||0));let o=a.reduce((e,t)=>e+(t.size||0),0),s={timestamp:Date.now(),storage:{usage:n.usage,quota:n.quota,percent:n.quota>0?Math.round(n.usage/n.quota*100):0},files:{required:i.length,orphaned:a.length,total:t.length},orphaned:a.map(e=>({id:e.id,type:e.type,size:e.size||0,cachedAt:e.cachedAt||0})),orphanedSize:o,evicted:[],threshold:this.threshold};if(O.info(`Storage: ${k(n.usage)} / ${k(n.quota)} (${s.storage.percent}%)`),O.info(`Cache: ${i.length} required, ${a.length} orphaned (${k(o)} reclaimable)`),a.length>0)for(let e of a){let t=Date.now()-(e.cachedAt||0),n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),i=n>0?`${n}d ago`:`${r}h ago`;O.info(` Orphaned: ${e.type}/${e.id} (${k(e.size||0)}, cached ${i})`)}if(s.storage.percent>this.threshold&&a.length>0){O.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);let e=n.usage-n.quota*this.threshold/100;s.evicted=await this._evict(a,e)}else O.info(`No eviction needed (threshold: ${this.threshold}%)`);return s}async _getStorageEstimate(){try{if(typeof navigator<`u`&&navigator.storage?.estimate){let{usage:e,quota:t}=await navigator.storage.estimate();return{usage:e||0,quota:t||1/0}}}catch(e){O.warn(`Storage estimate unavailable:`,e.message)}return{usage:0,quota:1/0}}async _evict(e,t){let n=[],r=0;for(let i of e){if(r>=t)break;n.push(i),r+=i.size||0}if(n.length===0)return[];try{let e=n.map(e=>({type:e.type,id:e.id}));await this.cache.remove(e);for(let e of n)O.info(` Evicted: ${e.type}/${e.id} (${k(e.size||0)})`);O.info(`Evicted ${n.length} files, freed ${k(r)}`)}catch(e){return O.warn(`Eviction failed:`,e.message),[]}return n.map(e=>({id:e.id,type:e.type,size:e.size||0,cachedAt:e.cachedAt||0}))}},j=t(`Cache`),M=typeof window<`u`&&window.location.pathname.replace(/\/[^/]*$/,``).replace(/\/$/,``)||`/player/pwa`;async function N(t,n,r,i){let a=`${e}/widgets/${t}/${n}/${r}`,o=`<base href="${e}/media/file/">`,s=i;i.includes(`<base `)||(s=i.includes(`<head>`)?i.replace(`<head>`,`<head>`+o):i.includes(`<HEAD>`)?i.replace(`<HEAD>`,`<HEAD>`+o):o+i);let c=`<style>img,video{object-position:center center}</style>`;s.includes(`object-position:center center`)||(s.includes(`</head>`)?s=s.replace(`</head>`,c+`</head>`):s.includes(`</HEAD>`)&&(s=s.replace(`</HEAD>`,c+`</HEAD>`))),s=s.replace(/\[\[ViewPortWidth]]/g,`device-width`),s=s.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,e=>`/stream-proxy?url=`+encodeURIComponent(e));let l=RegExp(`https?://[^"'\\s)]+?(${e.replace(/\//g,`\\/`)}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,`g`);if(s=s.replace(l,(e,t)=>t),s=s.replace(/(<(?:script|link)\b[^>]*(?:src|href)=")(?!\/|https?:\/\/)(bundle\.min\.js|fonts\.css)(")/g,`$1${e}/dependencies/$2$3`),!s.includes(`xiboICTargetId`)){let e=`<script>var xiboICTargetId = '${r}';<\/script>`;s=s.includes(o)?s.replace(o,o+e):s.includes(`<head>`)?s.replace(`<head>`,`<head>`+e):e+s}return s=s.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${M}/ic"`),j.info(`Injected base tag in widget HTML`),(await fetch(`/store${e}/widgets/${t}/${n}/${r}`,{method:`PUT`,headers:{"Content-Type":`text/html; charset=utf-8`},body:s})).body?.cancel(),j.info(`Stored widget HTML at ${a} (${s.length} bytes)`),{cacheKey:a,html:s}}var P=n.version;export{D as a,S as c,s as d,i as f,b as i,c as l,N as n,w as o,a as p,A as r,T as s,P as t,l as u};
2
+ //# sourceMappingURL=src-CuVaZcMo.js.map