@xiboplayer/pwa 0.6.0 → 0.6.2

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 (49) hide show
  1. package/dist/assets/{chunk-config-yjpxlWy6.js → chunk-config-BjXWw-V8.js} +2 -2
  2. package/dist/assets/{chunk-config-yjpxlWy6.js.map → chunk-config-BjXWw-V8.js.map} +1 -1
  3. package/dist/assets/index-BglkPErZ.js +5 -0
  4. package/dist/assets/index-BglkPErZ.js.map +1 -0
  5. package/dist/assets/index-BwkVsox3.js +2 -0
  6. package/dist/assets/{index-C0V6Yuf7.js.map → index-BwkVsox3.js.map} +1 -1
  7. package/dist/assets/{index-DblGx8T7.js → index-C0mqgU51.js} +2 -2
  8. package/dist/assets/{index-DblGx8T7.js.map → index-C0mqgU51.js.map} +1 -1
  9. package/dist/assets/index-CwIMcVP6.js +13 -0
  10. package/dist/assets/index-CwIMcVP6.js.map +1 -0
  11. package/dist/assets/{index-D8pNyRvb.js → index-D4fqdfS-.js} +2 -2
  12. package/dist/assets/{index-D8pNyRvb.js.map → index-D4fqdfS-.js.map} +1 -1
  13. package/dist/assets/{index-BKKe321E.js → index-D9EQ-6Wd.js} +2 -2
  14. package/dist/assets/{index-BKKe321E.js.map → index-D9EQ-6Wd.js.map} +1 -1
  15. package/dist/assets/index-DnB9w-Dv.js +2 -0
  16. package/dist/assets/{index-ChxdOFuh.js.map → index-DnB9w-Dv.js.map} +1 -1
  17. package/dist/assets/{index-B-_xo7Jd.js → index-FG4fTI4i.js} +2 -2
  18. package/dist/assets/{index-B-_xo7Jd.js.map → index-FG4fTI4i.js.map} +1 -1
  19. package/dist/assets/index-IEsktHaW.js +2 -0
  20. package/dist/assets/{index-DcGeUWV6.js.map → index-IEsktHaW.js.map} +1 -1
  21. package/dist/assets/{index-CjVBCq85.js → index-so_tPJrr.js} +2 -2
  22. package/dist/assets/{index-CjVBCq85.js.map → index-so_tPJrr.js.map} +1 -1
  23. package/dist/assets/main-DJYbit7N.js +729 -0
  24. package/dist/assets/main-DJYbit7N.js.map +1 -0
  25. package/dist/assets/{setup-BKQoSJHa.js → setup-BXLaipeI.js} +2 -2
  26. package/dist/assets/{setup-BKQoSJHa.js.map → setup-BXLaipeI.js.map} +1 -1
  27. package/dist/assets/{sync-manager-Bxee4l4n.js → sync-manager-DMpg8tED.js} +2 -2
  28. package/dist/assets/{sync-manager-Bxee4l4n.js.map → sync-manager-DMpg8tED.js.map} +1 -1
  29. package/dist/assets/widget-html-D6xqg8Sp.js +2 -0
  30. package/dist/assets/widget-html-D6xqg8Sp.js.map +1 -0
  31. package/dist/assets/xmds-client-D6JI3K3_.js +16 -0
  32. package/dist/assets/xmds-client-D6JI3K3_.js.map +1 -0
  33. package/dist/index.html +3 -3
  34. package/dist/setup.html +3 -3
  35. package/dist/sw-pwa.js +1 -1
  36. package/package.json +13 -13
  37. package/dist/assets/index-BgzyAcAx.js +0 -5
  38. package/dist/assets/index-BgzyAcAx.js.map +0 -1
  39. package/dist/assets/index-BnKrYvmo.js +0 -13
  40. package/dist/assets/index-BnKrYvmo.js.map +0 -1
  41. package/dist/assets/index-C0V6Yuf7.js +0 -2
  42. package/dist/assets/index-ChxdOFuh.js +0 -2
  43. package/dist/assets/index-DcGeUWV6.js +0 -2
  44. package/dist/assets/main-BuxLonCL.js +0 -734
  45. package/dist/assets/main-BuxLonCL.js.map +0 -1
  46. package/dist/assets/widget-html-wxCcPbXd.js +0 -2
  47. package/dist/assets/widget-html-wxCcPbXd.js.map +0 -1
  48. package/dist/assets/xmds-client-xqEtcrNj.js +0 -16
  49. package/dist/assets/xmds-client-xqEtcrNj.js.map +0 -1
@@ -0,0 +1,16 @@
1
+ import{PLAYER_API as x,fetchWithRetry as w,createLogger as v}from"./index-BglkPErZ.js";const f=v("REST");class K{constructor(t){this.config=t,this.schemaVersion=7,this.retryOptions=t.retryOptions||{maxRetries:2,baseDelayMs:2e3},this._token=null,this._tokenExpiresAt=0,this._displayId=null,this._etags=new Map,this._responseCache=new Map,f.info("Using REST transport")}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${x}`:(this.config.restApiUrl||`${this.config.cmsUrl}${x}`).replace(/\/+$/,"")}_isProxyMode(){var t;return typeof window<"u"&&(((t=window.electronAPI)==null?void 0:t.isElectron)||window.location.hostname==="localhost")}async _authenticate(){const t=`${this.getRestBaseUrl()}/auth`;f.debug("Authenticating...");const e=await w(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})},this.retryOptions);if(!e.ok){const n=await e.text().catch(()=>"");throw new Error(`Auth failed: ${e.status} ${e.statusText} ${n}`)}const r=await e.json();this._token=r.token,this._displayId=r.displayId,this._tokenExpiresAt=Date.now()+(r.expiresIn-60)*1e3,f.info(`Authenticated as display ${this._displayId}`)}async _getToken(){return(!this._token||Date.now()>=this._tokenExpiresAt)&&await this._authenticate(),this._token}async restGet(t,e={}){const r=await this._getToken(),n=new URL(`${this.getRestBaseUrl()}${t}`);for(const[d,g]of Object.entries(e))n.searchParams.set(d,String(g));const l=t,a={Authorization:`Bearer ${r}`},i=this._etags.get(l);i&&(a["If-None-Match"]=i),f.debug(`GET ${t}`,e);const u=await w(n.toString(),{method:"GET",headers:a},this.retryOptions);if(u.status===401)return this._token=null,this.restGet(t,e);if(u.status===304){const d=this._responseCache.get(l);if(d)return f.debug(`${t} → 304 (using cache)`),d}if(!u.ok){const d=await u.text().catch(()=>"");throw new Error(`REST GET ${t} failed: ${u.status} ${u.statusText} ${d}`)}const s=u.headers.get("ETag");s&&this._etags.set(l,s);const c=u.headers.get("Content-Type")||"";let o;return c.includes("application/json")?o=await u.json():o=await u.text(),this._responseCache.set(l,o),o}async restSend(t,e,r={}){const n=await this._getToken(),l=new URL(`${this.getRestBaseUrl()}${e}`);f.debug(`${t} ${e}`);const a=await w(l.toString(),{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)},this.retryOptions);if(a.status===401)return this._token=null,this.restSend(t,e,r);if(!a.ok){const u=await a.text().catch(()=>"");throw new Error(`REST ${t} ${e} failed: ${a.status} ${a.statusText} ${u}`)}return(a.headers.get("Content-Type")||"").includes("application/json")?await a.json():await a.text()}async registerDisplay(){await this._getToken();const t=typeof navigator<"u"?`${navigator.platform} ${navigator.userAgent}`:"unknown",e=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||1,operatingSystem:t,macAddress:this.config.macAddress||"n/a",xmrChannel:this.config.xmrChannel,xmrPubKey:this.config.xmrPubKey||""});return this._parseRegisterDisplayJson(e)}_parseRegisterDisplayJson(t){const e=t.display||t,r=e["@attributes"]||{},n=r.code||e.code,l=r.message||e.message||"";if(n!=="READY")return{code:n,message:l,settings:null};const a={};let i=[],u=[];for(const[g,y]of Object.entries(e))if(!(g==="@attributes"||g==="file")){if(g==="commands"){Array.isArray(y)&&(u=y.map(p=>({commandCode:p.code||p.commandCode||"",commandString:p.commandString||""})));continue}if(g==="tags"){const p=h=>typeof h=="object"?h.tag||h.value||"":String(h);if(Array.isArray(y))i=y.map(p).filter(Boolean);else if(y&&typeof y=="object"){const h=p(y);h&&(i=[h])}else typeof y=="string"&&y&&(i=[y]);continue}a[g]=typeof y=="object"?JSON.stringify(y):String(y)}const s=r.checkRf||"",c=r.checkSchedule||"",o={date:r.date||e.date||null,timezone:r.timezone||e.timezone||null,status:r.status||e.status||null,localDate:r.localDate||e.localDate||null,version_instructions:r.version_instructions||e.version_instructions||null},d=e.syncGroup?{syncGroup:String(e.syncGroup),syncPublisherPort:parseInt(e.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(e.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(e.syncVideoPauseDelay||"100",10),isLead:String(e.syncGroup)==="lead"}:null;return{code:n,message:l,settings:a,tags:i,commands:u,displayAttrs:o,checkRf:s,checkSchedule:c,syncConfig:d}}async requiredFiles(){const t=await this.restGet(`/displays/${this._displayId}/media`);return this._parseRequiredFilesV2(t)}_parseRequiredFilesV2(t){const e=[];for(const r of t.media||[])e.push({type:r.type||"media",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:r.saveAs||null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(const r of t.layouts||[])e.push({type:"layout",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(const r of t.widgets||[])e.push({type:"dataset",id:r.id!=null?String(r.id):null,size:0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null,updateInterval:r.updateInterval||0});for(const r of t.dependencies||[])e.push({type:"static",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:r.type||null,code:null,layoutid:null,regionid:null,mediaid:null});return{files:e,purge:[]}}async schedule(){return this.restGet(`/displays/${this._displayId}/schedule`)}async getResource(t,e,r){return this.restGet(`/widgets/${t}/${e}/${r}`)}async notifyStatus(t){var e;if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate))try{const r=await navigator.storage.estimate();t.availableSpace=r.quota-r.usage,t.totalSpace=r.quota}catch{}return!t.timeZone&&typeof Intl<"u"&&(t.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),t.statusDialog||(t.statusDialog=`Current Layout: ${t.currentLayoutId||"None"}`),this.restSend("PUT",`/displays/${this._displayId}/status`,{statusData:t})}async mediaInventory(t){const e=Array.isArray(t)?{inventoryItems:t}:{inventory:t};return this.restSend("PUT",`/displays/${this._displayId}/inventory`,e)}async blackList(t,e,r){return f.warn(`BlackList not available in v2 API (${e}/${t}: ${r})`),!1}async submitLog(t,e=null){const r=Array.isArray(t)?{logs:t}:{logXml:t},n=await this.restSend("POST",`/displays/${this._displayId}/logs`,r);return(n==null?void 0:n.success)===!0}async submitScreenShot(t){const e=await this.restSend("POST",`/displays/${this._displayId}/screenshot`,{screenshot:t});return(e==null?void 0:e.success)===!0}async submitStats(t,e=null){try{const r=Array.isArray(t)?{stats:t}:{statXml:t},n=await this.restSend("POST",`/displays/${this._displayId}/stats`,r),l=(n==null?void 0:n.success)===!0;return f.info(`SubmitStats result: ${l}`),l}catch(r){throw f.error("SubmitStats failed:",r),r}}async reportFaults(t){const e=await this.restSend("POST",`/displays/${this._displayId}/faults`,{fault:t});return(e==null?void 0:e.success)===!0}async getWeather(){return this.restGet(`/displays/${this._displayId}/weather`)}static async isAvailable(t,e){var r;try{const a=`${typeof window<"u"&&(((r=window.electronAPI)==null?void 0:r.isElectron)||window.location.hostname==="localhost")?"":t.replace(/\/+$/,"")}${x}/health`,i=await w(a,{method:"GET"},e||{maxRetries:0});if(!i.ok)return!1;const u=await i.json();return u.version===2&&u.status==="ok"}catch{return!1}}}function S(b){const t=[];for(const e of b.children)e.tagName==="criteria"&&t.push({metric:e.getAttribute("metric")||"",condition:e.getAttribute("condition")||"",type:e.getAttribute("type")||"string",value:e.textContent||""});return t}function $(b){const e=new DOMParser().parseFromString(b,"text/xml"),r={default:null,defaultDependants:[],dependants:[],layouts:[],campaigns:[],overlays:[],actions:[],commands:[],dataConnectors:[]},n=e.querySelector("schedule");if(n){const s=Array.from(n.children).filter(c=>c.tagName==="dependants");for(const c of s)if(c.parentElement===n)for(const o of c.querySelectorAll("file"))o.textContent&&r.dependants.push(o.textContent)}const l=e.querySelector("default");if(l){r.default=l.getAttribute("file");const s=l.querySelectorAll("dependants > file");s.length>0&&(r.defaultDependants=[...s].map(c=>c.textContent))}for(const s of e.querySelectorAll("campaign")){const c={id:s.getAttribute("id"),priority:parseInt(s.getAttribute("priority")||"0"),fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),scheduleid:s.getAttribute("scheduleid"),maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),shareOfVoice:parseInt(s.getAttribute("shareOfVoice")||"0"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,criteria:S(s),layouts:[]};for(const o of s.querySelectorAll("layout")){const d=o.getAttribute("file"),g=o.querySelectorAll("dependants > file");c.layouts.push({id:String(d),file:d,fromdt:o.getAttribute("fromdt")||c.fromdt,todt:o.getAttribute("todt")||c.todt,scheduleid:c.scheduleid,priority:c.priority,campaignId:c.id,maxPlaysPerHour:parseInt(o.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:o.getAttribute("isGeoAware")==="1",geoLocation:o.getAttribute("geoLocation")||"",syncEvent:o.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(o.getAttribute("shareOfVoice")||"0"),duration:parseInt(o.getAttribute("duration")||"0"),cyclePlayback:o.getAttribute("cyclePlayback")==="1",groupKey:o.getAttribute("groupKey")||null,playCount:parseInt(o.getAttribute("playCount")||"0"),dependants:g.length>0?[...g].map(y=>y.textContent):[],criteria:S(o)})}r.campaigns.push(c)}for(const s of e.querySelectorAll("schedule > layout")){const c=s.getAttribute("file"),o=s.querySelectorAll("dependants > file");r.layouts.push({id:String(c),file:c,fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),scheduleid:s.getAttribute("scheduleid"),priority:parseInt(s.getAttribute("priority")||"0"),campaignId:null,maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(s.getAttribute("shareOfVoice")||"0"),duration:parseInt(s.getAttribute("duration")||"0"),cyclePlayback:s.getAttribute("cyclePlayback")==="1",groupKey:s.getAttribute("groupKey")||null,playCount:parseInt(s.getAttribute("playCount")||"0"),recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,dependants:o.length>0?[...o].map(d=>d.textContent):[],criteria:S(s)})}const a=e.querySelector("overlays");if(a)for(const s of a.querySelectorAll("overlay")){const c=s.getAttribute("file");r.overlays.push({id:String(c),duration:parseInt(s.getAttribute("duration")||"60"),file:c,fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),priority:parseInt(s.getAttribute("priority")||"0"),scheduleid:s.getAttribute("scheduleid"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,criteria:S(s)})}const i=e.querySelector("actions");if(i)for(const s of i.querySelectorAll("action"))r.actions.push({actionType:s.getAttribute("actionType")||"",triggerCode:s.getAttribute("triggerCode")||"",layoutCode:s.getAttribute("layoutCode")||"",commandCode:s.getAttribute("commandCode")||"",duration:parseInt(s.getAttribute("duration")||"0"),fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),priority:parseInt(s.getAttribute("priority")||"0"),scheduleid:s.getAttribute("scheduleid"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||""});for(const s of e.querySelectorAll("schedule > command"))r.commands.push({code:s.getAttribute("code")||"",date:s.getAttribute("date")||""});const u=e.querySelector("dataConnectors");if(u)for(const s of u.querySelectorAll("connector"))r.dataConnectors.push({id:s.getAttribute("id")||"",dataConnectorId:s.getAttribute("dataConnectorId")||"",dataSetId:s.getAttribute("dataSetId")||"",dataKey:s.getAttribute("dataKey")||"",dataParams:s.getAttribute("dataParams")||"",js:s.getAttribute("js")||"",url:s.getAttribute("url")||"",updateInterval:parseInt(s.getAttribute("updateInterval")||"300",10)});return r}const A=v("XMDS");class C{constructor(t){this.config=t,this.schemaVersion=5,this.retryOptions=t.retryOptions||{maxRetries:2,baseDelayMs:2e3}}buildEnvelope(t,e){const r=Object.entries(e).map(([n,l])=>{const a=String(l).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");return`<${n} xsi:type="xsd:string">${a}</${n}>`}).join(`
2
+ `);return`<?xml version="1.0" encoding="UTF-8"?>
3
+ <soap:Envelope
4
+ xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
5
+ xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
6
+ xmlns:tns="urn:xmds"
7
+ xmlns:types="urn:xmds/encodedTypes"
8
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
9
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema">
10
+ <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
11
+ <tns:${t}>
12
+ ${r}
13
+ </tns:${t}>
14
+ </soap:Body>
15
+ </soap:Envelope>`}rewriteXmdsUrl(t){var e;return typeof window<"u"&&((e=window.electronAPI)!=null&&e.isElectron||window.location.hostname==="localhost")?`/xmds-proxy?cms=${encodeURIComponent(t)}`:`${t}/xmds.php`}async call(t,e={}){const r=this.rewriteXmdsUrl(this.config.cmsUrl),n=`${r}${r.includes("?")?"&":"?"}v=${this.schemaVersion}&method=${t}`,l=this.buildEnvelope(t,e);A.debug(`${t}`,e),A.debug(`URL: ${n}`);const a=await w(n,{method:"POST",headers:{"Content-Type":"text/xml; charset=utf-8"},body:l},this.retryOptions);if(!a.ok)throw new Error(`XMDS ${t} failed: ${a.status} ${a.statusText}`);const i=await a.text();return this.parseResponse(i,t)}parseResponse(t,e){var s,c;const n=new DOMParser().parseFromString(t,"text/xml");let l=n.querySelector("Fault");if(l||(l=Array.from(n.querySelectorAll("*")).find(o=>o.localName==="Fault"||o.tagName.endsWith(":Fault"))),l){const o=((s=l.querySelector("faultstring"))==null?void 0:s.textContent)||((c=Array.from(l.querySelectorAll("*")).find(d=>d.localName==="faultstring"))==null?void 0:c.textContent)||"Unknown SOAP fault";throw new Error(`SOAP Fault: ${o}`)}const a=`${e}Response`;let i=n.querySelector(a);if(i||(i=Array.from(n.querySelectorAll("*")).find(o=>o.localName===a||o.tagName.endsWith(":"+a))),!i)throw new Error(`No ${a} element in SOAP response`);const u=i.firstElementChild;return u?u.textContent:null}async registerDisplay(){const t=`${navigator.platform} ${navigator.userAgent}`,e=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||"1",operatingSystem:t,macAddress:this.config.macAddress||"n/a",xmrChannel:this.config.xmrChannel||"",xmrPubKey:this.config.xmrPubKey||"",licenceResult:"licensed"});return this.parseRegisterDisplayResponse(e)}parseRegisterDisplayResponse(t){const n=new DOMParser().parseFromString(t,"text/xml").querySelector("display");if(!n)throw new Error("Invalid RegisterDisplay response: no <display> element");const l=n.getAttribute("code"),a=n.getAttribute("message");if(l!=="READY")return{code:l,message:a,settings:null};const i={},u=[],s=[];for(const p of n.children){const h=p.tagName.toLowerCase();if(h!=="file"){if(h==="commands"){for(const m of p.querySelectorAll("command"))s.push({commandCode:m.getAttribute("code")||m.getAttribute("commandCode")||"",commandString:m.getAttribute("commandString")||""});continue}if(h==="tags"){for(const m of p.querySelectorAll("tag"))m.textContent&&u.push(m.textContent);continue}i[p.tagName]=p.textContent}}const c=n.getAttribute("checkRf")||"",o=n.getAttribute("checkSchedule")||"",d={date:n.getAttribute("date")||null,timezone:n.getAttribute("timezone")||null,status:n.getAttribute("status")||null,localDate:n.getAttribute("localDate")||null,version_instructions:n.getAttribute("version_instructions")||null},g=i.syncGroup||null,y=g?{syncGroup:g,syncPublisherPort:parseInt(i.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(i.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(i.syncVideoPauseDelay||"100",10),isLead:g==="lead"}:null;return{code:l,message:a,settings:i,tags:u,commands:s,displayAttrs:d,checkRf:c,checkSchedule:o,syncConfig:y}}async requiredFiles(){const t=await this.call("RequiredFiles",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return this.parseRequiredFilesResponse(t)}parseRequiredFilesResponse(t){const r=new DOMParser().parseFromString(t,"text/xml"),n=[];for(const i of r.querySelectorAll("file"))n.push({type:i.getAttribute("type"),id:i.getAttribute("id"),size:parseInt(i.getAttribute("size")||"0"),md5:i.getAttribute("md5"),download:i.getAttribute("download"),path:i.getAttribute("path"),saveAs:i.getAttribute("saveAs")||null,fileType:i.getAttribute("fileType")||null,code:i.getAttribute("code"),layoutid:i.getAttribute("layoutid"),regionid:i.getAttribute("regionid"),mediaid:i.getAttribute("mediaid")});const l=[],a=r.querySelector("purge");if(a)for(const i of a.querySelectorAll("item"))l.push({id:i.getAttribute("id"),storedAs:i.getAttribute("storedAs")});return{files:n,purge:l}}async schedule(){const t=await this.call("Schedule",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return $(t)}async getResource(t,e,r){return await this.call("GetResource",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,layoutId:String(t),regionId:String(e),mediaId:String(r)})}async notifyStatus(t){var e;if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate))try{const r=await navigator.storage.estimate();t.availableSpace=r.quota-r.usage,t.totalSpace=r.quota}catch{}return!t.timeZone&&typeof Intl<"u"&&(t.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),t.statusDialog||(t.statusDialog=`Current Layout: ${t.currentLayoutId||"None"}`),await this.call("NotifyStatus",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,status:JSON.stringify(t)})}async mediaInventory(t){return await this.call("MediaInventory",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaInventory:t})}async blackList(t,e,r){try{const n=await this.call("BlackList",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaId:String(t),type:e||"media",reason:r||"Failed to render"});return A.info(`BlackListed ${e}/${t}: ${r}`),n==="true"}catch(n){return A.warn("BlackList failed:",n),!1}}async submitLog(t,e=null){return await this.call("SubmitLog",{serverKey:this.config.cmsKey,hardwareKey:e||this.config.hardwareKey,logXml:t})==="true"}async submitScreenShot(t){return await this.call("SubmitScreenShot",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,screenShot:t})==="true"}async reportFaults(t){return this.call("ReportFaults",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,fault:t})}async getWeather(){return this.call("GetWeather",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})}async submitStats(t,e=null){try{const n=await this.call("SubmitStats",{serverKey:this.config.cmsKey,hardwareKey:e||this.config.hardwareKey,statXml:t})==="true";return A.info(`SubmitStats result: ${n}`),n}catch(r){throw A.error("SubmitStats failed:",r),r}}}export{K as R,C as X,$ as p};
16
+ //# sourceMappingURL=xmds-client-D6JI3K3_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xmds-client-D6JI3K3_.js","sources":["../../../xmds/src/rest-client.js","../../../xmds/src/schedule-parser.js","../../../xmds/src/xmds-client.js"],"sourcesContent":["/**\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';\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\n this._etags = new Map();\n this._responseCache = new Map();\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 // ─── 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 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 = {}) {\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 this._token = null;\n return this.restGet(path, queryParams);\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 etag = response.headers.get('ETag');\n if (etag) {\n this._etags.set(cacheKey, etag);\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 this._responseCache.set(cacheKey, data);\n return data;\n }\n\n /**\n * Make an authenticated POST/PUT request with JSON body.\n */\n async restSend(method, path, body = {}) {\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 this._token = null;\n return this.restSend(method, path, body);\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 || 1,\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 const 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 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 if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\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 /api/v2/player/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 response = await fetchWithRetry(url, { method: 'GET' }, 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","/**\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 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 });\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 });\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","/**\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 } from '@xiboplayer/utils';\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 || '1',\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 files.push({\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\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 // Enrich with 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 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"],"names":["log","createLogger","RestClient","config","PLAYER_API","_a","url","response","fetchWithRetry","errorBody","data","path","queryParams","token","key","value","cacheKey","headers","cachedEtag","cached","etag","contentType","method","body","os","json","display","attrs","code","message","settings","tags","commands","c","extractTag","t","checkRf","checkSchedule","displayAttrs","syncConfig","files","m","l","w","d","layoutId","regionId","mediaId","status","estimate","inventoryXml","type","reason","logXml","hardwareKeyOverride","result","base64Image","statsXml","success","error","faultJson","cmsUrl","retryOptions","parseCriteria","parentEl","criteria","child","parseScheduleResponse","xml","doc","schedule","scheduleEl","globalDeps","el","depContainer","fileEl","defaultEl","defaultDeps","campaignEl","campaign","layoutEl","fileId","depEls","overlaysContainer","overlayEl","actionsContainer","actionEl","cmdEl","dataConnectorsContainer","dcEl","XmdsClient","params","paramElements","escaped","xmdsUrl","fault","faultString","_b","responseTag","responseEl","returnEl","name","tagEl","syncGroupVal","purgeItems","purgeEl","itemEl"],"mappings":"uFAgBA,MAAMA,EAAMC,EAAa,MAAM,EAExB,MAAMC,CAAW,CACtB,YAAYC,EAAQ,CAClB,KAAK,OAASA,EACd,KAAK,cAAgB,EACrB,KAAK,aAAeA,EAAO,cAAgB,CAAE,WAAY,EAAG,YAAa,GAAI,EAG7E,KAAK,OAAS,KACd,KAAK,gBAAkB,EACvB,KAAK,WAAa,KAGlB,KAAK,OAAS,IAAI,IAClB,KAAK,eAAiB,IAAI,IAE1BH,EAAI,KAAK,sBAAsB,CACjC,CAUA,gBAAiB,CACf,OAAI,KAAK,eACA,GAAG,OAAO,SAAS,MAAM,GAAGI,CAAU,IAElC,KAAK,OAAO,YAAc,GAAG,KAAK,OAAO,MAAM,GAAGA,CAAU,IAC7D,QAAQ,OAAQ,EAAE,CAChC,CAKA,cAAe,OACb,OAAO,OAAO,OAAW,QACtBC,EAAA,OAAO,cAAP,YAAAA,EAAoB,aACpB,OAAO,SAAS,WAAa,YAClC,CAQA,MAAM,eAAgB,CACpB,MAAMC,EAAM,GAAG,KAAK,eAAc,CAAE,QAEpCN,EAAI,MAAM,mBAAmB,EAE7B,MAAMO,EAAW,MAAMC,EAAeF,EAAK,CACzC,OAAQ,OACR,QAAS,CAAE,eAAgB,kB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,KAAK,uBAAuB0D,CAAO,EAAE,EAClCA,CACT,OAASC,EAAO,CACd,MAAA3D,EAAI,MAAM,sBAAuB2D,CAAK,EAChCA,CACR,CACF,CACF"}
package/dist/index.html CHANGED
@@ -94,10 +94,10 @@
94
94
  height: 100%;
95
95
  }
96
96
  </style>
97
- <script type="module" crossorigin src="./assets/main-BuxLonCL.js"></script>
97
+ <script type="module" crossorigin src="./assets/main-DJYbit7N.js"></script>
98
98
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
99
- <link rel="modulepreload" crossorigin href="./assets/index-BgzyAcAx.js">
100
- <link rel="modulepreload" crossorigin href="./assets/widget-html-wxCcPbXd.js">
99
+ <link rel="modulepreload" crossorigin href="./assets/index-BglkPErZ.js">
100
+ <link rel="modulepreload" crossorigin href="./assets/widget-html-D6xqg8Sp.js">
101
101
  </head>
102
102
  <body>
103
103
  <!-- Status overlay -->
package/dist/setup.html CHANGED
@@ -287,10 +287,10 @@
287
287
  color: #444;
288
288
  }
289
289
  </style>
290
- <script type="module" crossorigin src="./assets/setup-BKQoSJHa.js"></script>
290
+ <script type="module" crossorigin src="./assets/setup-BXLaipeI.js"></script>
291
291
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
292
- <link rel="modulepreload" crossorigin href="./assets/index-BgzyAcAx.js">
293
- <link rel="modulepreload" crossorigin href="./assets/xmds-client-xqEtcrNj.js">
292
+ <link rel="modulepreload" crossorigin href="./assets/index-BglkPErZ.js">
293
+ <link rel="modulepreload" crossorigin href="./assets/xmds-client-D6JI3K3_.js">
294
294
  </head>
295
295
  <body>
296
296
  <div class="container">
package/dist/sw-pwa.js CHANGED
@@ -1,2 +1,2 @@
1
- import{D as C}from"./assets/widget-html-wxCcPbXd.js";import{VERSION as S}from"./assets/index-B-_xo7Jd.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-yjpxlWy6.js";import{createLogger as E}from"./assets/index-BgzyAcAx.js";const o="2026-03-02T20:56:57.798Z",s=E("SW"),c=v(s),d=c.chunkSize,N=c.threshold,O=c.concurrency;s.info("Loading modular Service Worker:",o);const u=new C({concurrency:O,chunkSize:d,chunksPerFile:2}),A=new R(u),W=new T(u,{chunkSize:d,chunkStorageThreshold:N});async function I(e){const t=new URL(e.request.url),n=t.pathname.replace(i+"/ic",""),a=e.request.method;s.info("Interactive Control request:",a,n);let l=null;if(a==="POST"||a==="PUT")try{l=await e.request.text()}catch{}const h=await self.clients.matchAll({type:"window"});if(h.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const f=h[0];try{const r=await new Promise((m,g)=>{const p=new MessageChannel,w=setTimeout(()=>g(new Error("IC timeout")),5e3);p.port1.onmessage=y=>{clearTimeout(w),m(y.data)},f.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:n,search:t.search,body:l},[p.port2])});return new Response(r.body||"",{status:r.status||200,headers:{"Content-Type":r.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(r){return s.error("IC handler error:",r),new Response(JSON.stringify({error:r.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",e=>{s.info("Installing... Version:",o),e.waitUntil((async()=>{if(self.registration.active)try{const n=await(await caches.open("xibo-sw-version")).match("version");if(n){const a=await n.text();if(a===o){s.info("Same version already active, skipping activation to preserve streams");return}s.info("Version changed:",a,"→",o)}}catch{}return s.info("New version, activating immediately"),self.skipWaiting()})())});self.addEventListener("activate",e=>{s.info("Activating... Version:",o,"| @xiboplayer/cache:",S),e.waitUntil(caches.keys().then(t=>Promise.all(t.filter(n=>n.startsWith("xibo-")&&n!=="xibo-sw-version").map(n=>(s.info("Deleting legacy cache:",n),caches.delete(n))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(o)),s.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{s.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(n=>{n.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",e=>{const t=new URL(e.request.url);if(t.pathname.startsWith(i+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&e.request.method==="GET"){if(t.pathname.startsWith(i+"/ic/")){e.respondWith(I(e));return}e.respondWith(A.handleRequest(e))}});self.addEventListener("message",e=>{e.waitUntil(W.handleMessage(e).then(t=>{var n;(n=e.ports[0])==null||n.postMessage(t)}))});s.info("Modular Service Worker ready");
1
+ import{D as C}from"./assets/widget-html-D6xqg8Sp.js";import{VERSION as S}from"./assets/index-FG4fTI4i.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-BjXWw-V8.js";import{createLogger as E}from"./assets/index-BglkPErZ.js";const o="2026-03-04T00:15:13.038Z",s=E("SW"),c=v(s),d=c.chunkSize,N=c.threshold,O=c.concurrency;s.info("Loading modular Service Worker:",o);const u=new C({concurrency:O,chunkSize:d,chunksPerFile:2}),A=new R(u),W=new T(u,{chunkSize:d,chunkStorageThreshold:N});async function I(e){const t=new URL(e.request.url),n=t.pathname.replace(i+"/ic",""),a=e.request.method;s.info("Interactive Control request:",a,n);let l=null;if(a==="POST"||a==="PUT")try{l=await e.request.text()}catch{}const h=await self.clients.matchAll({type:"window"});if(h.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const f=h[0];try{const r=await new Promise((m,g)=>{const p=new MessageChannel,w=setTimeout(()=>g(new Error("IC timeout")),5e3);p.port1.onmessage=y=>{clearTimeout(w),m(y.data)},f.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:n,search:t.search,body:l},[p.port2])});return new Response(r.body||"",{status:r.status||200,headers:{"Content-Type":r.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(r){return s.error("IC handler error:",r),new Response(JSON.stringify({error:r.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",e=>{s.info("Installing... Version:",o),e.waitUntil((async()=>{if(self.registration.active)try{const n=await(await caches.open("xibo-sw-version")).match("version");if(n){const a=await n.text();if(a===o){s.info("Same version already active, skipping activation to preserve streams");return}s.info("Version changed:",a,"→",o)}}catch{}return s.info("New version, activating immediately"),self.skipWaiting()})())});self.addEventListener("activate",e=>{s.info("Activating... Version:",o,"| @xiboplayer/cache:",S),e.waitUntil(caches.keys().then(t=>Promise.all(t.filter(n=>n.startsWith("xibo-")&&n!=="xibo-sw-version").map(n=>(s.info("Deleting legacy cache:",n),caches.delete(n))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(o)),s.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{s.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(n=>{n.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",e=>{const t=new URL(e.request.url);if(t.pathname.startsWith(i+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&e.request.method==="GET"){if(t.pathname.startsWith(i+"/ic/")){e.respondWith(I(e));return}e.respondWith(A.handleRequest(e))}});self.addEventListener("message",e=>{e.waitUntil(W.handleMessage(e).then(t=>{var n;(n=e.ports[0])==null||n.postMessage(t)}))});s.info("Modular Service Worker ready");
2
2
  //# sourceMappingURL=sw-pwa.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiboplayer/pwa",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Lightweight PWA Xibo Player with RendererLite",
5
5
  "type": "module",
6
6
  "files": [
@@ -10,18 +10,18 @@
10
10
  "html2canvas": "^1.4.1",
11
11
  "nanoevents": "^9.0.0",
12
12
  "xml2js": "^0.6.2",
13
- "@xiboplayer/cache": "0.6.0",
14
- "@xiboplayer/core": "0.6.0",
15
- "@xiboplayer/crypto": "0.6.0",
16
- "@xiboplayer/renderer": "0.6.0",
17
- "@xiboplayer/schedule": "0.6.0",
18
- "@xiboplayer/stats": "0.6.0",
19
- "@xiboplayer/sync": "0.6.0",
20
- "@xiboplayer/xmds": "0.6.0",
21
- "@xiboplayer/utils": "0.6.0",
22
- "@xiboplayer/settings": "0.6.0",
23
- "@xiboplayer/xmr": "0.6.0",
24
- "@xiboplayer/sw": "0.6.0"
13
+ "@xiboplayer/crypto": "0.6.2",
14
+ "@xiboplayer/renderer": "0.6.2",
15
+ "@xiboplayer/schedule": "0.6.2",
16
+ "@xiboplayer/stats": "0.6.2",
17
+ "@xiboplayer/settings": "0.6.2",
18
+ "@xiboplayer/sw": "0.6.2",
19
+ "@xiboplayer/sync": "0.6.2",
20
+ "@xiboplayer/xmds": "0.6.2",
21
+ "@xiboplayer/xmr": "0.6.2",
22
+ "@xiboplayer/core": "0.6.2",
23
+ "@xiboplayer/cache": "0.6.2",
24
+ "@xiboplayer/utils": "0.6.2"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/node": "^22.10.5",
@@ -1,5 +0,0 @@
1
- const D="0.6.0",R={version:D},y={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},f=[];class N{constructor(t,e=null){this.name=t,this.useGlobal=e===null,this.useGlobal||this.setLevel(e)}setLevel(t){this.useGlobal=!1,typeof t=="string"?this.level=y[t.toUpperCase()]??y.INFO:this.level=t}getEffectiveLevel(){return this.useGlobal?h.level:this.level}debug(...t){this.getEffectiveLevel()<=y.DEBUG&&console.log(`[${this.name}] DEBUG:`,...t),w("debug",this.name,t)}info(...t){this.getEffectiveLevel()<=y.INFO&&console.log(`[${this.name}]`,...t),w("info",this.name,t)}warn(...t){this.getEffectiveLevel()<=y.WARNING&&console.warn(`[${this.name}]`,...t),w("warning",this.name,t)}error(...t){this.getEffectiveLevel()<=y.ERROR&&console.error(`[${this.name}]`,...t),w("error",this.name,t)}log(t,...e){switch(t.toUpperCase()){case"DEBUG":return this.debug(...e);case"INFO":return this.info(...e);case"WARNING":case"WARN":return this.warn(...e);case"ERROR":return this.error(...e)}}}const h={level:y.WARNING,setGlobalLevel(i){typeof i=="string"?this.level=y[i.toUpperCase()]??y.INFO:this.level=i,console.log(`[Logger] Global log level set to: ${this.getLevelName(this.level)}`)},getLevelName(i){return Object.keys(y).find(t=>y[t]===i)||"UNKNOWN"}};let T=!1;if(typeof window<"u"){const t=new URLSearchParams(window.location.search).get("logLevel"),e=localStorage.getItem("xibo_log_level");t?(h.setGlobalLevel(t),T=!0):e?(h.setGlobalLevel(e),T=!0):h.setGlobalLevel("WARNING")}else typeof self<"u"&&self.swLogLevel&&h.setGlobalLevel(self.swLogLevel);function k(i,t=null){return new N(i,t)}function F(i){h.setGlobalLevel(i),typeof window<"u"&&localStorage.setItem("xibo_log_level",i.toUpperCase())}function H(){return h.getLevelName(h.level)}function W(){return h.level<=y.DEBUG}function Y(i){if(T||!i)return!1;const t=U(i);return h.setGlobalLevel(t),!0}function U(i){switch((i||"").toLowerCase()){case"debug":return"DEBUG";case"info":case"notice":case"audit":return"INFO";case"warning":return"WARNING";case"error":case"critical":case"alert":case"emergency":return"ERROR";default:return"INFO"}}function w(i,t,e){if(f.length!==0)for(const a of f)try{a({level:i,name:t,args:e})}catch{}}function z(i){f.push(i)}function X(i){const t=f.indexOf(i);t>=0&&f.splice(t,1)}class V{constructor(){this.events=new Map}on(t,e){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(e)}once(t,e){const a=(...s)=>{e(...s),this.off(t,a)};this.on(t,a)}off(t,e){if(!this.events.has(t))return;const a=this.events.get(t),s=a.indexOf(e);s!==-1&&a.splice(s,1)}emit(t,...e){if(!this.events.has(t))return;const a=this.events.get(t).slice();for(const s of a)s(...e)}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}}function b(i,t){const e=new Uint8Array(i);let a="";for(let n=0;n<e.length;n++)a+=String.fromCharCode(e[n]);const s=btoa(a),r=[];for(let n=0;n<s.length;n+=64)r.push(s.substring(n,n+64));return`-----BEGIN ${t}-----
2
- ${r.join(`
3
- `)}
4
- -----END ${t}-----`}async function G(){const i=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:1024,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),t=await crypto.subtle.exportKey("spki",i.publicKey),e=await crypto.subtle.exportKey("pkcs8",i.privateKey);return{publicKeyPem:b(t,"PUBLIC KEY"),privateKeyPem:b(e,"PRIVATE KEY")}}function O(i){return!i||typeof i!="string"?!1:/^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\n[A-Za-z0-9+/=\n]+\n-----END \1-----$/.test(i.trim())}var x={};const m="xibo_config",E="xibo-hw-backup",P=1;function _(){const i=typeof process<"u"&&x?x:{},t={cmsUrl:i.CMS_URL||"",cmsKey:i.CMS_KEY||"",displayName:i.DISPLAY_NAME||"",hardwareKey:i.HARDWARE_KEY||"",xmrChannel:i.XMR_CHANNEL||"",googleGeoApiKey:i.GOOGLE_GEO_API_KEY||""};return Object.values(t).some(a=>a!=="")?t:null}class I{constructor(){this.data=this.load(),this._fromEnv||this._restoreHardwareKeyFromBackup()}load(){const t=_();if(t)return this._fromEnv=!0,t;if(typeof localStorage>"u")return{cmsUrl:"",cmsKey:"",displayName:"",hardwareKey:"",xmrChannel:""};const e=localStorage.getItem(m);let a={};if(e)try{a=JSON.parse(e)}catch(r){console.error("[Config] Failed to parse localStorage config:",r)}let s=!1;return!a.hardwareKey||a.hardwareKey.length<10?(console.warn("[Config] Missing/invalid hardwareKey — generating"),a.hardwareKey=this.generateStableHardwareKey(),this._backupHardwareKey(a.hardwareKey),s=!0):console.log("[Config] ✓ Loaded existing hardwareKey:",a.hardwareKey),a.xmrChannel||(console.warn("[Config] Missing xmrChannel — generating"),a.xmrChannel=this.generateXmrChannel(),s=!0),a.cmsUrl=a.cmsUrl||"",a.cmsKey=a.cmsKey||"",a.displayName=a.displayName||"",s&&localStorage.setItem(m,JSON.stringify(a)),a}_backupKeys(t){try{const e=indexedDB.open(E,P);e.onupgradeneeded=()=>{const a=e.result;a.objectStoreNames.contains("keys")||a.createObjectStore("keys")},e.onsuccess=()=>{const a=e.result,s=a.transaction("keys","readwrite"),r=s.objectStore("keys");for(const[n,o]of Object.entries(t))r.put(o,n);s.oncomplete=()=>{console.log("[Config] Keys backed up to IndexedDB:",Object.keys(t).join(", ")),a.close()}}}catch{}}_backupHardwareKey(t){this._backupKeys({hardwareKey:t})}async _restoreHardwareKeyFromBackup(){if(!(typeof indexedDB>"u"))try{const t=await new Promise((r,n)=>{const o=indexedDB.open(E,P);o.onupgradeneeded=()=>{const c=o.result;c.objectStoreNames.contains("keys")||c.createObjectStore("keys")},o.onsuccess=()=>r(o.result),o.onerror=()=>n(o.error)}),a=t.transaction("keys","readonly").objectStore("keys"),s=await new Promise(r=>{const n=a.get("hardwareKey");n.onsuccess=()=>r(n.result),n.onerror=()=>r(null)});t.close(),s&&s!==this.data.hardwareKey?(console.log("[Config] Restoring hardware key from IndexedDB backup:",s),console.log("[Config] (was:",this.data.hardwareKey,")"),this.data.hardwareKey=s,this.save()):!s&&this.data.hardwareKey&&this._backupHardwareKey(this.data.hardwareKey)}catch{}}save(){typeof localStorage<"u"&&localStorage.setItem(m,JSON.stringify(this.data))}isConfigured(){return!!(this.data.cmsUrl&&this.data.cmsKey&&this.data.displayName)}generateStableHardwareKey(){if(typeof crypto<"u"&&crypto.randomUUID){const s="pwa-"+crypto.randomUUID().replace(/-/g,"").substring(0,28);return console.log("[Config] Generated new UUID-based hardware key:",s),s}const e="pwa-"+Array.from({length:28},()=>Math.floor(Math.random()*16).toString(16)).join("");return console.log("[Config] Generated new random hardware key:",e),e}getCanvasFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("2d");return e?(e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("Xibo Player",2,15),t.toDataURL()):"no-canvas"}catch{return"canvas-error"}}generateHardwareKey(){return this.generateStableHardwareKey()}generateXmrChannel(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}async ensureXmrKeyPair(){if(this.data.xmrPubKey&&O(this.data.xmrPubKey))return;console.log("[Config] Generating RSA key pair for XMR registration...");const{publicKeyPem:t,privateKeyPem:e}=await G();this.data.xmrPubKey=t,this.data.xmrPrivKey=e,this.save(),typeof indexedDB<"u"&&this._backupKeys({xmrPubKey:t,xmrPrivKey:e}),console.log("[Config] RSA key pair generated and saved")}hash(t){let e=2166136261;for(let s=0;s<t.length;s++)e^=t.charCodeAt(s),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);e=e>>>0;let a="";for(let s=0;s<4;s++){let r=e+s*1234567;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n)+s,r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);r=r>>>0,a+=r.toString(16).padStart(8,"0")}return a.substring(0,32)}get cmsUrl(){return this.data.cmsUrl}set cmsUrl(t){this.data.cmsUrl=t,this.save()}get cmsKey(){return this.data.cmsKey}set cmsKey(t){this.data.cmsKey=t,this.save()}get displayName(){return this.data.displayName}set displayName(t){this.data.displayName=t,this.save()}get hardwareKey(){return this.data.hardwareKey||(console.error("[Config] CRITICAL: hardwareKey missing! Generating emergency key."),this.data.hardwareKey=this.generateStableHardwareKey(),this.save()),this.data.hardwareKey}get xmrChannel(){return this.data.xmrChannel||(console.warn("[Config] xmrChannel missing at access time — generating"),this.data.xmrChannel=this.generateXmrChannel(),this.save()),this.data.xmrChannel}get xmrPubKey(){return this.data.xmrPubKey||""}get xmrPrivKey(){return this.data.xmrPrivKey||""}get googleGeoApiKey(){return this.data.googleGeoApiKey||""}set googleGeoApiKey(t){this.data.googleGeoApiKey=t,this.save()}}const M=new I,q=new Set(["serverPort","kioskMode","fullscreen","hideMouseCursor","preventSleep","width","height"]);function J(i,t){const e=new Set([...q,...t||[]]),a={};for(const[s,r]of Object.entries(i))e.has(s)||(a[s]=r);return Object.keys(a).length>0?a:void 0}const $=k("FetchRetry"),S=3e4,L=12e4;function v(i){if(!i)return S;const t=Number(i);if(!isNaN(t)&&t>=0)return Math.min(t*1e3,L);const e=new Date(i);if(!isNaN(e.getTime())){const a=e.getTime()-Date.now();return Math.min(Math.max(a,0),L)}return S}async function Z(i,t={},e={}){const{maxRetries:a=3,baseDelayMs:s=1e3,maxDelayMs:r=3e4}=e;let n,o;for(let c=0;c<=a;c++){try{const l=await fetch(i,t);if(l.status===429){const u=v(l.headers.get("Retry-After"));if($.debug(`429 Rate limited, waiting ${u}ms (Retry-After: ${l.headers.get("Retry-After")})`),o=l,n=new Error("HTTP 429: Too Many Requests"),n.status=429,c<a){await new Promise(d=>setTimeout(d,u));continue}break}if(l.ok||l.status>=400&&l.status<500)return l;if(o=l,n=new Error(`HTTP ${l.status}: ${l.statusText}`),n.status=l.status,l.status===503&&c<a){const u=l.headers.get("Retry-After");if(u){const d=v(u);$.debug(`503 Service Unavailable, Retry-After: ${u} (${d}ms)`),await new Promise(K=>setTimeout(K,d));continue}}}catch(l){n=l,o=null}if(c<a){const u=Math.min(s*Math.pow(2,c),r)*(.5+Math.random()*.5);$.debug(`Retry ${c+1}/${a} in ${Math.round(u)}ms:`,String(i).slice(0,80)),await new Promise(d=>setTimeout(d,u))}}if(o)return o;throw n}const p=k("CmsApi");class Q{constructor({baseUrl:t,clientId:e,clientSecret:a,apiToken:s}={}){this.baseUrl=(t||"").replace(/\/+$/,""),this.clientId=e||null,this.clientSecret=a||null,this.accessToken=s||null,this.tokenExpiry=s?1/0:0}async authenticate(){p.info("Authenticating with CMS API...");const t=await fetch(`${this.baseUrl}/api/authorize/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.clientId,client_secret:this.clientSecret})});if(!t.ok){const a=await t.text();throw new Error(`OAuth2 authentication failed (${t.status}): ${a}`)}const e=await t.json();return this.accessToken=e.access_token,this.tokenExpiry=Date.now()+(e.expires_in||3600)*1e3,p.info("Authenticated successfully, token expires in",e.expires_in,"s"),this.accessToken}async ensureToken(){if(!(this.accessToken&&Date.now()<this.tokenExpiry-6e4)){if(!this.clientId||!this.clientSecret){if(this.accessToken)return;throw new g("AUTH","/authorize",0,"No valid token and no OAuth2 credentials")}await this.authenticate()}}async request(t,e,a={}){var c;await this.ensureToken();const s=new URL(`${this.baseUrl}/api${e}`),r={method:t,headers:{Authorization:`Bearer ${this.accessToken}`}};if(t==="GET")for(const[l,u]of Object.entries(a))u!=null&&s.searchParams.set(l,String(u));else r.headers["Content-Type"]="application/x-www-form-urlencoded",r.body=new URLSearchParams(a);const n=await fetch(s,r);if(!n.ok){const l=await n.text();let u;try{const d=JSON.parse(l);u=((c=d.error)==null?void 0:c.message)||d.message||l}catch{u=l}throw new g(t,e,n.status,u)}return(n.headers.get("Content-Type")||"").includes("application/json")?n.json():null}get(t,e){return this.request("GET",t,e)}post(t,e){return this.request("POST",t,e)}put(t,e){return this.request("PUT",t,e)}del(t){return this.request("DELETE",t)}async findDisplay(t){p.info("Looking up display by hardwareKey:",t);const e=await this.request("GET","/display",{hardwareKey:t}),a=Array.isArray(e)?e:[];if(a.length===0)return p.info("No display found for hardwareKey:",t),null;const s=a[0];return p.info(`Found display: ${s.display} (ID: ${s.displayId}, licensed: ${s.licensed})`),s}async authorizeDisplay(t){p.info("Authorizing display:",t),await this.request("PUT",`/display/authorise/${t}`),p.info("Display authorized successfully")}async editDisplay(t,e){return p.info("Editing display:",t,e),this.request("PUT",`/display/${t}`,e)}async listDisplays(t={}){const e=await this.request("GET","/display",t);return Array.isArray(e)?e:[]}async requestScreenshot(t){await this.request("PUT",`/display/requestscreenshot/${t}`)}async getDisplayStatus(t){return this.request("GET",`/display/status/${t}`)}async requestMultipart(t,e,a){var o;await this.ensureToken();const s=`${this.baseUrl}/api${e}`,r=await fetch(s,{method:t,headers:{Authorization:`Bearer ${this.accessToken}`},body:a});if(!r.ok){const c=await r.text();let l;try{const u=JSON.parse(c);l=((o=u.error)==null?void 0:o.message)||u.message||c}catch{l=c}throw new Error(`CMS API ${t} ${e} failed (${r.status}): ${l}`)}return(r.headers.get("Content-Type")||"").includes("application/json")?r.json():null}async createLayout({name:t,resolutionId:e,description:a}){const s={name:t,resolutionId:e};return a&&(s.description=a),this.request("POST","/layout",s)}async listLayouts(t={}){const e=await this.request("GET","/layout",t);return Array.isArray(e)?e:[]}async getLayout(t){return this.request("GET",`/layout/${t}`)}async deleteLayout(t){await this.request("DELETE",`/layout/${t}`)}async publishLayout(t){await this.request("PUT",`/layout/publish/${t}`,{publishNow:1})}async checkoutLayout(t){return this.request("PUT",`/layout/checkout/${t}`)}async getDraftLayout(t){const e=await this.listLayouts({parentId:t});return e.length>0?e[0]:null}async editLayoutBackground(t,e){return this.request("PUT",`/layout/background/${t}`,e)}async addRegion(t,e){return this.request("POST",`/region/${t}`,e)}async editRegion(t,e){return this.request("PUT",`/region/${t}`,e)}async deleteRegion(t){await this.request("DELETE",`/region/${t}`)}async addWidget(t,e,a={}){const{templateId:s,displayOrder:r,...n}=a,o={};s!==void 0&&(o.templateId=s),r!==void 0&&(o.displayOrder=r);const c=await this.request("POST",`/playlist/widget/${t}/${e}`,o);return Object.keys(n).length>0?(n.duration!==void 0&&n.useDuration===void 0&&(n.useDuration=1),this.request("PUT",`/playlist/widget/${c.widgetId}`,n)):c}async editWidget(t,e){return this.request("PUT",`/playlist/widget/${t}`,e)}async deleteWidget(t){await this.request("DELETE",`/playlist/widget/${t}`)}async uploadMedia(t){return this.requestMultipart("POST","/library",t)}async listMedia(t={}){const e=await this.request("GET","/library",t);return Array.isArray(e)?e:[]}async getMedia(t){return this.request("GET",`/library/${t}`)}async deleteMedia(t){await this.request("DELETE",`/library/${t}`)}async createCampaign(t){return this.request("POST","/campaign",{name:t})}async listCampaigns(t={}){const e=await this.request("GET","/campaign",t);return Array.isArray(e)?e:[]}async deleteCampaign(t){await this.request("DELETE",`/campaign/${t}`)}async assignLayoutToCampaign(t,e,a){const s={layoutId:e};a!==void 0&&(s.displayOrder=a),await this.request("POST",`/campaign/layout/assign/${t}`,s)}async createSchedule(t){const e={...t};Array.isArray(e.displayGroupIds)&&delete e.displayGroupIds,await this.ensureToken();const a=`${this.baseUrl}/api/schedule`,s=new URLSearchParams;for(const[o,c]of Object.entries(e))c!=null&&s.set(o,String(c));if(Array.isArray(t.displayGroupIds))for(const o of t.displayGroupIds)s.append("displayGroupIds[]",String(o));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const o=await r.text();throw new Error(`CMS API POST /schedule failed (${r.status}): ${o}`)}return(r.headers.get("Content-Type")||"").includes("application/json")?r.json():null}async deleteSchedule(t){await this.request("DELETE",`/schedule/${t}`)}async listSchedules(t={}){const e=await this.request("GET","/schedule/data/events",t);return Array.isArray(e)?e:(e==null?void 0:e.events)||[]}async listDisplayGroups(t={}){const e=await this.request("GET","/displaygroup",t);return Array.isArray(e)?e:[]}async createDisplayGroup(t,e){const a={displayGroup:t};return e&&(a.description=e),this.request("POST","/displaygroup",a)}async deleteDisplayGroup(t){await this.request("DELETE",`/displaygroup/${t}`)}async assignDisplayToGroup(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/displaygroup/${t}/display/assign`,s=new URLSearchParams;s.append("displayId[]",String(e));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new Error(`CMS API assign display to group failed (${r.status}): ${n}`)}}async unassignDisplayFromGroup(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/displaygroup/${t}/display/unassign`,s=new URLSearchParams;s.append("displayId[]",String(e));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new Error(`CMS API unassign display from group failed (${r.status}): ${n}`)}}async listResolutions(){const t=await this.request("GET","/resolution");return Array.isArray(t)?t:[]}async listTemplates(t={}){const e=await this.request("GET","/template",t);return Array.isArray(e)?e:[]}async assignMediaToPlaylist(t,e){const a=Array.isArray(e)?e:[e];await this.ensureToken();const s=`${this.baseUrl}/api/playlist/library/assign/${t}`,r=new URLSearchParams;for(const c of a)r.append("media[]",String(c));const n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:r});if(!n.ok){const c=await n.text();throw new g("POST",`/playlist/library/assign/${t}`,n.status,c)}return(n.headers.get("Content-Type")||"").includes("application/json")?n.json():null}async editLayout(t,e){return this.request("PUT",`/layout/${t}`,e)}async copyLayout(t,e={}){return this.post(`/layout/copy/${t}`,e)}async discardLayout(t){await this.put(`/layout/discard/${t}`)}async editCampaign(t,e){return this.put(`/campaign/${t}`,e)}async getCampaign(t){return this.get(`/campaign/${t}`)}async unassignLayoutFromCampaign(t,e){await this.post(`/campaign/layout/unassign/${t}`,{layoutId:e})}async editSchedule(t,e){return this.put(`/schedule/${t}`,e)}async retireLayout(t){await this.put(`/layout/retire/${t}`)}async unretireLayout(t){await this.put(`/layout/unretire/${t}`)}async getLayoutStatus(t){return this.get(`/layout/status/${t}`)}async tagLayout(t,e){await this.post(`/layout/${t}/tag`,{tag:e.join(",")})}async untagLayout(t,e){await this.post(`/layout/${t}/untag`,{tag:e.join(",")})}async listCommands(t={}){const e=await this.get("/command",t);return Array.isArray(e)?e:[]}async createCommand(t){return this.post("/command",t)}async editCommand(t,e){return this.put(`/command/${t}`,e)}async deleteCommand(t){await this.del(`/command/${t}`)}async deleteDisplay(t){await this.del(`/display/${t}`)}async wolDisplay(t){await this.post(`/display/wol/${t}`)}async setDefaultLayout(t,e){return this.put(`/display/${t}`,{defaultLayoutId:e})}async purgeDisplay(t){await this.post(`/display/purge/${t}`)}async listDayParts(t={}){const e=await this.get("/daypart",t);return Array.isArray(e)?e:[]}async createDayPart(t){return this.post("/daypart",t)}async editDayPart(t,e){return this.put(`/daypart/${t}`,e)}async deleteDayPart(t){await this.del(`/daypart/${t}`)}async uploadMediaUrl(t,e){return this.post("/library",{url:t,name:e,type:"uri"})}async copyMedia(t){return this.post(`/library/copy/${t}`)}async downloadMedia(t){await this.ensureToken();const e=`${this.baseUrl}/api/library/download/${t}`,a=await fetch(e,{headers:{Authorization:`Bearer ${this.accessToken}`}});if(!a.ok){const s=await a.text();throw new g("GET",`/library/download/${t}`,a.status,s)}return a}async editMedia(t,e){return this.put(`/library/${t}`,e)}async getMediaUsage(t){return this.get(`/library/usage/${t}`)}async tidyLibrary(){await this.post("/library/tidy")}async listPlaylists(t={}){const e=await this.get("/playlist",t);return Array.isArray(e)?e:[]}async createPlaylist(t){return this.post("/playlist",{name:t})}async getPlaylist(t){return this.get(`/playlist/${t}`)}async editPlaylist(t,e){return this.put(`/playlist/${t}`,e)}async deletePlaylist(t){await this.del(`/playlist/${t}`)}async reorderPlaylist(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/playlist/order/${t}`,s=new URLSearchParams;for(const n of e)s.append("widgets[]",String(n));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new g("POST",`/playlist/order/${t}`,r.status,n)}}async copyPlaylist(t){return this.post(`/playlist/copy/${t}`)}async setWidgetTransition(t,e,a={}){return this.put(`/playlist/widget/transition/${t}`,{type:e,...a})}async setWidgetAudio(t,e){return this.put(`/playlist/widget/${t}/audio`,e)}async removeWidgetAudio(t){await this.del(`/playlist/widget/${t}/audio`)}async setWidgetExpiry(t,e){return this.put(`/playlist/widget/${t}/expiry`,e)}async saveAsTemplate(t,e){return this.post(`/template/${t}`,e)}async getTemplate(t){return this.get(`/template/${t}`)}async deleteTemplate(t){await this.del(`/template/${t}`)}async listDatasets(t={}){const e=await this.get("/dataset",t);return Array.isArray(e)?e:[]}async createDataset(t){return this.post("/dataset",t)}async editDataset(t,e){return this.put(`/dataset/${t}`,e)}async deleteDataset(t){await this.del(`/dataset/${t}`)}async listDatasetColumns(t){const e=await this.get(`/dataset/${t}/column`);return Array.isArray(e)?e:[]}async createDatasetColumn(t,e){return this.post(`/dataset/${t}/column`,e)}async editDatasetColumn(t,e,a){return this.put(`/dataset/${t}/column/${e}`,a)}async deleteDatasetColumn(t,e){await this.del(`/dataset/${t}/column/${e}`)}async listDatasetData(t,e={}){const a=await this.get(`/dataset/data/${t}`,e);return Array.isArray(a)?a:[]}async addDatasetRow(t,e){return this.post(`/dataset/data/${t}`,e)}async editDatasetRow(t,e,a){return this.put(`/dataset/data/${t}/${e}`,a)}async deleteDatasetRow(t,e){await this.del(`/dataset/data/${t}/${e}`)}async importDatasetCsv(t,e){return this.requestMultipart("POST",`/dataset/import/${t}`,e)}async clearDataset(t){await this.del(`/dataset/data/${t}`)}async listNotifications(t={}){const e=await this.get("/notification",t);return Array.isArray(e)?e:[]}async createNotification(t){return this.post("/notification",t)}async editNotification(t,e){return this.put(`/notification/${t}`,e)}async deleteNotification(t){await this.del(`/notification/${t}`)}async listFolders(t={}){const e=await this.get("/folder",t);return Array.isArray(e)?e:[]}async createFolder(t){return this.post("/folder",t)}async editFolder(t,e){return this.put(`/folder/${t}`,e)}async deleteFolder(t){await this.del(`/folder/${t}`)}async listTags(t={}){const e=await this.get("/tag",t);return Array.isArray(e)?e:[]}async createTag(t){return this.post("/tag",t)}async editTag(t,e){return this.put(`/tag/${t}`,e)}async deleteTag(t){await this.del(`/tag/${t}`)}async tagEntity(t,e,a){await this.post(`/${t}/${e}/tag`,{tag:a.join(",")})}async untagEntity(t,e,a){await this.post(`/${t}/${e}/untag`,{tag:a.join(",")})}async dgChangeLayout(t,e){await this.post(`/displaygroup/${t}/action/changeLayout`,{layoutId:e})}async dgOverlayLayout(t,e){await this.post(`/displaygroup/${t}/action/overlayLayout`,{layoutId:e})}async dgRevertToSchedule(t){await this.post(`/displaygroup/${t}/action/revertToSchedule`)}async dgCollectNow(t){await this.post(`/displaygroup/${t}/action/collectNow`)}async dgSendCommand(t,e){await this.post(`/displaygroup/${t}/action/command`,{commandId:e})}async editDisplayGroup(t,e){return this.put(`/displaygroup/${t}`,e)}}class g extends Error{constructor(t,e,a,s){super(`CMS API ${t} ${e} → ${a}: ${s}`),this.name="CmsApiError",this.method=t,this.path=e,this.status=a,this.detail=s}}const tt=R.version,j="/api/v2/player";var C;let A=((C=M.data)==null?void 0:C.playerApiBase)||j,B=A;function et(i){A=i.replace(/\/+$/,""),B=A}export{Q as CmsApiClient,g as CmsApiError,V as EventEmitter,y as LOG_LEVELS,B as PLAYER_API,q as SHELL_ONLY_KEYS,tt as VERSION,Y as applyCmsLogLevel,M as config,k as createLogger,J as extractPwaConfig,Z as fetchWithRetry,H as getLogLevel,W as isDebug,U as mapCmsLogLevel,z as registerLogSink,F as setLogLevel,et as setPlayerApi,X as unregisterLogSink};
5
- //# sourceMappingURL=index-BgzyAcAx.js.map