[grade=pending] rebuild: frontend dist artifacts with i18n language selector + share modal
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s

Rebuilt features.js (includes i18n language selector + share modal updates)
and sw.js (updated service worker cache hash).
This commit is contained in:
Hermes committed 2026-08-13 09:13:55 -07:00
1 parent 0e9370891f
commit 9d085ebf94
3 files changed
+256 -264

No files matched your search

+2 -2
View File
@@ -16,7 +16,7 @@
The interactive tour is unavailable, but you can explore the dashboard freely. The interactive tour is unavailable, but you can explore the dashboard freely.
Check the documentation for help getting started. Check the documentation for help getting started.
</p> </p>
`,document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(g){return this.data[g]||null},setItem(g,m){this.data[g]=m},removeItem(g){delete this.data[g]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}c.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window);const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const g=await h.json();if(g.tld&&(SITE.tld=g.tld.startsWith(".")?g.tld:"."+g.tld),g.dns&&(SITE.dnsIp=g.dns.ip||"",SITE.dnsPort=g.dns.port||DC.DEFAULTS.DNS_PORT),g.dnsServers&&typeof g.dnsServers=="object")for(const[b,r]of Object.entries(g.dnsServers))b!=="__proto__"&&b!=="constructor"&&b!=="prototype"&&(SITE.dnsServers[b]=r);g.configurationType&&(SITE.configurationType=g.configurationType),g.domain&&(SITE.domain=g.domain),g.defaults&&(SITE.defaults=g.defaults),g.routingMode&&(SITE.routingMode=g.routingMode),SITE.onboardingCompleted=g.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const m=document.getElementById("manage-tokens");m&&(m.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const f=document.getElementById("external-proxy-ip");f&&SITE.dnsIp&&(f.value=SITE.dnsIp,f.placeholder=SITE.dnsIp)})();function buildDomain(c){return c+SITE.tld}function buildServiceUrl(c){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+c:SITE.configurationType==="public"&&SITE.domain?"https://"+c+"."+SITE.domain:"https://"+buildDomain(c)}function getDnsServerAddr(c){const a=SITE.dnsServers[c];return a?`${a.ip}:${a.port}`:buildDomain(c)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[c,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return c;return null}function renderDnsCards(){const c=document.querySelector(".top");if(!c)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const f='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',h=c.firstElementChild;a.forEach(g=>{const m=escapeHtml(g),b=escapeHtml((SITE.dnsServers[g].name||g).toUpperCase()),r=document.createElement("div");r.className="card",r.setAttribute("data-app",g),r.setAttribute("data-status","off"),r.innerHTML=`<span id="${m}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${f}</div><span class="name">${b}</span><span class="spacer"></span><span id="${m}-pill" class="badge off">OFF</span></div><div class="response-row"><span id="${m}-time" class="response-time">--</span></div><div class="health-row" id="health-${m}"><span id="uptime-${m}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${m}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${m}-restart" class="restart-btn">Restart</button><button id="${m}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${m}-open">Open</button><button id="${m}-logs" class="logs-btn">Logs</button><button id="${m}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,c.insertBefore(r,h)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const c=await fetch("/api/v1/csrf-token");if(!c.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await c.jsLine truncated `,document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(g){return this.data[g]||null},setItem(g,m){this.data[g]=m},removeItem(g){delete this.data[g]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}c.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window);const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const g=await h.json();if(g.tld&&(SITE.tld=g.tld.startsWith(".")?g.tld:"."+g.tld),g.dns&&(SITE.dnsIp=g.dns.ip||"",SITE.dnsPort=g.dns.port||DC.DEFAULTS.DNS_PORT),g.dnsServers&&typeof g.dnsServers=="object")for(const[b,r]of Object.entries(g.dnsServers))b!=="__proto__"&&b!=="constructor"&&b!=="prototype"&&(SITE.dnsServers[b]=r);g.configurationType&&(SITE.configurationType=g.configurationType),g.domain&&(SITE.domain=g.domain),g.defaults&&(SITE.defaults=g.defaults),g.routingMode&&(SITE.routingMode=g.routingMode),SITE.onboardingCompleted=g.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const m=document.getElementById("manage-tokens");m&&(m.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const f=document.getElementById("external-proxy-ip");f&&SITE.dnsIp&&(f.value=SITE.dnsIp,f.placeholder=SITE.dnsIp)})();function buildDomain(c){return c+SITE.tld}function buildServiceUrl(c){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+c:SITE.configurationType==="public"&&SITE.domain?"https://"+c+"."+SITE.domain:"https://"+buildDomain(c)}function getDnsServerAddr(c){const a=SITE.dnsServers[c];return a?`${a.ip}:${a.port}`:buildDomain(c)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[c,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return c;return null}function renderDnsCards(){const c=document.querySelector(".top");if(!c)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const f='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',h=c.firstElementChild;a.forEach(g=>{const m=escapeHtml(g),b=escapeHtml((SITE.dnsServers[g].name||g).toUpperCase()),r=document.createElement("div");r.className="card",r.setAttribute("data-app",g),r.setAttribute("data-status","off"),r.innerHTML=`<span id="${m}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${f}</div><span class="name">${b}</span><span class="spacer"></span><span id="${m}-pill" class="badge off">OFF</span></div><div class="response-row"><span id="${m}-time" class="response-time">--</span></div><div class="health-row" id="health-${m}"><span id="uptime-${m}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${m}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${m}-restart" class="restart-btn">Restart</button><button id="${m}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${m}-open">Open</button><button id="${m}-logs" class="logs-btn">Logs</button><button id="${m}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,c.insertBefore(r,h)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const c=await fetch("/api/v1/csrf-token");if(!c.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await c.jsLine truncated
position: fixed; top: 20px; right: 20px; position: fixed; top: 20px; right: 20px;
background: ${m.bg}; color: ${m.fg}; background: ${m.bg}; color: ${m.fg};
padding: 16px 24px; border-radius: 8px; padding: 16px 24px; border-radius: 8px;
@@ -846,4 +846,4 @@ The service will be briefly unavailable.`))try{o&&(o.textContent="\u{1F504}",o.d
<span style="color: #4caf50;">\u2713 Connected</span> <span style="color: #4caf50;">\u2713 Connected</span>
<span style="color: var(--muted); margin-left: 6px;">${w.self?.hostname} (${w.self?.ip})</span> <span style="color: var(--muted); margin-left: 6px;">${w.self?.hostname} (${w.self?.ip})</span>
`,y.disabled=!1):w.installed?(i.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',y.disabled=!0):(i.innerHTML='<span style="color: var(--muted);">Not available</span>',y.disabled=!0)}catch{i.innerHTML='<span style="color: var(--muted);">Could not check</span>',y.disabled=!0}y.checked=!1,f()}function r(){const e=document.getElementById("service-type-local"),n=document.getElementById("service-type-external"),l=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),i=document.getElementById("tab-local"),y=document.getElementById("tab-external");function u(){e.checked?(l.style.display="grid",t.style.display="none",i&&(i.style.background="var(--accent)",i.style.color="var(--bg)"),y&&(y.style.background="transparent",y.style.color="var(--muted)")):(l.style.display="none",t.style.display="block",y&&(y.style.background="var(--accent)",y.style.color="var(--bg)"),i&&(i.style.background="transparent",i.style.color="var(--muted)"))}e?.addEventListener("change",u),n?.addEventListener("change",u)}function v(){const e=document.getElementById("service-name-input"),n=document.getElementById("service-subdomain-input"),l=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const L=c(e.value);!t&&n&&(n.value=L),l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()}),n?.addEventListener("input",()=>{t=n.value!==c(e?.value||"");const L=n.value.trim()||c(e?.value||"");l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()});const i=document.getElementById("external-service-name"),y=document.getElementById("external-service-subdomain"),u=document.getElementById("external-subdomain-preview"),w=document.getElementById("external-domain-preview");let T=!1;i?.addEventListener("input",()=>{const L=c(i.value);!T&&y&&(y.value=L);const P=y?.value||L;u&&(u.textContent=P?`\u2192 ${buildDomain(P)}`:""),w&&(w.textContent=P?buildDomain(P):"")}),y?.addEventListener("input",()=>{T=y.value!==c(i?.value||"");const L=y.value.trim()||c(i?.value||"");u&&(u.textContent=L?`\u2192 ${buildDomain(L)}`:""),w&&(w.textContent=L?buildDomain(L):"")})}async function d(){const e=document.getElementById("external-service-name").value.trim(),n=document.getElementById("external-service-url").value.trim(),l=(document.getElementById("external-service-subdomain").value.trim()||c(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),i=document.getElementById("external-service-icon").value.trim(),y=document.getElementById("external-create-dns").checked,u=document.getElementById("external-create-caddy").checked,w=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",T=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!e||!n){showNotification("Please fill in Name and External URL","warning");return}if(!l){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!n.startsWith("http://")&&!n.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const C=buildDomain(l);try{const B={dns:null,caddy:null,dashboard:!1};if(y)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:C,ip:w,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(S){B.dns=S.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(u)try{const E={subdomain:l,externalUrl:n,preserveHost:T,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(E){B.caddy=E.message}const $={id:l,name:e,url:`https://${C}`,externalUrl:n,logo:t||i||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const k=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(E=>!k.includes(E.id));safeSet("custom-services",JSON.stringify(x));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(E){console.warn("Failed to save to services.json:",E)}window.buildGrid(),window.refreshAll(),o();const I=[`External service "${e}" added!`];y&&I.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),u&&I.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),I.push(`Access at: https://${C}`),showNotification(I.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated `,y.disabled=!1):w.installed?(i.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',y.disabled=!0):(i.innerHTML='<span style="color: var(--muted);">Not available</span>',y.disabled=!0)}catch{i.innerHTML='<span style="color: var(--muted);">Could not check</span>',y.disabled=!0}y.checked=!1,f()}function r(){const e=document.getElementById("service-type-local"),n=document.getElementById("service-type-external"),l=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),i=document.getElementById("tab-local"),y=document.getElementById("tab-external");function u(){e.checked?(l.style.display="grid",t.style.display="none",i&&(i.style.background="var(--accent)",i.style.color="var(--bg)"),y&&(y.style.background="transparent",y.style.color="var(--muted)")):(l.style.display="none",t.style.display="block",y&&(y.style.background="var(--accent)",y.style.color="var(--bg)"),i&&(i.style.background="transparent",i.style.color="var(--muted)"))}e?.addEventListener("change",u),n?.addEventListener("change",u)}function v(){const e=document.getElementById("service-name-input"),n=document.getElementById("service-subdomain-input"),l=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const L=c(e.value);!t&&n&&(n.value=L),l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()}),n?.addEventListener("input",()=>{t=n.value!==c(e?.value||"");const L=n.value.trim()||c(e?.value||"");l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()});const i=document.getElementById("external-service-name"),y=document.getElementById("external-service-subdomain"),u=document.getElementById("external-subdomain-preview"),w=document.getElementById("external-domain-preview");let T=!1;i?.addEventListener("input",()=>{const L=c(i.value);!T&&y&&(y.value=L);const P=y?.value||L;u&&(u.textContent=P?`\u2192 ${buildDomain(P)}`:""),w&&(w.textContent=P?buildDomain(P):"")}),y?.addEventListener("input",()=>{T=y.value!==c(i?.value||"");const L=y.value.trim()||c(i?.value||"");u&&(u.textContent=L?`\u2192 ${buildDomain(L)}`:""),w&&(w.textContent=L?buildDomain(L):"")})}async function d(){const e=document.getElementById("external-service-name").value.trim(),n=document.getElementById("external-service-url").value.trim(),l=(document.getElementById("external-service-subdomain").value.trim()||c(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),i=document.getElementById("external-service-icon").value.trim(),y=document.getElementById("external-create-dns").checked,u=document.getElementById("external-create-caddy").checked,w=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",T=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!e||!n){showNotification("Please fill in Name and External URL","warning");return}if(!l){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!n.startsWith("http://")&&!n.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const C=buildDomain(l);try{const B={dns:null,caddy:null,dashboard:!1};if(y)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:C,ip:w,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(S){B.dns=S.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(u)try{const E={subdomain:l,externalUrl:n,preserveHost:T,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(E){B.caddy=E.message}const $={id:l,name:e,url:`https://${C}`,externalUrl:n,logo:t||i||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const k=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(E=>!k.includes(E.id));safeSet("custom-services",JSON.stringify(x));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(E){console.warn("Failed to save to services.json:",E)}window.buildGrid(),window.refreshAll(),o();const I=[`External service "${e}" added!`];y&&I.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),u&&I.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),I.push(`Access at: https://${C}`),showNotification(I.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLyoqXG4gKiBFcnJvciBIYW5kbGVyXG4gKiBIYW5kbGVzIGVycm9ycyBncmFjZWZ1bGx5IHdpdGhvdXQgYnJlYWtpbmcgdGhlIG9uYm9hcmRpbmcgdG91clxuICovXG5cbihmdW5jdGlvbih3aW5kb3cpIHtcbiAgJ3VzZSBzdHJpY3QnO1xuXG4gIGNsYXNzIEVycm9ySGFuZGxlciB7XG4gICAgY29uc3RydWN0b3IoKSB7XG4gICAgICB0aGlzLmVycm9ycyA9IFtdO1xuICAgICAgdGhpcy5tYXhFcnJvcnMgPSA1MDsgLy8gS2VlcCBsYXN0IDUwIGVycm9yc1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIExvZyBhbiBlcnJvciB3aXRob3V0IGJyZWFraW5nIHRoZSB0b3VyXG4gICAgICogQHBhcmFtIHtzdHJpbmd9IGNvbnRleHQgLSBDb250ZXh0IHdoZXJlIGVycm9yIG9jY3VycmVkXG4gICAgICogQHBhcmFtIHtFcnJvcnxzdHJpbmd9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdCBvciBtZXNzYWdlXG4gICAgICogQHBhcmFtIHtPYmplY3R9IG1ldGFkYXRhIC0gQWRkaXRpb25hbCBtZXRhZGF0YVxuICAgICAqL1xuICAgIGxvZ0Vycm9yKGNvbnRleHQsIGVycm9yLCBtZXRhZGF0YSA9IHt9KSB7XG4gICAgICBjb25zdCBlcnJvckVudHJ5ID0ge1xuICAgICAgICB0aW1lc3RhbXA6IG5ldyBEYXRlKCkudG9JU09TdHJpbmcoKSxcbiAgICAgICAgY29udGV4dCxcbiAgICAgICAgbWVzc2FnZTogZXJyb3IgaW5zdGFuY2VvZiBFcnJvciA/IGVycm9yLm1lc3NhZ2UgOiBlcnJvcixcbiAgICAgICAgc3RhY2s6IGVycm9yIGluc3RhbmNlb2YgRXJyb3IgPyBlcnJvci5zdGFjayA6IG51bGwsXG4gICAgICAgIG1ldGFkYXRhXG4gICAgICB9O1xuXG4gICAgICAvLyBBZGQgdG8gZXJyb3JzIGFycmF5XG4gICAgICB0aGlzLmVycm9ycy5wdXNoKGVycm9yRW50cnkpO1xuXG4gICAgICAvLyBLZWVwIG9ubHkgbGFzdCBtYXhFcnJvcnNcbiAgICAgIGlmICh0aGlzLmVycm9ycy5sZW5ndGggPiB0aGlzLm1heEVycm9ycykge1xuICAgICAgICB0aGlzLmVycm9ycy5zaGlmdCgpO1xuICAgICAgfVxuXG4gICAgICAvLyBMb2cgdG8gY29uc29sZVxuICAgICAgY29uc29sZS5lcnJvcihgW09uYm9hcmRpbmcgRXJyb3JdICR7Y29udGV4dH06YCwgZXJyb3IsIG1ldGFkYXRhKTtcblxuICAgICAgLy8gT3B0aW9uYWxseSBzZW5kIHRvIGVycm9yIHRyYWNraW5nIHNlcnZpY2VcbiAgICAgIC8vIHRoaXMuc2VuZFRvRXJyb3JUcmFja2luZyhlcnJvckVudHJ5KTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBBdHRlbXB0IHRvIHJlY292ZXIgZnJvbSBhbiBlcnJvciBhbmQgY29udGludWUgdG91clxuICAgICAqIEBwYXJhbSB7RXJyb3J9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdFxuICAgICAqIEBwYXJhbSB7bnVtYmVyfSBjdXJyZW50U3RlcCAtIEN1cnJlbnQgc3RlcCBpbmRleFxuICAgICAqIEByZXR1cm5zIHtPYmplY3R9IFJlY292ZXJ5IGFjdGlvblxuICAgICAqL1xuICAgIHJlY292ZXJGcm9tRXJyb3IoZXJyb3IsIGN1cnJlbnRTdGVwKSB7XG4gICAgICBjb25zdCBlcnJvclR5cGUgPSB0aGlzLmNsYXNzaWZ5RXJyb3IoZXJyb3IpO1xuXG4gICAgICBzd2l0Y2ggKGVycm9yVHlwZSkge1xuICAgICAgICBjYXNlICdFTEVNRU5UX05PVF9GT1VORCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignRWxlbWVudCBOb3QgRm91bmQnLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4geyBcbiAgICAgICAgICAgIGFjdGlvbjogJ1NLSVBfU1RFUCcsIFxuICAgICAgICAgICAgbmV4dFN0ZXA6IGN1cnJlbnRTdGVwICsgMSxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdUYXJnZXQgZWxlbWVudCBub3QgZm91bmQsIHNraXBwaW5nIHRvIG5leHQgc3RlcCdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ1NUT1JBR0VfVU5BVkFJTEFCTEUnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ1N0b3JhZ2UgVW5hdmFpbGFibGUnLCBlcnJvcik7XG4gICAgICAgICAgcmV0dXJuIHsgXG4gICAgICAgICAgICBhY3Rpb246ICdVU0VfTUVNT1JZX1NUT1JBR0UnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ0xvY2FsIHN0b3JhZ2UgdW5hdmFpbGFibGUsIHVzaW5nIGluLW1lbW9yeSBzdG9yYWdlJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnRFJJVkVSX05PVF9MT0FERUQnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ0RyaXZlci5qcyBOb3QgTG9hZGVkJywgZXJyb3IpO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdEcml2ZXIuanMgbGlicmFyeSBub3QgbG9hZGVkLCBjYW5ub3Qgc3RhcnQgdG91cidcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ0lOVkFMSURfVE9PTFRJUCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignSW52YWxpZCBUb29sdGlwIENvbmZpZ3VyYXRpb24nLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnU0tJUF9TVEVQJyxcbiAgICAgICAgICAgIG5leHRTdGVwOiBjdXJyZW50U3RlcCArIDEsXG4gICAgICAgICAgICBtZXNzYWdlOiAnSW52YWxpZCB0b29sdGlwIGNvbmZpZ3VyYXRpb24sIHNraXBwaW5nJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnVEhFTUVfREVURUNUSU9OX0ZBSUxFRCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVGhlbWUgRGV0ZWN0aW9uIEZhaWxlZCcsIGVycm9yKTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnVVNFX0RFRkFVTFRfVEhFTUUnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ1VzaW5nIGRlZmF1bHQgZGFyayB0aGVtZSdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVW5rbm93biBFcnJvcicsIGVycm9yLCB7IGN1cnJlbnRTdGVwIH0pO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdVbmV4cGVjdGVkIGVycm9yIG9jY3VycmVkLCBhYm9ydGluZyB0b3VyJ1xuICAgICAgICAgIH07XG4gICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQ2xhc3NpZnkgZXJyb3IgdHlwZVxuICAgICAqIEBwcml2YXRlXG4gICAgICogQHBhcmFtIHtFcnJvcn0gZXJyb3IgLSBUaGUgZXJyb3Igb2JqZWN0XG4gICAgICogQHJldHVybnMge3N0cmluZ30gRXJyb3IgdHlwZVxuICAgICAqL1xuICAgIGNsYXNzaWZ5RXJyb3IoZXJyb3IpIHtcbiAgICAgIGNvbnN0IG1lc3NhZ2UgPSBlcnJvci5tZXNzYWdlIHx8IGVycm9yLnRvU3RyaW5nKCk7XG5cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdlbGVtZW50JykgJiYgbWVzc2FnZS5pbmNsdWRlcygnbm90IGZvdW5kJykpIHtcbiAgICAgICAgcmV0dXJuICdFTEVNRU5UX05PVF9GT1VORCc7XG4gICAgICB9XG4gICAgICBpZiAobWVzc2FnZS5pbmNsdWRlcygnc3RvcmFnZScpIHx8IG1lc3NhZ2UuaW5jbHVkZXMoJ3F1b3RhJykpIHtcbiAgICAgICAgcmV0dXJuICdTVE9SQUdFX1VOQVZBSUxBQkxFJztcbiAgICAgIH1cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdkcml2ZXInKSB8fCBtZXNzYWdlLmluY2x1ZGVzKCd1bmRlZmluZWQnKSkge1xuICAgI Line truncated //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLyoqXG4gKiBFcnJvciBIYW5kbGVyXG4gKiBIYW5kbGVzIGVycm9ycyBncmFjZWZ1bGx5IHdpdGhvdXQgYnJlYWtpbmcgdGhlIG9uYm9hcmRpbmcgdG91clxuICovXG5cbihmdW5jdGlvbih3aW5kb3cpIHtcbiAgJ3VzZSBzdHJpY3QnO1xuXG4gIGNsYXNzIEVycm9ySGFuZGxlciB7XG4gICAgY29uc3RydWN0b3IoKSB7XG4gICAgICB0aGlzLmVycm9ycyA9IFtdO1xuICAgICAgdGhpcy5tYXhFcnJvcnMgPSA1MDsgLy8gS2VlcCBsYXN0IDUwIGVycm9yc1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIExvZyBhbiBlcnJvciB3aXRob3V0IGJyZWFraW5nIHRoZSB0b3VyXG4gICAgICogQHBhcmFtIHtzdHJpbmd9IGNvbnRleHQgLSBDb250ZXh0IHdoZXJlIGVycm9yIG9jY3VycmVkXG4gICAgICogQHBhcmFtIHtFcnJvcnxzdHJpbmd9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdCBvciBtZXNzYWdlXG4gICAgICogQHBhcmFtIHtPYmplY3R9IG1ldGFkYXRhIC0gQWRkaXRpb25hbCBtZXRhZGF0YVxuICAgICAqL1xuICAgIGxvZ0Vycm9yKGNvbnRleHQsIGVycm9yLCBtZXRhZGF0YSA9IHt9KSB7XG4gICAgICBjb25zdCBlcnJvckVudHJ5ID0ge1xuICAgICAgICB0aW1lc3RhbXA6IG5ldyBEYXRlKCkudG9JU09TdHJpbmcoKSxcbiAgICAgICAgY29udGV4dCxcbiAgICAgICAgbWVzc2FnZTogZXJyb3IgaW5zdGFuY2VvZiBFcnJvciA/IGVycm9yLm1lc3NhZ2UgOiBlcnJvcixcbiAgICAgICAgc3RhY2s6IGVycm9yIGluc3RhbmNlb2YgRXJyb3IgPyBlcnJvci5zdGFjayA6IG51bGwsXG4gICAgICAgIG1ldGFkYXRhXG4gICAgICB9O1xuXG4gICAgICAvLyBBZGQgdG8gZXJyb3JzIGFycmF5XG4gICAgICB0aGlzLmVycm9ycy5wdXNoKGVycm9yRW50cnkpO1xuXG4gICAgICAvLyBLZWVwIG9ubHkgbGFzdCBtYXhFcnJvcnNcbiAgICAgIGlmICh0aGlzLmVycm9ycy5sZW5ndGggPiB0aGlzLm1heEVycm9ycykge1xuICAgICAgICB0aGlzLmVycm9ycy5zaGlmdCgpO1xuICAgICAgfVxuXG4gICAgICAvLyBMb2cgdG8gY29uc29sZVxuICAgICAgY29uc29sZS5lcnJvcihgW09uYm9hcmRpbmcgRXJyb3JdICR7Y29udGV4dH06YCwgZXJyb3IsIG1ldGFkYXRhKTtcblxuICAgICAgLy8gT3B0aW9uYWxseSBzZW5kIHRvIGVycm9yIHRyYWNraW5nIHNlcnZpY2VcbiAgICAgIC8vIHRoaXMuc2VuZFRvRXJyb3JUcmFja2luZyhlcnJvckVudHJ5KTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBBdHRlbXB0IHRvIHJlY292ZXIgZnJvbSBhbiBlcnJvciBhbmQgY29udGludWUgdG91clxuICAgICAqIEBwYXJhbSB7RXJyb3J9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdFxuICAgICAqIEBwYXJhbSB7bnVtYmVyfSBjdXJyZW50U3RlcCAtIEN1cnJlbnQgc3RlcCBpbmRleFxuICAgICAqIEByZXR1cm5zIHtPYmplY3R9IFJlY292ZXJ5IGFjdGlvblxuICAgICAqL1xuICAgIHJlY292ZXJGcm9tRXJyb3IoZXJyb3IsIGN1cnJlbnRTdGVwKSB7XG4gICAgICBjb25zdCBlcnJvclR5cGUgPSB0aGlzLmNsYXNzaWZ5RXJyb3IoZXJyb3IpO1xuXG4gICAgICBzd2l0Y2ggKGVycm9yVHlwZSkge1xuICAgICAgICBjYXNlICdFTEVNRU5UX05PVF9GT1VORCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignRWxlbWVudCBOb3QgRm91bmQnLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4geyBcbiAgICAgICAgICAgIGFjdGlvbjogJ1NLSVBfU1RFUCcsIFxuICAgICAgICAgICAgbmV4dFN0ZXA6IGN1cnJlbnRTdGVwICsgMSxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdUYXJnZXQgZWxlbWVudCBub3QgZm91bmQsIHNraXBwaW5nIHRvIG5leHQgc3RlcCdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ1NUT1JBR0VfVU5BVkFJTEFCTEUnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ1N0b3JhZ2UgVW5hdmFpbGFibGUnLCBlcnJvcik7XG4gICAgICAgICAgcmV0dXJuIHsgXG4gICAgICAgICAgICBhY3Rpb246ICdVU0VfTUVNT1JZX1NUT1JBR0UnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ0xvY2FsIHN0b3JhZ2UgdW5hdmFpbGFibGUsIHVzaW5nIGluLW1lbW9yeSBzdG9yYWdlJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnRFJJVkVSX05PVF9MT0FERUQnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ0RyaXZlci5qcyBOb3QgTG9hZGVkJywgZXJyb3IpO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdEcml2ZXIuanMgbGlicmFyeSBub3QgbG9hZGVkLCBjYW5ub3Qgc3RhcnQgdG91cidcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ0lOVkFMSURfVE9PTFRJUCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignSW52YWxpZCBUb29sdGlwIENvbmZpZ3VyYXRpb24nLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnU0tJUF9TVEVQJyxcbiAgICAgICAgICAgIG5leHRTdGVwOiBjdXJyZW50U3RlcCArIDEsXG4gICAgICAgICAgICBtZXNzYWdlOiAnSW52YWxpZCB0b29sdGlwIGNvbmZpZ3VyYXRpb24sIHNraXBwaW5nJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnVEhFTUVfREVURUNUSU9OX0ZBSUxFRCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVGhlbWUgRGV0ZWN0aW9uIEZhaWxlZCcsIGVycm9yKTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnVVNFX0RFRkFVTFRfVEhFTUUnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ1VzaW5nIGRlZmF1bHQgZGFyayB0aGVtZSdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVW5rbm93biBFcnJvcicsIGVycm9yLCB7IGN1cnJlbnRTdGVwIH0pO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdVbmV4cGVjdGVkIGVycm9yIG9jY3VycmVkLCBhYm9ydGluZyB0b3VyJ1xuICAgICAgICAgIH07XG4gICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQ2xhc3NpZnkgZXJyb3IgdHlwZVxuICAgICAqIEBwcml2YXRlXG4gICAgICogQHBhcmFtIHtFcnJvcn0gZXJyb3IgLSBUaGUgZXJyb3Igb2JqZWN0XG4gICAgICogQHJldHVybnMge3N0cmluZ30gRXJyb3IgdHlwZVxuICAgICAqL1xuICAgIGNsYXNzaWZ5RXJyb3IoZXJyb3IpIHtcbiAgICAgIGNvbnN0IG1lc3NhZ2UgPSBlcnJvci5tZXNzYWdlIHx8IGVycm9yLnRvU3RyaW5nKCk7XG5cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdlbGVtZW50JykgJiYgbWVzc2FnZS5pbmNsdWRlcygnbm90IGZvdW5kJykpIHtcbiAgICAgICAgcmV0dXJuICdFTEVNRU5UX05PVF9GT1VORCc7XG4gICAgICB9XG4gICAgICBpZiAobWVzc2FnZS5pbmNsdWRlcygnc3RvcmFnZScpIHx8IG1lc3NhZ2UuaW5jbHVkZXMoJ3F1b3RhJykpIHtcbiAgICAgICAgcmV0dXJuICdTVE9SQUdFX1VOQVZBSUxBQkxFJztcbiAgICAgIH1cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdkcml2ZXInKSB8fCBtZXNzYWdlLmluY2x1ZGVzKCd1bmRlZmluZWQnKSkge1xuICAgI Line truncated
+253 -261
View File
@@ -90,57 +90,44 @@
<button id="logo-save" class="btn-accent">Save</button> <button id="logo-save" class="btn-accent">Save</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("logo-modal"),C=document.getElementById("logo-preview-dark"),O=document.getElementById("logo-preview-light"),E=document.getElementById("logo-status"),M=document.getElementById("logo-same-both"),R=document.getElementById("logo-dual-uploads"),P=document.getElementById("logo-single-upload"),A=document.getElementById("logo-upload-dark"),p=document.getElementById("logo-upload-light"),T=document.getElementById("logo-upload-single"),x=document.querySelector("#brand .brand-logo-dark"),$=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),H=document.getElementById("dashboard-title"),L=DC.NAME;let u=null,j=null,v=null,N="left",g=L;M?.addEventListener("change",()=>{M.checked?(R.style.display="none",P.style.display="",u=null,j=null):(R.style.display="flex",P.style.display="none",v=null)});function D(n,e){if(!n||!n.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const t=new FileReader;t.onload=o=>e(o.target.result),t.readAsDataURL(n)}A?.addEventListener("change",n=>{D(n.target.files[0],e=>{u=e,C.src=e,E.textContent="New dark logo ready to save"})}),p?.addEventListener("change",n=>{D(n.target.files[0],e=>{j=e,O.src=e,E.textContent="New light logo ready to save"})}),T?.addEventListener("change",n=>{D(n.target.files[0],e=>{v=e,C.src=e,O.src=e,E.textContent="New logo ready to save (both themes)"})});function B(n){k.setAttribute("data-logo-pos",n),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===n?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===n?"white":"var(--fg)"})}function f(n){g=n||L,document.title=g;const e=document.querySelector(".dashboard-title");e&&(e.textContent=g)}async function I(){try{const n=await fetch("/api/v1/logo");if(n.ok){const e=await n.json();e.customLogoDark&&(x.src=e.customLogoDark,C.src=e.customLogoDark),e.customLogoLight&&($.src=e.customLogoLight,O.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(x.src=e.customLogo,$.src=e.customLogo,C.src=e.customLogo,O.src=e.customLogo),e.isDefault||(E.textContent="Using custom logo"),e.position&&(N=e.position,B(e.position)),e.dashboardTitle&&f(e.dashboardTitle)}}catch(n){console.warn("Could not load custom logo:",n.message)}}document.querySelectorAll(".logo-pos-btn").forEach(n=>{n.addEventListener("click",()=>{N=n.dataset.pos,B(N)})}),document.getElementById("brand")?.addEventListener("click",()=>{u=null,j=null,v=null,A&&(A.value=""),p&&(p.value=""),T&&(T.value=""),M&&(M.checked=!1),R.style.display="flex",P.style.display="none",C.src=x.src,O.src=$.src;const n=x.src.includes("custom-logo")||$.src.includes("custom-logo");E.textContent=n?"Using custom logo":"Using default logos",B(N),H.value=g,y.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const n=H.value.trim()||L,e={position:N,dashboardTitle:n};M?.checked&&v?(e.dataDark=v,e.dataLight=v):(u&&(e.dataDark=u),j&&(e.dataLight=j));const t=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(t.ok){const o=await t.json(),r="?t="+Date.now();o.pathDark&&(x.src=o.pathDark+r,C.src=o.pathDark+r),o.pathLight&&($.src=o.pathLight+r,O.src=o.pathLight+r),B(N),f(n),y.classList.remove("show")}else{const o=await t.json();showNotification("Failed to save: "+o.error,"error")}}catch(n){showNotification("Error saving: "+n.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults? </div>`);const h=document.getElementById("logo-modal"),L=document.getElementById("logo-preview-dark"),R=document.getElementById("logo-preview-light"),S=document.getElementById("logo-status"),$=document.getElementById("logo-same-both"),P=document.getElementById("logo-dual-uploads"),N=document.getElementById("logo-single-upload"),D=document.getElementById("logo-upload-dark"),m=document.getElementById("logo-upload-light"),T=document.getElementById("logo-upload-single"),w=document.querySelector("#brand .brand-logo-dark"),B=document.querySelector("#brand .brand-logo-light"),E=document.querySelector(".top-row"),H=document.getElementById("dashboard-title"),C=DC.NAME;let v=null,O=null,f=null,z="left",A=C;$?.addEventListener("change",()=>{$.checked?(P.style.display="none",N.style.display="",v=null,O=null):(P.style.display="flex",N.style.display="none",f=null)});function U(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const s=new FileReader;s.onload=n=>e(n.target.result),s.readAsDataURL(t)}D?.addEventListener("change",t=>{U(t.target.files[0],e=>{v=e,L.src=e,S.textContent="New dark logo ready to save"})}),m?.addEventListener("change",t=>{U(t.target.files[0],e=>{O=e,R.src=e,S.textContent="New light logo ready to save"})}),T?.addEventListener("change",t=>{U(t.target.files[0],e=>{f=e,L.src=e,R.src=e,S.textContent="New logo ready to save (both themes)"})});function p(t){E.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function u(t){A=t||C,document.title=A;const e=document.querySelector(".dashboard-title");e&&(e.textContent=A)}async function b(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(w.src=e.customLogoDark,L.src=e.customLogoDark),e.customLogoLight&&(B.src=e.customLogoLight,R.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(w.src=e.customLogo,B.src=e.customLogo,L.src=e.customLogo,R.src=e.customLogo),e.isDefault||(S.textContent="Using custom logo"),e.position&&(z=e.position,p(e.position)),e.dashboardTitle&&u(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{z=t.dataset.pos,p(z)})}),document.getElementById("brand")?.addEventListener("click",()=>{v=null,O=null,f=null,D&&(D.value=""),m&&(m.value=""),T&&(T.value=""),$&&($.checked=!1),P.style.display="flex",N.style.display="none",L.src=w.src,R.src=B.src;const t=w.src.includes("custom-logo")||B.src.includes("custom-logo");S.textContent=t?"Using custom logo":"Using default logos",p(z),H.value=A,h.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=H.value.trim()||C,e={position:z,dashboardTitle:t};$?.checked&&f?(e.dataDark=f,e.dataLight=f):(v&&(e.dataDark=v),O&&(e.dataLight=O));const s=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(s.ok){const n=await s.json(),i="?t="+Date.now();n.pathDark&&(w.src=n.pathDark+i,L.src=n.pathDark+i),n.pathLight&&(B.src=n.pathLight+i,R.src=n.pathLight+i),p(z),u(t),h.classList.remove("show")}else{const n=await s.json();showNotification("Failed to save: "+n.error,"error")}}catch(t){showNotification("Error saving: "+t.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults?
This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(x.src="/assets/dashcaddy-logo-dark.png",$.src="/assets/dashcaddy-logo-light.png",C.src="/assets/dashcaddy-logo-dark.png",O.src="/assets/dashcaddy-logo-light.png",E.textContent="Using default logos",u=null,j=null,v=null,H.value=L,f(L),N="left",B("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const t=document.querySelector('link[rel="icon"]'),o=document.getElementById("favicon-preview"),r=document.getElementById("favicon-status");t&&(t.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),o&&(o.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),r&&(r.textContent="Using DashCaddy favicon"),l=null}}catch(n){showNotification("Error resetting branding: "+n.message,"error")}}),wireModal(y,document.getElementById("logo-cancel"));const b=document.getElementById("favicon-preview"),z=document.getElementById("favicon-status"),i=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let l=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function w(){try{const n=await fetch("/api/v1/favicon");if(n.ok){const e=await n.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),b.src=e.customFavicon+"?t="+Date.now(),z.textContent="Using custom favicon")}}catch(n){console.warn("Could not load custom favicon:",n.message)}}i?.addEventListener("change",n=>{const e=n.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),i.value="";return}const t=new FileReader;t.onload=o=>{l=o.target.result,b.src=l,z.textContent="New favicon ready to save"},t.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(l)try{const n=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:l})});if(n.ok){const e=await n.json();c.href=e.path+"?t="+Date.now(),b.src=e.path+"?t="+Date.now(),z.textContent="Using custom favicon",l=null}else{const e=await n.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(n){showNotification("Error saving favicon: "+n.message,"error")}}),w(),I();const m=document.getElementById("settings-timezone");m&&(new MutationObserver(()=>{y.classList.contains("show")&&m.options.length===0&&(async()=>{let e;try{const t=await fetch("/api/v1/config");t.ok&&(e=(await t.json()).timezone)}catch{}window.populateTimezoneSelect(m,e)})()}).observe(y,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=m.value;if(e)try{const t=await fetch("/api/v1/config");if(!t.ok)return;const o=await t.json();o.timezone=e,o.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(t){console.warn("Failed to save timezone:",t.message)}}))})(),window.populateTimezoneSelect=function(y,C){const O=Intl.supportedValuesOf("timeZone"),E=C||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";y.innerHTML="";for(const M of O){const R=document.createElement("option");R.value=M,R.textContent=M.replace(/_/g," "),M===E&&(R.selected=!0),y.appendChild(R)}},(function(){let y="homelab",C=null;async function O(){try{const D=await fetch("/api/v1/config");if(D.ok&&(C=await D.json(),C&&C.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(D){console.warn("Could not fetch server config, checking localStorage fallback:",D.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}O();const E=document.getElementById("setup-timezone");E&&window.populateTimezoneSelect(E);function M(g){document.querySelectorAll(".setup-step").forEach(B=>{B.style.display="none"});const D=document.getElementById(g);D&&(D.style.display="block")}function R(){const g=document.getElementById("setup-summary-content");if(!g)return;let D='<div style="display: grid; gap: 20px;">';if(y==="homelab"){const f=document.getElementById("setup-tld")?.value?.trim()||".home",I=document.getElementById("setup-ca-name")?.value?.trim()||"",b=document.getElementById("setup-dns-ip")?.value?.trim()||"",z=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;D+=` This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(w.src="/assets/dashcaddy-logo-dark.png",B.src="/assets/dashcaddy-logo-light.png",L.src="/assets/dashcaddy-logo-dark.png",R.src="/assets/dashcaddy-logo-light.png",S.textContent="Using default logos",v=null,O=null,f=null,H.value=C,u(C),z="left",p("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const s=document.querySelector('link[rel="icon"]'),n=document.getElementById("favicon-preview"),i=document.getElementById("favicon-status");s&&(s.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),n&&(n.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),i&&(i.textContent="Using DashCaddy favicon"),d=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(h,document.getElementById("logo-cancel"));const g=document.getElementById("favicon-preview"),M=document.getElementById("favicon-status"),r=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let d=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function x(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),g.src=e.customFavicon+"?t="+Date.now(),M.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}r?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),r.value="";return}const s=new FileReader;s.onload=n=>{d=n.target.result,g.src=d,M.textContent="New favicon ready to save"},s.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(d)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:d})});if(t.ok){const e=await t.json();c.href=e.path+"?t="+Date.now(),g.src=e.path+"?t="+Date.now(),M.textContent="Using custom favicon",d=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),x(),b();const y=document.getElementById("settings-timezone");y&&(new MutationObserver(()=>{h.classList.contains("show")&&y.options.length===0&&(async()=>{let e;try{const s=await fetch("/api/v1/config");s.ok&&(e=(await s.json()).timezone)}catch{}window.populateTimezoneSelect(y,e)})()}).observe(h,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=y.value;if(e)try{const s=await fetch("/api/v1/config");if(!s.ok)return;const n=await s.json();n.timezone=e,n.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}catch(s){console.warn("Failed to save timezone:",s.message)}}))})(),window.populateTimezoneSelect=function(h,L){const R=Intl.supportedValuesOf("timeZone"),S=L||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";h.innerHTML="";for(const $ of R){const P=document.createElement("option");P.value=$,P.textContent=$.replace(/_/g," "),$===S&&(P.selected=!0),h.appendChild(P)}},(function(){let h="homelab",L=null;async function R(){try{const u=await fetch("/api/v1/config");if(u.ok&&(L=await u.json(),L&&L.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(u){console.warn("Could not fetch server config, checking localStorage fallback:",u.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}R();const S=document.getElementById("setup-timezone");S&&window.populateTimezoneSelect(S);function $(p){document.querySelectorAll(".setup-step").forEach(b=>{b.style.display="none"});const u=document.getElementById(p);u&&(u.style.display="block")}function P(){const p=document.getElementById("setup-summary-content");if(!p)return;let u='<div style="display: grid; gap: 20px;">';if(h==="homelab"){const g=document.getElementById("setup-tld")?.value?.trim()||".home",M=document.getElementById("setup-ca-name")?.value?.trim()||"",r=document.getElementById("setup-dns-ip")?.value?.trim()||"",c=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;u+=`
<div> <div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Home Lab Configuration</h3> <h3 style="margin: 0 0 12px; color: var(--accent);">Home Lab Configuration</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;"> <div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>TLD:</strong> ${f}</div> <div><strong>TLD:</strong> ${g}</div>
<div><strong>Certificate Authority:</strong> ${I}</div> <div><strong>Certificate Authority:</strong> ${M}</div>
<div><strong>DNS Server:</strong> ${b}:${z}</div> <div><strong>DNS Server:</strong> ${r}:${c}</div>
<div><strong>Example URLs:</strong> https://uptime${f}, https://nextcloud${f}</div> <div><strong>Example URLs:</strong> https://uptime${g}, https://nextcloud${g}</div>
</div> </div>
</div> </div>
`}else if(y==="simple"){const f=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";D+=` `}else if(h==="simple"){const g=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";u+=`
<div> <div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Simple Setup</h3> <h3 style="margin: 0 0 12px; color: var(--accent);">Simple Setup</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;"> <div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Access Method:</strong> IP:Port only</div> <div><strong>Access Method:</strong> IP:Port only</div>
<div><strong>Default IP:</strong> ${f}</div> <div><strong>Default IP:</strong> ${g}</div>
<div><strong>SSL:</strong> None (HTTP only)</div> <div><strong>SSL:</strong> None (HTTP only)</div>
<div><strong>Example URLs:</strong> http://${f}:8080, http://${f}:3000</div> <div><strong>Example URLs:</strong> http://${g}:8080, http://${g}:3000</div>
</div> </div>
</div> </div>
`}else if(y==="public"){const f=document.getElementById("setup-public-domain")?.value?.trim()||"",I=document.getElementById("setup-public-email")?.value?.trim()||"",b=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",z=b==="subdirectory"?`https://${f}/sonarr, https://${f}/grafana`:`https://sonarr.${f}, https://grafana.${f}`;D+=` `}else if(h==="public"){const g=document.getElementById("setup-public-domain")?.value?.trim()||"",M=document.getElementById("setup-public-email")?.value?.trim()||"",r=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",c=r==="subdirectory"?`https://${g}/sonarr, https://${g}/grafana`:`https://sonarr.${g}, https://grafana.${g}`;u+=`
<div> <div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Public Server</h3> <h3 style="margin: 0 0 12px; color: var(--accent);">Public Server</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;"> <div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Domain:</strong> ${f}</div> <div><strong>Domain:</strong> ${g}</div>
<div><strong>SSL:</strong> Let's Encrypt</div> <div><strong>SSL:</strong> Let's Encrypt</div>
<div><strong>Email:</strong> ${I}</div> <div><strong>Email:</strong> ${M}</div>
<div><strong>Routing:</strong> ${b==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div> <div><strong>Routing:</strong> ${r==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div>
<div><strong>Example URLs:</strong> ${z}</div> <div><strong>Example URLs:</strong> ${c}</div>
</div> </div>
</div> </div>
`}const B=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";D+=` `}const b=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";u+=`
<div style="margin-top: 8px; padding-top: 12px; border-top: 1px solid var(--border);"> <div style="margin-top: 8px; padding-top: 12px; border-top: 1px solid var(--border);">
<div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${B.replace(/_/g," ")}</div> <div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${b.replace(/_/g," ")}</div>
</div> </div>
`,D+=` `,u+="</div>",p.innerHTML=u,$("setup-step-summary")}async function N(p){try{const u=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});return u.ok?(await u.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${u.status}`),{function:"saveConfigToServer"}),!1)}catch(u){return errorHandler.logError("[SetupWizard] Save Config",u,{function:"saveConfigToServer"}),!1}}async function D(){const p={setupComplete:!0,configurationType:h,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(h==="homelab"){p.tld=document.getElementById("setup-tld")?.value?.trim()||".home",p.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const M=document.getElementById("setup-dns-provider")?.value||"technitium";p.dns={provider:M,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},p.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else h==="simple"?(p.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",p.defaults={dnsType:"none",sslType:"none",targetIP:p.defaultIP}):h==="public"&&(p.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",p.email=document.getElementById("setup-public-email")?.value?.trim()||"",p.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",p.defaults={dnsType:p.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const u=await N(p);safeSet("dashcaddy-config",JSON.stringify(p)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const b=h==="homelab"?"Professional Home Lab":h==="simple"?"Simple Setup":"Public Server",g=u?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${b}. Settings saved to: ${g}`,"success",5e3),setTimeout(()=>location.reload(),500)}const m=document.getElementById("setup-step-1-next");m&&(m.onclick=function(p){p.preventDefault();const u=document.querySelector('input[name="config-type"]:checked');u&&(h=u.value),$(h==="homelab"?"setup-step-homelab":h==="simple"?"setup-step-simple":h==="public"?"setup-step-public":"setup-step-homelab")});const T=document.getElementById("setup-skip");T&&(T.onclick=async function(p){p.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await N({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const w=document.getElementById("setup-tld");w&&(w.oninput=function(p){const u=p.target.value||".home",b=document.getElementById("tld-preview"),g=document.getElementById("tld-preview-2");b&&(b.textContent=u),g&&(g.textContent=u)});const B=document.getElementById("setup-homelab-back");B&&(B.onclick=function(p){p.preventDefault(),$("setup-step-1")});const E=document.getElementById("setup-homelab-next");E&&(E.onclick=function(p){p.preventDefault();const u=document.getElementById("setup-tld")?.value?.trim()||"",b=document.getElementById("setup-ca-name")?.value?.trim()||"",g=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!u||!u.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!b){showNotification("Please enter a Certificate Authority name","warning");return}if(!g){showNotification("Please enter your DNS server IP address","warning");return}P()});const H=document.getElementById("setup-simple-back");H&&(H.onclick=function(p){p.preventDefault(),$("setup-step-1")});const C=document.getElementById("setup-simple-next");C&&(C.onclick=function(p){p.preventDefault(),P()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(p){p.onchange=function(){var u=document.getElementById("dns-requirement-note");u&&(u.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const v=document.getElementById("setup-public-back");v&&(v.onclick=function(p){p.preventDefault(),$("setup-step-1")});const O=document.getElementById("setup-public-next");O&&(O.onclick=function(p){p.preventDefault();const u=document.getElementById("setup-public-domain")?.value?.trim()||"",b=document.getElementById("setup-public-email")?.value?.trim()||"";if(!u){showNotification("Please enter your domain name","warning");return}if(!b||!b.includes("@")){showNotification("Please enter a valid email address","warning");return}P()});const f=document.getElementById("setup-summary-back");f&&(f.onclick=function(p){p.preventDefault(),h==="homelab"?$("setup-step-homela Line truncated
<div style="margin-top: 12px; padding: 12px 14px; border-radius: 8px; border: 1px solid var(--warn-fg, #f39c12); background: color-mix(in srgb, var(--warn-fg, #f39c12) 8%, transparent);">
<div style="display: flex; gap: 8px; align-items: flex-start;">
<span style="font-size: 1.1rem;">\u{1F4BE}</span>
<div style="font-size: 0.85rem; line-height: 1.45;">
<strong style="color: var(--warn-fg, #f39c12);">Disk-space tip:</strong>
Health-check monitoring records uptime, response-time, and incident data continuously.
By default DashCaddy keeps <strong>30 days</strong> of history and warns at <strong>80% disk usage</strong>.
You can tune the retention period, polling interval, and disk threshold later under
<strong>Health \u2192 Configure \u2192 Global Settings</strong>.
</div>
</div>
</div>
`,D+="</div>",g.innerHTML=D,M("setup-step-summary")}async function P(g){try{const D=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});return D.ok?(await D.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${D.status}`),{function:"saveConfigToServer"}),!1)}catch(D){return errorHandler.logError("[SetupWizard] Save Config",D,{function:"saveConfigToServer"}),!1}}async function A(){const g={setupComplete:!0,configurationType:y,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(y==="homelab"){g.tld=document.getElementById("setup-tld")?.value?.trim()||".home",g.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const I=document.getElementById("setup-dns-provider")?.value||"technitium";g.dns={provider:I,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},g.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else y==="simple"?(g.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",g.defaults={dnsType:"none",sslType:"none",targetIP:g.defaultIP}):y==="public"&&(g.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",g.email=document.getElementById("setup-public-email")?.value?.trim()||"",g.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",g.defaults={dnsType:g.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const D=await P(g);safeSet("dashcaddy-config",JSON.stringify(g)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const B=y==="homelab"?"Professional Home Lab":y==="simple"?"Simple Setup":"Public Server",f=D?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${B}. Settings saved to: ${f}`,"success",5e3),setTimeout(()=>location.reload(),500)}const p=document.getElementById("setup-step-1-next");p&&(p.onclick=function(g){g.preventDefault();const D=document.querySelector('input[name="config-type"]:checked');D&&(y=D.value),M(y==="homelab"?"setup-step-homelab":y==="simple"?"setup-step-simple":y==="public"?"setup-step-public":"setup-step-homelab")});const T=document.getElementById("setup-skip");T&&(T.onclick=async function(g){g.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await P({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const x=document.getElementById("setup-tld");x&&(x.oninput=function(g){const D=g.target.value||".home",B=document.getElementById("tld-preview"),f=document.getElementById("tld-preview-2");B&&(B.textContent=D),f&&(f.textContent=D)});const $=document.getElementById("setup-homelab-back");$&&($.onclick=function(g){g.preventDefault(),M("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(g){g.preventDefault();const D=document.getElementById("setup-tld")?.value?.trim()||"",B=document.getElementById("setup-ca-name")?.value?.trim()||"",f=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!D||!D.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!B){showNotification("Please enter a Certificate Authority name","warning");return}if(!f){showNotification("Please enter your DNS server IP address","warning");return}R()});const H=document.getElementById("setup-simple-back");H&&(H.onclick=function(g){g.preventDefault(),M("setup-step-1")});const L=document.getElementById("setup-simple-next");L&&(L.onclick=function(g){g.preventDefault(),R()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(g){g.onchange=function(){var D=document.getElementById("dns-requirement-note");D&&(D.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const u=document.getElementById("setup-public-back");u&&(u.onclick=function(g){g.preventDefault(),M("setup-step-1")});const j=document.getElementById("setup-public-next");j&&(j.onclick=function(g){g.preventDefault();const D=document.getElementById("setup-public-domain")?.value?.trim()||"",B=document.getElementById("setup-public-email")?.value?.trim()||"";if(!D){showNotification("Please enter your domain name","warning");return}if(!B||!B.includes("@")){showNotification("Please enter a valid email address","warning");return}R()});const v=document.getElementById("setup-summary-back");v&&(v.onclick=function(g){g.preventDefault(),y==="homelab"?M("setup-step-homela Line truncated
<div class="app-selector-content"> <div class="app-selector-content">
<h2 style="margin: 0 0 24px; color: var(--fg); text-align: center;">Choose an App</h2> <h2 style="margin: 0 0 24px; color: var(--fg); text-align: center;">Choose an App</h2>
<div id="app-selector-grid" class="app-selector-grid"></div> <div id="app-selector-grid" class="app-selector-grid"></div>
@@ -346,12 +333,12 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
</button> </button>
</div> </div>
</div> </div>
</div>`);const C="custom-apps";let O=null,E=null;const M=document.getElementById("app-selector-modal"),R=document.getElementById("app-selector-grid");async function P(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return O=c.templates,E=c.categories,!0}catch(i){y.logError("[AppSelector] Fetch Templates",i,{function:"fetchApiTemplates"})}return!1}async function A(i){try{return await(await fetch(`/api/v1/apps/ports/${i}/check`)).json()}catch(c){return y.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function p(i){try{const l=await(await fetch(`/api/v1/apps/ports/${i}/suggest`)).json();if(l.success)return l.suggestedPort}catch(c){y.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return i}async function T(){if(R.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!O&&!await P()){R.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}R.innerHTML="";const i={};for(const[l,w]of Object.entries(O)){const m=w.category||"Other";i[m]||(i[m]=[]),i[m].push({id:l,...w})}const c=E?Object.keys(E):Object.keys(i).sort();for(const l of c){const w=i[l];if(!w||w.length===0)continue;w.sort((e,t)=>(t.popularity||0)-(e.popularity||0));const m=document.createElement("div");m.className="app-category-header";const n=E?.[l]||{};m.innerHTML=`${escapeHtml(n.icon||"")} ${escapeHtml(l)}`,n.color&&(m.style.borderBottomColor=n.color),R.appendChild(m),w.forEach(e=>{const t=document.createElement("div");t.className="app-option";const o=e.isDashboardWidget,r=o&&safeGet("widget-"+e.id+"-enabled")!=="false",a=o?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${r?"#2ecc7130":"#e74c3c30"}; color: ${r?"#2ecc71":"#e74c3c"}; font-weight: 600;">${r?"ON":"OFF"}</div>`:"",s=!o&&e.difficulty?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"}20; color: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"};">${escapeHtml(e.difficulty)}</div>`:"";t.innerHTML=` </div>`);const L="custom-apps";let R=null,S=null;const $=document.getElementById("app-selector-modal"),P=document.getElementById("app-selector-grid");async function N(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return R=c.templates,S=c.categories,!0}catch(r){h.logError("[AppSelector] Fetch Templates",r,{function:"fetchApiTemplates"})}return!1}async function D(r){try{return await(await fetch(`/api/v1/apps/ports/${r}/check`)).json()}catch(c){return h.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function m(r){try{const d=await(await fetch(`/api/v1/apps/ports/${r}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){h.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return r}async function T(){if(P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!R&&!await N()){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}P.innerHTML="";const r={};for(const[d,x]of Object.entries(R)){const y=x.category||"Other";r[y]||(r[y]=[]),r[y].push({id:d,...x})}const c=S?Object.keys(S):Object.keys(r).sort();for(const d of c){const x=r[d];if(!x||x.length===0)continue;x.sort((e,s)=>(s.popularity||0)-(e.popularity||0));const y=document.createElement("div");y.className="app-category-header";const t=S?.[d]||{};y.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(d)}`,t.color&&(y.style.borderBottomColor=t.color),P.appendChild(y),x.forEach(e=>{const s=document.createElement("div");s.className="app-option";const n=e.isDashboardWidget,i=n&&safeGet("widget-"+e.id+"-enabled")!=="false",a=n?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${i?"#2ecc7130":"#e74c3c30"}; color: ${i?"#2ecc71":"#e74c3c"}; font-weight: 600;">${i?"ON":"OFF"}</div>`:"",o=!n&&e.difficulty?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"}20; color: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"};">${escapeHtml(e.difficulty)}</div>`:"";s.innerHTML=`
<div class="app-option-icon">${escapeHtml(e.icon||"\u{1F4E6}")}</div> <div class="app-option-icon">${escapeHtml(e.icon||"\u{1F4E6}")}</div>
<div class="app-option-name">${escapeHtml(e.name)}</div> <div class="app-option-name">${escapeHtml(e.name)}</div>
<div class="app-option-desc">${escapeHtml(e.description||"")}</div> <div class="app-option-desc">${escapeHtml(e.description||"")}</div>
${a}${s} ${a}${o}
`,o?t.onclick=()=>x(e,t):t.onclick=()=>$(e),R.appendChild(t)})}window.renderRecipeCards&&await window.renderRecipeCards(R)}function x(i,c){const l="widget-"+i.id+"-enabled",m=!(safeGet(l)!=="false");safeSet(l,String(m));const n=i.widgetSelector;if(n){const t=document.querySelector(n);t&&(t.style.display=m?"":"none")}const e=c.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=m?"ON":"OFF",e.style.background=m?"#2ecc7130":"#e74c3c30",e.style.color=m?"#2ecc71":"#e74c3c"),showNotification(`${i.name} widget ${m?"enabled":"disabled"}`,"success",2e3)}async function $(i){const c=document.getElementById("app-deploy-modal"),l=document.getElementById("app-deploy-title"),w=document.getElementById("deploy-subdomain"),m=document.getElementById("deploy-url-preview"),n=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),t=document.getElementById("deploy-tailscale-only"),o=document.getElementById("tailscale-status");try{const G=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:i.id})})).json();if(G.success&&G.exists){const V=G.container;confirm(`Found existing ${i.name} container: `,n?s.onclick=()=>w(e,s):s.onclick=()=>B(e),P.appendChild(s)})}window.renderRecipeCards&&await window.renderRecipeCards(P)}function w(r,c){const d="widget-"+r.id+"-enabled",y=!(safeGet(d)!=="false");safeSet(d,String(y));const t=r.widgetSelector;if(t){const s=document.querySelector(t);s&&(s.style.display=y?"":"none")}const e=c.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=y?"ON":"OFF",e.style.background=y?"#2ecc7130":"#e74c3c30",e.style.color=y?"#2ecc71":"#e74c3c"),showNotification(`${r.name} widget ${y?"enabled":"disabled"}`,"success",2e3)}async function B(r){const c=document.getElementById("app-deploy-modal"),d=document.getElementById("app-deploy-title"),x=document.getElementById("deploy-subdomain"),y=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),s=document.getElementById("deploy-tailscale-only"),n=document.getElementById("tailscale-status");try{const W=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:r.id})})).json();if(W.success&&W.exists){const V=W.container;confirm(`Found existing ${r.name} container:
Container: ${V.name} Container: ${V.name}
Status: ${V.status} Status: ${V.status}
@@ -360,38 +347,38 @@ Port: ${V.primaryPort||"N/A"}
Would you like to use this existing container? Would you like to use this existing container?
Click OK to configure DNS/Caddy for the existing container. Click OK to configure DNS/Caddy for the existing container.
Click Cancel to deploy a new container.`)&&(i._useExisting=!0,i._existingContainer=V)}}catch{}l.textContent=`Deploy ${i.name}`;const r=i.subdomain||i.id.replace(/-/g,"");w.value=r;const a=document.getElementById("subpath-compat-warning");if(a)if(SITE.routingMode==="subdirectory"){const q=i.subpathSupport||"strip";q==="none"?(a.style.display="block",a.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+i.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):q==="strip"?(a.style.display="block",a.innerHTML='<span style="color: var(--muted);">&#9432; '+i.name+" has unverified subdirectory support. It may require additional configuration.</span>"):a.style.display="none"}else a.style.display="none";const s=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),d=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),S=document.querySelector(`input[name="dns-type"][value="${s}"]`),h=document.querySelector(`input[name="ssl-type"][value="${d}"]`);S?S.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,h?h.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,n.value=SITE.defaults.targetIP||"localhost",t.checked=!1;const U=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),F=_?.querySelector("div");if(_&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const q=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,G=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;q&&!q.dataset.moved&&(F.appendChild(q),q.dataset.moved="1"),G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1")}const W=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(i.mediaMount){W.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const q=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){q.style.display="block",G.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`<span style="font-weight: 500;">${escapeHtml(ee.folderName)}</span><br><span style="font-size: 0.7rem; color: var(--muted);">from ${escapeHtml(ee.sourceImage)}</span>`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},G.appendChild(Z)})}else q.style.display="none"}catch{q.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else W.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(i.id==="plex"||i.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",i.docker?.volumes?.length){const q=i.mediaMount?.containerPath,G=i.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(q&&V.endsWith(":"+q)));G.length>0?(ne.style.display="block",G.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=` Click Cancel to deploy a new container.`)&&(r._useExisting=!0,r._existingContainer=V)}}catch{}d.textContent=`Deploy ${r.name}`;const i=r.subdomain||r.id.replace(/-/g,"");x.value=i;const a=document.getElementById("subpath-compat-warning");if(a)if(SITE.routingMode==="subdirectory"){const J=r.subpathSupport||"strip";J==="none"?(a.style.display="block",a.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+r.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):J==="strip"?(a.style.display="block",a.innerHTML='<span style="color: var(--muted);">&#9432; '+r.name+" has unverified subdirectory support. It may require additional configuration.</span>"):a.style.display="none"}else a.style.display="none";const o=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),l=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),k=document.querySelector(`input[name="dns-type"][value="${o}"]`),I=document.querySelector(`input[name="ssl-type"][value="${l}"]`);k?k.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,I?I.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",s.checked=!1;const j=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),F=_?.querySelector("div");if(_&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const J=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,W=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;J&&!J.dataset.moved&&(F.appendChild(J),J.dataset.moved="1"),W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1")}const q=document.getElementById("media-path-section"),G=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(r.mediaMount){q.style.display="block",G.value="",G.placeholder="/media/Movies, /media/TVShows or click Browse";const J=document.getElementById("detected-mounts-container"),W=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){J.style.display="block",W.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];G.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`<span style="font-weight: 500;">${escapeHtml(ee.folderName)}</span><br><span style="font-size: 0.7rem; color: var(--muted);">from ${escapeHtml(ee.sourceImage)}</span>`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=G.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),G.value=le.join(", ")},W.appendChild(Z)})}else J.style.display="none"}catch{J.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(G)}}else q.style.display="none",G.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(r.id==="plex"||r.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",r.docker?.volumes?.length){const J=r.mediaMount?.containerPath,W=r.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(J&&V.endsWith(":"+J)));W.length>0?(ne.style.display="block",W.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=`
<input type="text" class="vol-host-path" data-container-path="${ee}" value="${te}" <input type="text" class="vol-host-path" data-container-path="${ee}" value="${te}"
style="flex: 1; padding: 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem;" /> style="flex: 1; padding: 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem;" />
<span style="color: var(--muted); font-size: 0.85rem; white-space: nowrap;">\u2192 ${ee}</span> <span style="color: var(--muted); font-size: 0.85rem; white-space: nowrap;">\u2192 ${ee}</span>
<button type="button" class="vol-browse-btn" style="padding: 8px 10px; background: var(--accent); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.8rem;">\u{1F4C2}</button> <button type="button" class="vol-browse-btn" style="padding: 8px 10px; background: var(--accent); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.8rem;">\u{1F4C2}</button>
`,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=i.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const q=e.value||se;Y.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const G=await A(q);if(G.available)Y.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(q))} is available</span>`;else{const V=await p(se);Y.innerHTML=` `,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=r.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const J=e.value||se;Y.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const W=await D(J);if(W.available)Y.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(J))} is available</span>`;else{const V=await m(se);Y.innerHTML=`
<span style="color: #e74c3c;">Port ${escapeHtml(q)} in use by ${escapeHtml(G.conflict?.usedBy||"unknown")}</span> <span style="color: #e74c3c;">Port ${escapeHtml(J)} in use by ${escapeHtml(W.conflict?.usedBy||"unknown")}</span>
`;const K=document.createElement("button");K.type="button",K.textContent=`Use ${V}`,K.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",K.onclick=()=>{document.getElementById("deploy-port").value=V,Y.innerHTML=`<span style="color: #4caf50;">Using suggested port ${escapeHtml(String(V))}</span>`},Y.appendChild(K)}}let re;e.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const G=await(await fetch("/api/v1/tailscale/status")).json();G.success&&G.installed&&G.connected?o.innerHTML=` `;const K=document.createElement("button");K.type="button",K.textContent=`Use ${V}`,K.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",K.onclick=()=>{document.getElementById("deploy-port").value=V,Y.innerHTML=`<span style="color: #4caf50;">Using suggested port ${escapeHtml(String(V))}</span>`},Y.appendChild(K)}}let re;e.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const W=await(await fetch("/api/v1/tailscale/status")).json();W.success&&W.installed&&W.connected?n.innerHTML=`
<span style="color: #4caf50;">Connected</span> <span style="color: #4caf50;">Connected</span>
<span style="color: var(--muted); margin-left: 8px;">${G.self?.hostname} (${G.self?.ip})</span> <span style="color: var(--muted); margin-left: 8px;">${W.self?.hostname} (${W.self?.ip})</span>
<span style="color: var(--muted); margin-left: 8px;">| ${G.deviceCount} devices</span> <span style="color: var(--muted); margin-left: 8px;">| ${W.deviceCount} devices</span>
`:G.installed?o.innerHTML='<span style="color: #ff9800;">Not connected</span>':(o.innerHTML='<span style="color: var(--muted);">Not available</span>',t.disabled=!0)}catch{o.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function ae(){const q=w.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${q}`;else if(G==="private")K=`${V==="none"?"http":"https"}://${buildDomain(q)}`;else if(G==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||q;K=SITE.domain?`${te}://${q}.${SITE.domain}`:`${te}://${q}`}else{const te=e.value||i.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${n.value}:${te}`}m.textContent=K}w.oninput=ae,n.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(q=>{q.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(q=>{q.onchange=ae}),ae(),M.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(i)}async function k(i){const c=i.appTemplate,l=safeGetJSON(C,[]),w=c._useExisting&&c._existingContainer,m=l.find(n=>n.id===i.subdomain);if(!(m&&!w&&!confirm(`An app with subdomain "${i.subdomain}" already exists. Redeploy?`))){if(m){const n=l.indexOf(m);l.splice(n,1),safeSet(C,JSON.stringify(l))}if(w)i.port=c._existingContainer.primaryPort;else{const n=i.port||c.defaultPort||8080;showNotification(`Checking port ${n} availability...`,"info",0);const e=await A(n);if(!e.available){const t=await p(c.defaultPort||8080);if(confirm(`Port ${n} is already in use by ${e.conflict?.usedBy||"another container"}. `:W.installed?n.innerHTML='<span style="color: #ff9800;">Not connected</span>':(n.innerHTML='<span style="color: var(--muted);">Not available</span>',s.disabled=!0)}catch{n.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function ae(){const J=x.value||"subdomain",W=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${J}`;else if(W==="private")K=`${V==="none"?"http":"https"}://${buildDomain(J)}`;else if(W==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||J;K=SITE.domain?`${te}://${J}.${SITE.domain}`:`${te}://${J}`}else{const te=e.value||r.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}y.textContent=K}x.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(J=>{J.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(J=>{J.onchange=ae}),ae(),$.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(r)}async function E(r){const c=r.appTemplate,d=safeGetJSON(L,[]),x=c._useExisting&&c._existingContainer,y=d.find(t=>t.id===r.subdomain);if(!(y&&!x&&!confirm(`An app with subdomain "${r.subdomain}" already exists. Redeploy?`))){if(y){const t=d.indexOf(y);d.splice(t,1),safeSet(L,JSON.stringify(d))}if(x)r.port=c._existingContainer.primaryPort;else{const t=r.port||c.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await D(t);if(!e.available){const s=await m(c.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}.
Would you like to use port ${t} instead?`))i.port=t;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(w?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const n={appId:c.id,config:{subdomain:i.subdomain,ip:i.ip,createDns:i.dnsType==="private",port:i.port||c.defaultPort||null,sslType:i.sslType,dnsType:i.dnsType,tailscaleOnly:i.tailscaleOnly||!1,mediaPath:i.mediaPath||null,plexClaimToken:i.plexClaimToken||null,customVolumes:i.customVolumes||null}};w&&(n.config.useExisting=!0,n.config.existingContainerId=c._existingContainer.id,n.config.existingPort=c._existingContainer.primaryPort,!i.port&&c._existingContainer.primaryPort&&(n.config.port=c._existingContainer.primaryPort));const t=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(t.success){const o={id:i.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:t.containerId,url:t.url,ip:i.ip,appTemplate:c.id,tailscaleOnly:i.tailscaleOnly||!1};l.push(o),safeSet(C,JSON.stringify(l)),window.APPS&&!window.APPS.some(a=>a.id===c.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let r=t.usedExisting?`${c.name} configured with existing container! Would you like to use port ${s} instead?`))r.port=s;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(x?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const t={appId:c.id,config:{subdomain:r.subdomain,ip:r.ip,createDns:r.dnsType==="private",port:r.port||c.defaultPort||null,sslType:r.sslType,dnsType:r.dnsType,tailscaleOnly:r.tailscaleOnly||!1,mediaPath:r.mediaPath||null,plexClaimToken:r.plexClaimToken||null,customVolumes:r.customVolumes||null}};x&&(t.config.useExisting=!0,t.config.existingContainerId=c._existingContainer.id,t.config.existingPort=c._existingContainer.primaryPort,!r.port&&c._existingContainer.primaryPort&&(t.config.port=c._existingContainer.primaryPort));const s=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(s.success){const n={id:r.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:s.containerId,url:s.url,ip:r.ip,appTemplate:c.id,tailscaleOnly:r.tailscaleOnly||!1};d.push(n),safeSet(L,JSON.stringify(d)),window.APPS&&!window.APPS.some(a=>a.id===c.id)&&(window.APPS.push(n),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let i=s.usedExisting?`${c.name} configured with existing container!
URL: ${t.url}`:`${c.name} deployed successfully! URL: ${s.url}`:`${c.name} deployed successfully!
URL: ${t.url}`;t.warning&&(r+=` URL: ${s.url}`;s.warning&&(i+=`
\u26A0 Warning: ${t.warning}`),showNotification(r,"success",8e3),delete c._useExisting,delete c._existingContainer,t.url&&t.url.startsWith("https://")&&H(t.url,c.name),t.setupInstructions&&t.setupInstructions.length>0&&setTimeout(()=>{const a=t.setupInstructions.join(` \u26A0 Warning: ${s.warning}`),showNotification(i,"success",8e3),delete c._useExisting,delete c._existingContainer,s.url&&s.url.startsWith("https://")&&H(s.url,c.name),s.setupInstructions&&s.setupInstructions.length>0&&setTimeout(()=>{const a=s.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${c.name}: ${a}`,"info",1e4)},1e3)}else throw new Error(t.error||"Deployment failed")}catch(n){y.logError("[AppSelector] Deployment",n,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${n.message}`,"error",8e3)}}}async function H(i,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let l=0;const w=12,m=async()=>{l++;try{const n=await fetch(i,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return l<w?setTimeout(m,5e3):showNotification(`\u26A0\uFE0F ${c} deployed but SSL certificate may still be generating. `);showNotification(`Setup Instructions for ${c.name}: ${a}`,"info",1e4)},1e3)}else throw new Error(s.error||"Deployment failed")}catch(t){h.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${t.message}`,"error",8e3)}}}async function H(r,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const x=12,y=async()=>{d++;try{const t=await fetch(r,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return d<x?setTimeout(y,5e3):showNotification(`\u26A0\uFE0F ${c} deployed but SSL certificate may still be generating.
Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(m,3e3)}function L(){safeGetJSON(C,[]).forEach(c=>{window.APPS.some(l=>l.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{T(),M.classList.add("show")}),wireModal(M,document.getElementById("app-selector-cancel"));const u=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{u.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const i=JSON.parse(u.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),l=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(m=>{l.push({hostPath:m.value.trim(),containerPath:m.dataset.containerPath})});const w={appTemplate:i,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:l.length>0?l:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!w.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(i.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}u.classList.remove("show"),k(w)}),wireModal(u);const j=document.getElementById("folder-browser-modal"),v=document.getElementById("folder-browser-path"),N=document.getElementById("folder-browser-list"),g=document.getElementById("folder-browser-selected"),D=document.getElementById("folder-browser-selected-list");let B="",f=[],I=null;window.openFolderBrowser=function(i){I=i,f=i.value.split(",").map(c=>c.trim()).filter(c=>c),B="",z(),b(""),j.classList.add("show")};async function b(i){v.textContent=i||"Select a drive...",N.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const l=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(i)}`)).json();if(!l.success){N.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(l.error)}</div>`;return}B=l.path||"",v.textContent=B||"Select a drive...";let w="";l.parent&&l.parent!==l.path&&(w+=`<div class="folder-item" data-path="${escapeHtml(l.parent)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px;"> Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(y,3e3)}function C(){safeGetJSON(L,[]).forEach(c=>{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{T(),$.classList.add("show")}),wireModal($,document.getElementById("app-selector-cancel"));const v=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{v.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const r=JSON.parse(v.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(y=>{d.push({hostPath:y.value.trim(),containerPath:y.dataset.containerPath})});const x={appTemplate:r,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:d.length>0?d:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!x.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(r.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}v.classList.remove("show"),E(x)}),wireModal(v);const O=document.getElementById("folder-browser-modal"),f=document.getElementById("folder-browser-path"),z=document.getElementById("folder-browser-list"),A=document.getElementById("folder-browser-selected"),U=document.getElementById("folder-browser-selected-list");let p="",u=[],b=null;window.openFolderBrowser=function(r){b=r,u=r.value.split(",").map(c=>c.trim()).filter(c=>c),p="",M(),g(""),O.classList.add("show")};async function g(r){f.textContent=r||"Select a drive...",z.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const d=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(r)}`)).json();if(!d.success){z.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(d.error)}</div>`;return}p=d.path||"",f.textContent=p||"Select a drive...";let x="";d.parent&&d.parent!==d.path&&(x+=`<div class="folder-item" data-path="${escapeHtml(d.parent)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px;">
<span style="font-size: 1.2rem;">\u2B06\uFE0F</span> <span style="font-size: 1.2rem;">\u2B06\uFE0F</span>
<span style="color: var(--muted);">.. Parent Directory</span> <span style="color: var(--muted);">.. Parent Directory</span>
</div>`),l.items.length===0&&!l.parent?w+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':l.items.length===0?w+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':l.items.forEach(m=>{const n=m.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=f.includes(m.path),t=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";w+=`<div class="folder-item" data-path="${escapeHtml(m.path)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px; ${t}"> </div>`),d.items.length===0&&!d.parent?x+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':d.items.length===0?x+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':d.items.forEach(y=>{const t=y.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=u.includes(y.path),s=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";x+=`<div class="folder-item" data-path="${escapeHtml(y.path)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px; ${s}">
<span style="font-size: 1.2rem;">${n}</span> <span style="font-size: 1.2rem;">${t}</span>
<span style="flex: 1;">${escapeHtml(m.name)}</span> <span style="flex: 1;">${escapeHtml(y.name)}</span>
${e?'<span style="color: var(--success);">\u2713</span>':""} ${e?'<span style="color: var(--success);">\u2713</span>':""}
</div>`}),N.innerHTML=w,N.querySelectorAll(".folder-item").forEach(m=>{m.addEventListener("click",()=>{b(m.dataset.path)}),m.addEventListener("mouseenter",()=>{m.style.background="var(--card-bg)"}),m.addEventListener("mouseleave",()=>{const n=f.includes(m.dataset.path);m.style.background=n?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){N.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Failed to load: ${escapeHtml(c.message)}</div>`}}function z(){if(f.length===0){g.style.display="none";return}g.style.display="block",D.innerHTML=f.map(i=>` </div>`}),z.innerHTML=x,z.querySelectorAll(".folder-item").forEach(y=>{y.addEventListener("click",()=>{g(y.dataset.path)}),y.addEventListener("mouseenter",()=>{y.style.background="var(--card-bg)"}),y.addEventListener("mouseleave",()=>{const t=u.includes(y.dataset.path);y.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){z.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Failed to load: ${escapeHtml(c.message)}</div>`}}function M(){if(u.length===0){A.style.display="none";return}A.style.display="block",U.innerHTML=u.map(r=>`
<span style="padding: 6px 12px; background: var(--card-bg); border: 1px solid var(--success); border-radius: 4px; display: flex; align-items: center; gap: 6px;"> <span style="padding: 6px 12px; background: var(--card-bg); border: 1px solid var(--success); border-radius: 4px; display: flex; align-items: center; gap: 6px;">
${escapeHtml(i)} ${escapeHtml(r)}
<button type="button" onclick="removeSelectedFolder('${escapeHtml(i)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button> <button type="button" onclick="removeSelectedFolder('${escapeHtml(r)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button>
</span> </span>
`).join("")}window.removeSelectedFolder=function(i){f=f.filter(c=>c!==i),z(),b(B)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{B&&!f.includes(B)&&(f.push(B),z(),b(B))}),wireModal(j,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{I&&(I.value=f.join(", ")),j.classList.remove("show")}),L()})(),(function(){injectModal("recipe-deploy-modal",`<div id="recipe-deploy-modal" class="weather-modal"> `).join("")}window.removeSelectedFolder=function(r){u=u.filter(c=>c!==r),M(),g(p)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{p&&!u.includes(p)&&(u.push(p),M(),g(p))}),wireModal(O,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{b&&(b.value=u.join(", ")),O.classList.remove("show")}),C()})(),(function(){injectModal("recipe-deploy-modal",`<div id="recipe-deploy-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 620px; max-width: 740px;"> <div class="weather-modal-content" style="min-width: 620px; max-width: 740px;">
<h3 id="recipe-deploy-title">Deploy Recipe</h3> <h3 id="recipe-deploy-title">Deploy Recipe</h3>
@@ -458,70 +445,70 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="recipe-next" class="btn-accent-solid">Next</button> <button id="recipe-next" class="btn-accent-solid">Next</button>
</div> </div>
</div> </div>
</div>`);let y=null,C=null,O=null,E=1,M=!1;const R=document.getElementById("recipe-deploy-modal"),P=document.getElementById("recipe-cancel"),A=document.getElementById("recipe-prev"),p=document.getElementById("recipe-next");wireModal(R,P);async function T(){try{const B=await fetch("/api/v1/recipes/templates"),f=await B.json();if(f.success)return y=f.templates,C=f.categories,!0;if(B.status===403)return M=!1,!1}catch(B){console.warn("Failed to fetch recipe templates:",B.message)}return!1}async function x(){try{M=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{M=!1}return M}window.renderRecipeCards=async function(B){await x();let f;if(M&&y?f=y:f=$(),!f||f.length===0)return;const I=document.createElement("div");I.className="app-category-header",I.innerHTML="\u{1F9EA} Recipes",I.style.borderBottomColor="#8e44ad",B.appendChild(I);const b=Array.isArray(f)?f:Object.values(f);b.sort((z,i)=>(i.popularity||0)-(z.popularity||0));for(const z of b){const i=document.createElement("div");i.className="app-option",i.style.position="relative";const c=`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: rgba(142,68,173,0.2); color: #a855f7;">${z.componentCount||z.components?.length||"?"} apps</div>`,l=M?"":'<div style="position: absolute; top: 6px; right: 6px; font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; background: rgba(241,196,15,0.2); color: #f1c40f; font-weight: 600;">PREMIUM</div>';i.innerHTML=` </div>`);let h=null,L=null,R=null,S=1,$=!1;const P=document.getElementById("recipe-deploy-modal"),N=document.getElementById("recipe-cancel"),D=document.getElementById("recipe-prev"),m=document.getElementById("recipe-next");wireModal(P,N);async function T(){try{const p=await fetch("/api/v1/recipes/templates"),u=await p.json();if(u.success)return h=u.templates,L=u.categories,!0;if(p.status===403)return $=!1,!1}catch(p){console.warn("Failed to fetch recipe templates:",p.message)}return!1}async function w(){try{$=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{$=!1}return $}window.renderRecipeCards=async function(p){await w();let u;if($&&h?u=h:u=B(),!u||u.length===0)return;const b=document.createElement("div");b.className="app-category-header",b.innerHTML="\u{1F9EA} Recipes",b.style.borderBottomColor="#8e44ad",p.appendChild(b);const g=Array.isArray(u)?u:Object.values(u);g.sort((M,r)=>(r.popularity||0)-(M.popularity||0));for(const M of g){const r=document.createElement("div");r.className="app-option",r.style.position="relative";const c=`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: rgba(142,68,173,0.2); color: #a855f7;">${M.componentCount||M.components?.length||"?"} apps</div>`,d=$?"":'<div style="position: absolute; top: 6px; right: 6px; font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; background: rgba(241,196,15,0.2); color: #f1c40f; font-weight: 600;">PREMIUM</div>';r.innerHTML=`
${l} ${d}
<div class="app-option-icon">${escapeHtml(z.icon||"\u{1F9EA}")}</div> <div class="app-option-icon">${escapeHtml(M.icon||"\u{1F9EA}")}</div>
<div class="app-option-name">${escapeHtml(z.name)}</div> <div class="app-option-name">${escapeHtml(M.name)}</div>
<div class="app-option-desc">${escapeHtml(z.description||"")}</div> <div class="app-option-desc">${escapeHtml(M.description||"")}</div>
${c} ${c}
`,i.onclick=()=>{if(!M){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(z)},B.appendChild(i)}};function $(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function k(B){O=B,E=1;const f=document.getElementById("app-selector-modal");f&&f.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${B.name}`,H(),L(),R.classList.add("show")}function H(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(B=>{const f=parseInt(B.dataset.step);B.classList.toggle("active",f===E),B.classList.toggle("completed",f<E)});for(let B=1;B<=4;B++){const f=document.getElementById(`recipe-step-${B}`);f&&(f.style.display=B===E?"":"none")}A.style.display=E>1&&E<4?"":"none",E===4?(p.style.display="none",P.textContent="Close"):E===3?(p.textContent="\u{1F680} Deploy",p.style.display="",P.textContent="Cancel"):(p.textContent="Next",p.style.display="",P.textContent="Cancel")}function L(){const B=document.getElementById("recipe-component-list");B.innerHTML="";const f=O.components||[];for(const I of f){const b=document.createElement("div");b.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const z=I.required,i=I.internal;b.innerHTML=` `,r.onclick=()=>{if(!$){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}E(M)},p.appendChild(r)}};function B(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function E(p){R=p,S=1;const u=document.getElementById("app-selector-modal");u&&u.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${p.name}`,H(),C(),P.classList.add("show")}function H(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(p=>{const u=parseInt(p.dataset.step);p.classList.toggle("active",u===S),p.classList.toggle("completed",u<S)});for(let p=1;p<=4;p++){const u=document.getElementById(`recipe-step-${p}`);u&&(u.style.display=p===S?"":"none")}D.style.display=S>1&&S<4?"":"none",S===4?(m.style.display="none",N.textContent="Close"):S===3?(m.textContent="\u{1F680} Deploy",m.style.display="",N.textContent="Cancel"):(m.textContent="Next",m.style.display="",N.textContent="Cancel")}function C(){const p=document.getElementById("recipe-component-list");p.innerHTML="";const u=R.components||[];for(const b of u){const g=document.createElement("div");g.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const M=b.required,r=b.internal;g.innerHTML=`
<input type="checkbox" ${z?"checked disabled":"checked"} data-component-id="${I.id}" <input type="checkbox" ${M?"checked disabled":"checked"} data-component-id="${b.id}"
style="width: 18px; height: 18px; accent-color: var(--accent);" /> style="width: 18px; height: 18px; accent-color: var(--accent);" />
<div style="flex: 1;"> <div style="flex: 1;">
<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(I.role||I.id)}</div> <div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(b.role||b.id)}</div>
<div style="font-size: 0.78rem; color: var(--muted);"> <div style="font-size: 0.78rem; color: var(--muted);">
${I.templateRef?escapeHtml(I.templateRef):"Built-in"} ${b.templateRef?escapeHtml(b.templateRef):"Built-in"}
${z?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'} ${M?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'}
${i?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""} ${r?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""}
</div> </div>
${I.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(I.note)}</div>`:""} ${b.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(b.note)}</div>`:""}
</div> </div>
`,B.appendChild(b)}}function u(){const B=document.getElementById("recipe-volumes-section"),f=document.getElementById("recipe-volume-list"),I=O.sharedVolumes;if(I&&Object.keys(I).length>0){B.style.display="",f.innerHTML="";for(const[b,z]of Object.entries(I)){const i=document.createElement("div");i.style.cssText="display: grid; gap: 4px;",i.innerHTML=` `,p.appendChild(g)}}function v(){const p=document.getElementById("recipe-volumes-section"),u=document.getElementById("recipe-volume-list"),b=R.sharedVolumes;if(b&&Object.keys(b).length>0){p.style.display="",u.innerHTML="";for(const[g,M]of Object.entries(b)){const r=document.createElement("div");r.style.cssText="display: grid; gap: 4px;",r.innerHTML=`
<label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(z.label||b)}</label> <label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(M.label||g)}</label>
<input type="text" data-volume-key="${b}" value="${escapeHtml(z.defaultPath||"")}" <input type="text" data-volume-key="${g}" value="${escapeHtml(M.defaultPath||"")}"
placeholder="${escapeHtml(z.defaultPath||"/path")}" placeholder="${escapeHtml(M.defaultPath||"/path")}"
style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-family: monospace; font-size: 0.85rem;" /> style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-family: monospace; font-size: 0.85rem;" />
<div class="form-hint-sm">${escapeHtml(z.description||"")}</div> <div class="form-hint-sm">${escapeHtml(M.description||"")}</div>
`,f.appendChild(i)}}else B.style.display="none"}function j(){const B=document.getElementById("recipe-review-content"),f=v(),I=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),b={};I.forEach(l=>{b[l.dataset.volumeKey]=l.value});const z=document.getElementById("recipe-timezone").value||"UTC",i=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;B.innerHTML=` `,u.appendChild(r)}}else p.style.display="none"}function O(){const p=document.getElementById("recipe-review-content"),u=f(),b=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),g={};b.forEach(d=>{g[d.dataset.volumeKey]=d.value});const M=document.getElementById("recipe-timezone").value||"UTC",r=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;p.innerHTML=`
<div style="font-weight: 600; font-size: 1rem; margin-bottom: 12px;">${escapeHtml(O.name)}</div> <div style="font-weight: 600; font-size: 1rem; margin-bottom: 12px;">${escapeHtml(R.name)}</div>
<div style="color: var(--muted); margin-bottom: 16px;">${escapeHtml(O.description||"")}</div> <div style="color: var(--muted); margin-bottom: 16px;">${escapeHtml(R.description||"")}</div>
<div style="margin-bottom: 12px;"> <div style="margin-bottom: 12px;">
<strong>Components (${f.length}):</strong> <strong>Components (${u.length}):</strong>
<div style="display: grid; gap: 4px; margin-top: 6px;"> <div style="display: grid; gap: 4px; margin-top: 6px;">
${f.map(l=>`<div style="padding: 4px 0; font-size: 0.85rem;"> ${u.map(d=>`<div style="padding: 4px 0; font-size: 0.85rem;">
\u2022 <strong>${escapeHtml(l.role||l.id)}</strong> ${l.internal?'<span style="color:var(--muted)">(internal)</span>':""} \u2022 <strong>${escapeHtml(d.role||d.id)}</strong> ${d.internal?'<span style="color:var(--muted)">(internal)</span>':""}
</div>`).join("")} </div>`).join("")}
</div> </div>
</div> </div>
${Object.keys(b).length>0?`<div style="margin-bottom: 12px;"> ${Object.keys(g).length>0?`<div style="margin-bottom: 12px;">
<strong>Volumes:</strong> <strong>Volumes:</strong>
${Object.entries(b).map(([l,w])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${l}: ${escapeHtml(w)}</div>`).join("")} ${Object.entries(g).map(([d,x])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${d}: ${escapeHtml(x)}</div>`).join("")}
</div>`:""} </div>`:""}
<div style="font-size: 0.85rem; color: var(--muted);"> <div style="font-size: 0.85rem; color: var(--muted);">
Timezone: ${escapeHtml(z)} &bull; IP: ${escapeHtml(i)} ${c?"&bull; Tailscale only":""} Timezone: ${escapeHtml(M)} &bull; IP: ${escapeHtml(r)} ${c?"&bull; Tailscale only":""}
</div> </div>
${O.network?`<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">Docker network: <code>${escapeHtml(O.network.name)}</code></div>`:""} ${R.network?`<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">Docker network: <code>${escapeHtml(R.network.name)}</code></div>`:""}
`}function v(){const B=document.querySelectorAll("#recipe-component-list input[data-component-id]"),f=new Set;B.forEach(b=>{b.checked&&f.add(b.dataset.componentId)});const I=O.components||[];return I.filter(b=>b.required).forEach(b=>f.add(b.id)),I.filter(b=>f.has(b.id))}async function N(){const B=document.getElementById("recipe-progress-list"),f=document.getElementById("recipe-deploy-result");f.style.display="none",B.innerHTML="";const I=v();for(const c of I){const l=document.createElement("div");l.id=`recipe-progress-${c.id}`,l.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",l.innerHTML=` `}function f(){const p=document.querySelectorAll("#recipe-component-list input[data-component-id]"),u=new Set;p.forEach(g=>{g.checked&&u.add(g.dataset.componentId)});const b=R.components||[];return b.filter(g=>g.required).forEach(g=>u.add(g.id)),b.filter(g=>u.has(g.id))}async function z(){const p=document.getElementById("recipe-progress-list"),u=document.getElementById("recipe-deploy-result");u.style.display="none",p.innerHTML="";const b=f();for(const c of b){const d=document.createElement("div");d.id=`recipe-progress-${c.id}`,d.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",d.innerHTML=`
<span class="recipe-progress-icon" style="font-size: 1.1rem;">\u23F3</span> <span class="recipe-progress-icon" style="font-size: 1.1rem;">\u23F3</span>
<span style="flex:1; font-weight: 500;">${escapeHtml(c.role||c.id)}</span> <span style="flex:1; font-weight: 500;">${escapeHtml(c.role||c.id)}</span>
<span class="recipe-progress-status" style="color: var(--muted);">Queued</span> <span class="recipe-progress-status" style="color: var(--muted);">Queued</span>
`,B.appendChild(l)}const b=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),z={};b.forEach(c=>{z[c.dataset.volumeKey]=c.value});const i={selectedComponents:I.map(c=>c.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:z},componentOverrides:{}};for(const c of I)g(c.id,"deploying","Deploying...");try{const l=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:O.id,config:i})})).json();if(l.success){for(const w of l.deployed||[])g(w.id,"success",w.url?`Running \u2192 ${w.url}`:"Running");for(const w of l.errors||[])g(w.componentId,"error",w.error);f.style.display="",f.innerHTML=` `,p.appendChild(d)}const g=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),M={};g.forEach(c=>{M[c.dataset.volumeKey]=c.value});const r={selectedComponents:b.map(c=>c.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:M},componentOverrides:{}};for(const c of b)A(c.id,"deploying","Deploying...");try{const d=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:R.id,config:r})})).json();if(d.success){for(const x of d.deployed||[])A(x.id,"success",x.url?`Running \u2192 ${x.url}`:"Running");for(const x of d.errors||[])A(x.componentId,"error",x.error);u.style.display="",u.innerHTML=`
<div style="padding: 14px; border-radius: 8px; background: rgba(46,204,113,0.1); border: 1px solid rgba(46,204,113,0.3);"> <div style="padding: 14px; border-radius: 8px; background: rgba(46,204,113,0.1); border: 1px solid rgba(46,204,113,0.3);">
<div style="font-weight: 600; color: var(--ok-fg); margin-bottom: 6px;">${escapeHtml(l.message||"Deployed!")}</div> <div style="font-weight: 600; color: var(--ok-fg); margin-bottom: 6px;">${escapeHtml(d.message||"Deployed!")}</div>
${l.setupInstructions?`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 8px;"> ${d.setupInstructions?`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 8px;">
<strong>Setup tips:</strong> <strong>Setup tips:</strong>
<ul style="margin: 4px 0 0 16px; padding: 0;">${l.setupInstructions.map(w=>`<li>${escapeHtml(w)}</li>`).join("")}</ul> <ul style="margin: 4px 0 0 16px; padding: 0;">${d.setupInstructions.map(x=>`<li>${escapeHtml(x)}</li>`).join("")}</ul>
</div>`:""} </div>`:""}
</div> </div>
`,showNotification(`${O.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else f.style.display="",f.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);"> `,showNotification(`${R.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else u.style.display="",u.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Deployment failed:</strong> ${escapeHtml(l.error||"Unknown error")} <strong>Deployment failed:</strong> ${escapeHtml(d.error||"Unknown error")}
</div>`,showNotification(`Recipe deployment failed: ${l.error}`,"error",5e3)}catch(c){f.style.display="",f.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);"> </div>`,showNotification(`Recipe deployment failed: ${d.error}`,"error",5e3)}catch(c){u.style.display="",u.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Network error:</strong> ${escapeHtml(c.message)} <strong>Network error:</strong> ${escapeHtml(c.message)}
</div>`}}function g(B,f,I){const b=document.getElementById(`recipe-progress-${B}`);if(!b)return;const z=b.querySelector(".recipe-progress-icon"),i=b.querySelector(".recipe-progress-status");f==="deploying"?(z.textContent="\u23F3",i.style.color="var(--accent)"):f==="success"?(z.textContent="\u2705",i.style.color="var(--ok-fg)"):f==="error"&&(z.textContent="\u274C",i.style.color="var(--bad-fg)"),i.textContent=I}p.addEventListener("click",()=>{if(E===3){E=4,H(),N();return}E<3&&(E++,H(),E===2&&u(),E===3&&j())}),A.addEventListener("click",()=>{E>1&&E<4&&(E--,H())}),window.groupRecipeCards=function(){const B=document.querySelectorAll(".service-card[data-recipe-id]");if(B.length===0)return;const f={};B.forEach(I=>{const b=I.dataset.recipeId;f[b]||(f[b]=[]),f[b].push(I)});for(const[I,b]of Object.entries(f))b.length<2||b.forEach((z,i)=>{if(z.style.borderLeft="3px solid rgba(142,68,173,0.5)",i===0){let c=z.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",c.textContent=I.replace(/-/g," "),z.style.position="relative",z.appendChild(c))}})},window.manageRecipe=async function(B,f){const I=`/api/v1/recipes/${B}/${f}`,b=f==="remove"?"DELETE":"POST",z=f==="remove"?`/api/v1/recipes/${B}`:I;if(!(f==="remove"&&!confirm(`Remove the entire ${B} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(z,{method:b})).json();c.success?(showNotification(`Recipe ${f}: ${c.results?.filter(l=>l.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${f} failed: ${c.error}`,"error",5e3)}catch(i){showNotification(`Network error: ${i.message}`,"error",5e3)}};const D=document.createElement("style");D.textContent=` </div>`}}function A(p,u,b){const g=document.getElementById(`recipe-progress-${p}`);if(!g)return;const M=g.querySelector(".recipe-progress-icon"),r=g.querySelector(".recipe-progress-status");u==="deploying"?(M.textContent="\u23F3",r.style.color="var(--accent)"):u==="success"?(M.textContent="\u2705",r.style.color="var(--ok-fg)"):u==="error"&&(M.textContent="\u274C",r.style.color="var(--bad-fg)"),r.textContent=b}m.addEventListener("click",()=>{if(S===3){S=4,H(),z();return}S<3&&(S++,H(),S===2&&v(),S===3&&O())}),D.addEventListener("click",()=>{S>1&&S<4&&(S--,H())}),window.groupRecipeCards=function(){const p=document.querySelectorAll(".service-card[data-recipe-id]");if(p.length===0)return;const u={};p.forEach(b=>{const g=b.dataset.recipeId;u[g]||(u[g]=[]),u[g].push(b)});for(const[b,g]of Object.entries(u))g.length<2||g.forEach((M,r)=>{if(M.style.borderLeft="3px solid rgba(142,68,173,0.5)",r===0){let c=M.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",c.textContent=b.replace(/-/g," "),M.style.position="relative",M.appendChild(c))}})},window.manageRecipe=async function(p,u){const b=`/api/v1/recipes/${p}/${u}`,g=u==="remove"?"DELETE":"POST",M=u==="remove"?`/api/v1/recipes/${p}`:b;if(!(u==="remove"&&!confirm(`Remove the entire ${p} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(M,{method:g})).json();c.success?(showNotification(`Recipe ${u}: ${c.results?.filter(d=>d.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${u} failed: ${c.error}`,"error",5e3)}catch(r){showNotification(`Network error: ${r.message}`,"error",5e3)}};const U=document.createElement("style");U.textContent=`
.recipe-step { .recipe-step {
flex: 1; flex: 1;
text-align: center; text-align: center;
@@ -563,16 +550,16 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
.recipe-step-panel { .recipe-step-panel {
min-height: 180px; min-height: 180px;
} }
`,document.head.appendChild(D),x()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const y=document.getElementById("reload-caddy-top"),C=y.textContent;try{y.textContent="\u23F3 Reloading...",y.disabled=!0;const O=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),E=await O.json();if(O.ok&&E.success)y.textContent="\u2705 Reloaded!",setTimeout(()=>{y.textContent=C,y.disabled=!1},2e3);else throw new Error(E.error||"Reload failed")}catch(O){y.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${O.message}`,"error"),setTimeout(()=>{y.textContent=C,y.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",'<div id="error-log-modal" class="logs-modal"><div class="logs-modal-content"><div class="logs-header"><h3>\u{1F4CB} Error Logs</h3><div class="logs-controls"><button id="error-log-refresh" style="padding:4px 12px!important;font-size:.85rem!important">\u{1F504} Refresh</button><button id="error-log-clear" style="padding:4px 12px!important;font-size:.85rem!important;background:color-mix(in srgb,var(--bad-fg) 15%,transparent)!important;border-color:var(--bad-fg)!important;color:var(--bad-fg)!important">\u{1F5D1}\uFE0F Clear</button><button id="error-log-close" class="close-btn">\u2715</button></div></div><div class="logs-container"><div id="error-log-content" class="logs-content"><div class="logs-loading">Loading error logs...</div></div></div></div></div>');const y=document.getElementById("error-log-modal"),C=document.getElementById("error-log-content"),O=document.getElementById("view-error-logs"),E=document.getElementById("error-log-refresh"),M=document.getElementById("error-log-clear"),R=document.getElementById("error-log-close");async function P(){C.innerHTML='<div class="logs-loading">Loading error logs...</div>';try{const T=await(await fetch("/api/v1/error-logs")).json();T.success&&T.logs?T.logs.length===0?C.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">\u2705 No errors logged! Everything is working smoothly.</div>':C.innerHTML=T.logs.map(x=>` `,document.head.appendChild(U),w()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const h=document.getElementById("reload-caddy-top"),L=h.textContent;try{h.textContent="\u23F3 Reloading...",h.disabled=!0;const R=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),S=await R.json();if(R.ok&&S.success)h.textContent="\u2705 Reloaded!",setTimeout(()=>{h.textContent=L,h.disabled=!1},2e3);else throw new Error(S.error||"Reload failed")}catch(R){h.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${R.message}`,"error"),setTimeout(()=>{h.textContent=L,h.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",'<div id="error-log-modal" class="logs-modal"><div class="logs-modal-content"><div class="logs-header"><h3>\u{1F4CB} Error Logs</h3><div class="logs-controls"><button id="error-log-refresh" style="padding:4px 12px!important;font-size:.85rem!important">\u{1F504} Refresh</button><button id="error-log-clear" style="padding:4px 12px!important;font-size:.85rem!important;background:color-mix(in srgb,var(--bad-fg) 15%,transparent)!important;border-color:var(--bad-fg)!important;color:var(--bad-fg)!important">\u{1F5D1}\uFE0F Clear</button><button id="error-log-close" class="close-btn">\u2715</button></div></div><div class="logs-container"><div id="error-log-content" class="logs-content"><div class="logs-loading">Loading error logs...</div></div></div></div></div>');const h=document.getElementById("error-log-modal"),L=document.getElementById("error-log-content"),R=document.getElementById("view-error-logs"),S=document.getElementById("error-log-refresh"),$=document.getElementById("error-log-clear"),P=document.getElementById("error-log-close");async function N(){L.innerHTML='<div class="logs-loading">Loading error logs...</div>';try{const T=await(await fetch("/api/v1/error-logs")).json();T.success&&T.logs?T.logs.length===0?L.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">\u2705 No errors logged! Everything is working smoothly.</div>':L.innerHTML=T.logs.map(w=>`
<div class="log-entry error"> <div class="log-entry error">
<span class="log-timestamp">${new Date(x.timestamp).toLocaleString()}</span> <span class="log-timestamp">${new Date(w.timestamp).toLocaleString()}</span>
<span class="log-level">ERROR</span> <span class="log-level">ERROR</span>
<div class="log-message"> <div class="log-message">
<strong>${escapeHtml(x.context)}</strong>: ${escapeHtml(x.error)} <strong>${escapeHtml(w.context)}</strong>: ${escapeHtml(w.error)}
${x.details?`<br><small style="opacity: 0.7;">${escapeHtml(x.details)}</small>`:""} ${w.details?`<br><small style="opacity: 0.7;">${escapeHtml(w.details)}</small>`:""}
</div> </div>
</div> </div>
`).join(""):C.innerHTML='<div style="padding: 20px; color: var(--bad-fg);">\u274C Failed to load error logs</div>'}catch(p){C.innerHTML=`<div style="padding: 20px; color: var(--bad-fg);">\u274C Error loading logs: ${escapeHtml(p.message)}</div>`}}async function A(){if(confirm("Clear all error logs?"))try{(await(await secureFetch("/api/v1/error-logs",{method:"DELETE"})).json()).success?(showNotification("\u2705 Error logs cleared","success",3e3),P()):showNotification("\u274C Failed to clear logs","error",3e3)}catch(p){showNotification(`\u274C Error: ${p.message}`,"error",3e3)}}O?.addEventListener("click",()=>{y.classList.add("show"),P()}),E?.addEventListener("click",P),M?.addEventListener("click",A),wireModal(y,R)})(),(function(){injectModal("container-logs-modal",`<div id="container-logs-modal" class="weather-modal" style="z-index: 1001;"> `).join(""):L.innerHTML='<div style="padding: 20px; color: var(--bad-fg);">\u274C Failed to load error logs</div>'}catch(m){L.innerHTML=`<div style="padding: 20px; color: var(--bad-fg);">\u274C Error loading logs: ${escapeHtml(m.message)}</div>`}}async function D(){if(confirm("Clear all error logs?"))try{(await(await secureFetch("/api/v1/error-logs",{method:"DELETE"})).json()).success?(showNotification("\u2705 Error logs cleared","success",3e3),N()):showNotification("\u274C Failed to clear logs","error",3e3)}catch(m){showNotification(`\u274C Error: ${m.message}`,"error",3e3)}}R?.addEventListener("click",()=>{h.classList.add("show"),N()}),S?.addEventListener("click",N),$?.addEventListener("click",D),wireModal(h,P)})(),(function(){injectModal("container-logs-modal",`<div id="container-logs-modal" class="weather-modal" style="z-index: 1001;">
<div class="weather-modal-content" style="min-width: 900px; max-width: 95vw; height: 80vh; display: flex; flex-direction: column;"> <div class="weather-modal-content" style="min-width: 900px; max-width: 95vw; height: 80vh; display: flex; flex-direction: column;">
<div class="logs-header" style="display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; border-bottom: 1px solid var(--border); margin-bottom: 12px;"> <div class="logs-header" style="display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; border-bottom: 1px solid var(--border); margin-bottom: 12px;">
<div> <div>
@@ -622,14 +609,14 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="cl-close-btn" class="btn-secondary">Close</button> <button id="cl-close-btn" class="btn-secondary">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("container-logs-modal"),C=document.getElementById("cl-container-select"),O=document.getElementById("cl-log-content"),E=document.getElementById("cl-log-search"),M=document.getElementById("cl-log-tail"),R=document.getElementById("cl-refresh"),P=document.getElementById("cl-stream"),A=document.getElementById("cl-download"),p=document.getElementById("cl-clear-search"),T=document.getElementById("cl-close"),x=document.getElementById("cl-close-btn"),$=document.getElementById("cl-stream-status"),k=document.getElementById("cl-stream-indicator"),H=document.getElementById("cl-stream-text"),L=document.getElementById("cl-line-count"),u=document.getElementById("cl-filter-count"),j=document.getElementById("cl-image"),v=document.getElementById("cl-status"),N=document.getElementById("cl-created");let g=null,D=[],B=[],f=null,I=!1,b=null;function z(s){if(!s)return"-";const d=new Date(s);return isNaN(d.getTime())?s:d.toLocaleString()}function i(s){if(!s)return"";const d=document.createElement("div");return d.textContent=s,d.innerHTML}function c(s,d){const S=s.stream==="stderr"?"log-stderr":"log-stdout",h=s.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return` </div>`);const h=document.getElementById("container-logs-modal"),L=document.getElementById("cl-container-select"),R=document.getElementById("cl-log-content"),S=document.getElementById("cl-log-search"),$=document.getElementById("cl-log-tail"),P=document.getElementById("cl-refresh"),N=document.getElementById("cl-stream"),D=document.getElementById("cl-download"),m=document.getElementById("cl-clear-search"),T=document.getElementById("cl-close"),w=document.getElementById("cl-close-btn"),B=document.getElementById("cl-stream-status"),E=document.getElementById("cl-stream-indicator"),H=document.getElementById("cl-stream-text"),C=document.getElementById("cl-line-count"),v=document.getElementById("cl-filter-count"),O=document.getElementById("cl-image"),f=document.getElementById("cl-status"),z=document.getElementById("cl-created");let A=null,U=[],p=[],u=null,b=!1,g=null;function M(o){if(!o)return"-";const l=new Date(o);return isNaN(l.getTime())?o:l.toLocaleString()}function r(o){if(!o)return"";const l=document.createElement("div");return l.textContent=o,l.innerHTML}function c(o,l){const k=o.stream==="stderr"?"log-stderr":"log-stdout",I=o.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return`
<div class="log-entry ${S}" data-index="${d}" style="padding: 4px 8px; border-bottom: 1px solid #333; display: flex; gap: 8px;"> <div class="log-entry ${k}" data-index="${l}" style="padding: 4px 8px; border-bottom: 1px solid #333; display: flex; gap: 8px;">
<span class="log-line-num" style="color: #666; min-width: 40px; text-align: right; user-select: none;">${d+1}</span> <span class="log-line-num" style="color: #666; min-width: 40px; text-align: right; user-select: none;">${l+1}</span>
<span class="log-stream-icon" style="color: ${s.stream==="stderr"?"#f59e0b":"#22c55e"};">${h}</span> <span class="log-stream-icon" style="color: ${o.stream==="stderr"?"#f59e0b":"#22c55e"};">${I}</span>
<span class="log-text" style="flex: 1; white-space: pre-wrap; word-break: break-all; color: #e5e5e5;">${i(s.text)}</span> <span class="log-text" style="flex: 1; white-space: pre-wrap; word-break: break-all; color: #e5e5e5;">${r(o.text)}</span>
</div> </div>
`}function l(s,d=""){if(!s||s.length===0){O.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs available</div>',L.textContent="0 lines",u.textContent="0 filtered";return}if(D=s,B=d?s.filter(S=>S.text&&S.text.toLowerCase().includes(d.toLowerCase())):s,L.textContent=`${s.length} lines`,u.textContent=d?`${B.length} of ${s.length} shown`:`${s.length} shown`,B.length===0){O.innerHTML=`<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs match "${i(d)}"</div>`;return}O.innerHTML=B.map((S,h)=>c(S,h)).join(""),O.scrollTop=O.scrollHeight}async function w(){try{const d=(await getJSON("/api/v1/logs/containers")).containers||[],S=C.value;C.innerHTML='<option value="">Select a container...</option>',d.forEach(h=>{const U=document.createElement("option");U.value=h.id,U.textContent=`${h.name} (${h.image.split(":")[0]}) - ${h.status}`,U.dataset.name=h.name,U.dataset.image=h.image,U.dataset.status=h.status,U.dataset.created=h.created,C.appendChild(U)}),S&&C.querySelector(`option[value="${S}"]`)&&(C.value=S,m(S))}catch(s){console.error("Failed to load containers:",s)}}function m(s){const d=C.querySelector(`option[value="${s}"]`);d&&(j.textContent=d.dataset.image||"-",v.textContent=d.dataset.status||"-",v.style.color=d.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",N.textContent=z(d.dataset.created))}async function n(){const s=C.value;if(!s){O.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>';return}t(),g=s,m(s);const d=M.value,S=E.value.trim();O.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading logs...</div>';try{const h=`/api/v1/logs/container/${s}${d!=="all"?`?tail=${d}`:""}`,U=await getJSON(h);U.logs&&U.logs.length>0?l(U.logs,S):(O.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs found for this container</div>',L.textContent="0 lines",u.textContent="0 filtered")}catch(h){O.innerHTML=`<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error loading logs: ${i(h.message)}</div>`}}function e(){const s=C.value;if(!s)return;t(),I=!0,P.textContent="\u23F9 Stop",$.style.display="flex",k.textContent="\u{1F7E2}",H.textContent="Connecting...";const d=`/api/v1/logs/stream/${s}`;f=new EventSource(d),f.onopen=()=>{k.textContent="\u{1F7E2}",H.textContent="Connected - streaming logs"},f.onmessage=S=>{try{const h=JSON.parse(S.data);if(h.error){k.textContent="\u{1F534}",H.textContent=`Error: ${h.error}`;return}D.push(h),B.push(h),L.textContent=`${D.length} lines`,u.textContent=`${B.length} shown`;const U=E.value.trim();if(!U||h.text&&h.text.toLowerCase().includes(U.toLowerCase())){const _=document.createElement("div");_.innerHTML=c(h,B.length-1);const F=_.firstElementChild;F.style.background="#1a3a1a",O.appendChild(F),O.scrollTop=O.scrollHeight}}catch(h){console.error("Error parsing log:",h)}},f.onerror=()=>{k.textContent="\u{1F534}",H.textContent="Disconnected",I=!1,P.textContent="\u25B6 Stream"},y._eventSource=f}function t(){f&&(f.close(),f=null),y._eventSource&&(y._eventSource.close(),y._eventSource=null),I=!1,P.textContent="\u25B6 Stream",$.style.display="none"}function o(){if(!D||D.length===0){showNotification("No logs to download","error");return}const s=C.querySelector(`option[value="${g}"]`)?.dataset.name||g,d=new Date().toISOString().replace(/[:.]/g,"-"),S=`${s}-logs-${d}.txt`,h=D.map(W=>{const J=W.timestamp||"",X=W.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${X} ${W.text}`}).join(` `}function d(o,l=""){if(!o||o.length===0){R.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs available</div>',C.textContent="0 lines",v.textContent="0 filtered";return}if(U=o,p=l?o.filter(k=>k.text&&k.text.toLowerCase().includes(l.toLowerCase())):o,C.textContent=`${o.length} lines`,v.textContent=l?`${p.length} of ${o.length} shown`:`${o.length} shown`,p.length===0){R.innerHTML=`<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs match "${r(l)}"</div>`;return}R.innerHTML=p.map((k,I)=>c(k,I)).join(""),R.scrollTop=R.scrollHeight}async function x(){try{const l=(await getJSON("/api/v1/logs/containers")).containers||[],k=L.value;L.innerHTML='<option value="">Select a container...</option>',l.forEach(I=>{const j=document.createElement("option");j.value=I.id,j.textContent=`${I.name} (${I.image.split(":")[0]}) - ${I.status}`,j.dataset.name=I.name,j.dataset.image=I.image,j.dataset.status=I.status,j.dataset.created=I.created,L.appendChild(j)}),k&&L.querySelector(`option[value="${k}"]`)&&(L.value=k,y(k))}catch(o){console.error("Failed to load containers:",o)}}function y(o){const l=L.querySelector(`option[value="${o}"]`);l&&(O.textContent=l.dataset.image||"-",f.textContent=l.dataset.status||"-",f.style.color=l.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",z.textContent=M(l.dataset.created))}async function t(){const o=L.value;if(!o){R.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>';return}s(),A=o,y(o);const l=$.value,k=S.value.trim();R.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading logs...</div>';try{const I=`/api/v1/logs/container/${o}${l!=="all"?`?tail=${l}`:""}`,j=await getJSON(I);j.logs&&j.logs.length>0?d(j.logs,k):(R.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs found for this container</div>',C.textContent="0 lines",v.textContent="0 filtered")}catch(I){R.innerHTML=`<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error loading logs: ${r(I.message)}</div>`}}function e(){const o=L.value;if(!o)return;s(),b=!0,N.textContent="\u23F9 Stop",B.style.display="flex",E.textContent="\u{1F7E2}",H.textContent="Connecting...";const l=`/api/v1/logs/stream/${o}`;u=new EventSource(l),u.onopen=()=>{E.textContent="\u{1F7E2}",H.textContent="Connected - streaming logs"},u.onmessage=k=>{try{const I=JSON.parse(k.data);if(I.error){E.textContent="\u{1F534}",H.textContent=`Error: ${I.error}`;return}U.push(I),p.push(I),C.textContent=`${U.length} lines`,v.textContent=`${p.length} shown`;const j=S.value.trim();if(!j||I.text&&I.text.toLowerCase().includes(j.toLowerCase())){const _=document.createElement("div");_.innerHTML=c(I,p.length-1);const F=_.firstElementChild;F.style.background="#1a3a1a",R.appendChild(F),R.scrollTop=R.scrollHeight}}catch(I){console.error("Error parsing log:",I)}},u.onerror=()=>{E.textContent="\u{1F534}",H.textContent="Disconnected",b=!1,N.textContent="\u25B6 Stream"},h._eventSource=u}function s(){u&&(u.close(),u=null),h._eventSource&&(h._eventSource.close(),h._eventSource=null),b=!1,N.textContent="\u25B6 Stream",B.style.display="none"}function n(){if(!U||U.length===0){showNotification("No logs to download","error");return}const o=L.querySelector(`option[value="${A}"]`)?.dataset.name||A,l=new Date().toISOString().replace(/[:.]/g,"-"),k=`${o}-logs-${l}.txt`,I=U.map(q=>{const G=q.timestamp||"",X=q.stream==="stderr"?"[ERR]":"[OUT]";return`${G?G+" ":""}${X} ${q.text}`}).join(`
`),U=new Blob([h],{type:"text/plain"}),_=URL.createObjectURL(U),F=document.createElement("a");F.href=_,F.download=S,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(_),showNotification(`Downloaded ${D.length} log lines`,"success")}C?.addEventListener("change",()=>{n()}),M?.addEventListener("change",()=>{n()}),R?.addEventListener("click",()=>{n()}),P?.addEventListener("click",()=>{I?t():e()}),A?.addEventListener("click",()=>{o()}),p?.addEventListener("click",()=>{E.value="",l(D,"")}),E?.addEventListener("input",()=>{clearTimeout(b),b=setTimeout(()=>{l(D,E.value.trim())},300)}),E?.addEventListener("keydown",s=>{s.key==="Escape"&&(E.value="",l(D,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{y.classList.add("show"),w()});function a(){t(),y.classList.remove("show")}T?.addEventListener("click",a),x?.addEventListener("click",a),document.addEventListener("keydown",s=>{s.key==="Escape"&&y.classList.contains("show")&&a()}),y.addEventListener("click",s=>{s.target===y&&a()}),window.openContainerLogsModal=function(s,d){y.classList.add("show"),w().then(()=>{const S=Array.from(C.options).find(h=>h.value===s||h.dataset.name===d);S?(C.value=S.value,m(S.value),n()):s?(g=s,j.textContent=d||s,v.textContent="-",N.textContent="-",n()):O.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>'})}})(),(function(){injectModal("snapshot-modal",`<div id="snapshot-modal" class="weather-modal"> `),j=new Blob([I],{type:"text/plain"}),_=URL.createObjectURL(j),F=document.createElement("a");F.href=_,F.download=k,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(_),showNotification(`Downloaded ${U.length} log lines`,"success")}L?.addEventListener("change",()=>{t()}),$?.addEventListener("change",()=>{t()}),P?.addEventListener("click",()=>{t()}),N?.addEventListener("click",()=>{b?s():e()}),D?.addEventListener("click",()=>{n()}),m?.addEventListener("click",()=>{S.value="",d(U,"")}),S?.addEventListener("input",()=>{clearTimeout(g),g=setTimeout(()=>{d(U,S.value.trim())},300)}),S?.addEventListener("keydown",o=>{o.key==="Escape"&&(S.value="",d(U,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{h.classList.add("show"),x()});function a(){s(),h.classList.remove("show")}T?.addEventListener("click",a),w?.addEventListener("click",a),document.addEventListener("keydown",o=>{o.key==="Escape"&&h.classList.contains("show")&&a()}),h.addEventListener("click",o=>{o.target===h&&a()}),window.openContainerLogsModal=function(o,l){h.classList.add("show"),x().then(()=>{const k=Array.from(L.options).find(I=>I.value===o||I.dataset.name===l);k?(L.value=k.value,y(k.value),t()):o?(A=o,O.textContent=l||o,f.textContent="-",z.textContent="-",t()):R.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>'})}})(),(function(){injectModal("snapshot-modal",`<div id="snapshot-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 700px; max-width: 850px;"> <div class="weather-modal-content" style="min-width: 700px; max-width: 850px;">
<h3>\u{1F4BE} Container Snapshots</h3> <h3>\u{1F4BE} Container Snapshots</h3>
<p class="modal-subtitle"> <p class="modal-subtitle">
@@ -683,7 +670,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="snapshot-close">Close</button> <button id="snapshot-close">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("snapshot-modal"),C=document.getElementById("snapshot-btn"),O=document.getElementById("snapshot-close"),E=document.getElementById("snapshot-container-select"),M=document.getElementById("snapshot-details"),R=document.getElementById("snapshot-create-btn"),P=document.getElementById("snapshot-create-status");let A=null;async function p(){try{const L=await(await fetch("/api/v1/containers")).json();if(!L.success||!L.containers)return;E.innerHTML='<option value="">-- Select a container --</option>';for(const u of L.containers){const j=document.createElement("option");j.value=u.id,j.textContent=`${u.name||u.id} (${u.image||"unknown"})`,j.dataset.name=u.name,j.dataset.image=u.image,j.dataset.status=u.status,j.dataset.created=u.created,E.appendChild(j)}}catch(H){console.error("Failed to load containers:",H)}}function T(H){if(!H||!H.value){M.style.display="none",A=null;return}A=H.value,document.getElementById("snapshot-image").textContent=H.dataset.image||"-",document.getElementById("snapshot-status").textContent=H.dataset.status||"-",document.getElementById("snapshot-created").textContent=H.dataset.created?new Date(H.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=H.value.substring(0,12),M.style.display=""}async function x(){if(!A){P.textContent="Please select a container first",P.style.color="var(--bad-fg)";return}const H=document.getElementById("snapshot-name").value.trim();if(!H){P.textContent="Please enter a snapshot name",P.style.color="var(--bad-fg)";return}const L=document.getElementById("snapshot-leave-running").checked;R.disabled=!0,R.textContent="Creating...",P.textContent="";try{const j=await(await fetch(`/api/v1/containers/${encodeURIComponent(A)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:H,leaveRunning:L})})).json();j.success?(P.textContent=`\u2713 Snapshot "${H}" created successfully`,P.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(P.textContent=`\u2717 Failed: ${j.error||"Unknown error"}`,P.style.color="var(--bad-fg)")}catch(u){P.textContent=`\u2717 Error: ${u.message}`,P.style.color="var(--bad-fg)"}finally{R.disabled=!1,R.textContent="\u{1F4BE} Create Snapshot"}}function $(){y.classList.add("show"),p()}function k(){y.classList.remove("show"),M.style.display="none",A=null,E.selectedIndex=0}C?.addEventListener("click",$),O?.addEventListener("click",k),wireModal(y,O),E?.addEventListener("change",H=>{const L=E.options[E.selectedIndex];T(L)}),R?.addEventListener("click",x),y?.querySelectorAll(".panel-tab").forEach(H=>{H.addEventListener("click",()=>{y.querySelectorAll(".panel-tab").forEach(L=>L.classList.remove("active")),y.querySelectorAll(".panel-section").forEach(L=>L.classList.remove("active")),H.classList.add("active"),y.querySelector(`#${H.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`<div id="arr-setup-modal" class="weather-modal"> </div>`);const h=document.getElementById("snapshot-modal"),L=document.getElementById("snapshot-btn"),R=document.getElementById("snapshot-close"),S=document.getElementById("snapshot-container-select"),$=document.getElementById("snapshot-details"),P=document.getElementById("snapshot-create-btn"),N=document.getElementById("snapshot-create-status");let D=null;async function m(){try{const C=await(await fetch("/api/v1/containers")).json();if(!C.success||!C.containers)return;S.innerHTML='<option value="">-- Select a container --</option>';for(const v of C.containers){const O=document.createElement("option");O.value=v.id,O.textContent=`${v.name||v.id} (${v.image||"unknown"})`,O.dataset.name=v.name,O.dataset.image=v.image,O.dataset.status=v.status,O.dataset.created=v.created,S.appendChild(O)}}catch(H){console.error("Failed to load containers:",H)}}function T(H){if(!H||!H.value){$.style.display="none",D=null;return}D=H.value,document.getElementById("snapshot-image").textContent=H.dataset.image||"-",document.getElementById("snapshot-status").textContent=H.dataset.status||"-",document.getElementById("snapshot-created").textContent=H.dataset.created?new Date(H.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=H.value.substring(0,12),$.style.display=""}async function w(){if(!D){N.textContent="Please select a container first",N.style.color="var(--bad-fg)";return}const H=document.getElementById("snapshot-name").value.trim();if(!H){N.textContent="Please enter a snapshot name",N.style.color="var(--bad-fg)";return}const C=document.getElementById("snapshot-leave-running").checked;P.disabled=!0,P.textContent="Creating...",N.textContent="";try{const O=await(await fetch(`/api/v1/containers/${encodeURIComponent(D)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:H,leaveRunning:C})})).json();O.success?(N.textContent=`\u2713 Snapshot "${H}" created successfully`,N.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(N.textContent=`\u2717 Failed: ${O.error||"Unknown error"}`,N.style.color="var(--bad-fg)")}catch(v){N.textContent=`\u2717 Error: ${v.message}`,N.style.color="var(--bad-fg)"}finally{P.disabled=!1,P.textContent="\u{1F4BE} Create Snapshot"}}function B(){h.classList.add("show"),m()}function E(){h.classList.remove("show"),$.style.display="none",D=null,S.selectedIndex=0}L?.addEventListener("click",B),R?.addEventListener("click",E),wireModal(h,R),S?.addEventListener("change",H=>{const C=S.options[S.selectedIndex];T(C)}),P?.addEventListener("click",w),h?.querySelectorAll(".panel-tab").forEach(H=>{H.addEventListener("click",()=>{h.querySelectorAll(".panel-tab").forEach(C=>C.classList.remove("active")),h.querySelectorAll(".panel-section").forEach(C=>C.classList.remove("active")),H.classList.add("active"),h.querySelector(`#${H.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`<div id="arr-setup-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 600px; max-width: 720px;"> <div class="weather-modal-content" style="min-width: 600px; max-width: 720px;">
<h3>\u{1F3AC} Smart Arr Connect</h3> <h3>\u{1F3AC} Smart Arr Connect</h3>
<p style="color: var(--muted); margin: 0 0 16px; font-size: 0.9rem;"> <p style="color: var(--muted); margin: 0 0 16px; font-size: 0.9rem;">
@@ -762,73 +749,73 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="arr-setup-cancel">Close</button> <button id="arr-setup-cancel">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("arr-setup-modal"),C=document.getElementById("arr-setup-btn"),O=document.getElementById("arr-setup-cancel"),E=document.getElementById("smart-connect-btn"),M=document.getElementById("smart-phase-detect"),R=document.getElementById("smart-phase-credentials"),P=document.getElementById("smart-phase-progress"),A=document.getElementById("smart-phase-results"),p=document.getElementById("smart-detect-results"),T=document.getElementById("smart-credential-inputs"),x=document.getElementById("smart-progress-steps"),$=document.getElementById("smart-results-content"),k=document.getElementById("smart-plex-libraries"),H=document.getElementById("smart-retry-btn");let L=null;const u={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},j={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function v(b){M.style.display=b==="detect"?"block":"none",R.style.display=b==="credentials"?"block":"none",P.style.display=b==="progress"?"block":"none",A.style.display=b==="results"?"block":"none"}function N(b){const z={connected:{bg:"var(--ok-fg)",icon:"&#10003;",text:"Connected"},needs_key:{bg:"#f39c12",icon:"&#128273;",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"&mdash;",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"&#10007;",text:"Error"}},i=z[b]||z.not_found;return`<span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: color-mix(in srgb, ${i.bg} 20%, transparent); color: ${i.bg};">${i.icon} ${i.text}</span>`}async function g(){v("detect"),p.style.display="none";try{if(L=await(await fetch("/api/v1/arr/smart-detect")).json(),!L.success){p.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Detection failed: ${escapeHtml(L.error)}</div>`,p.style.display="block";return}let z='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[c,l]of Object.entries(L.services)){const w=u[c]||"\u{1F4E6}",m=j[c]||c,n=l.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(l.source)}</span>`:"",e=l.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(l.version)}</span>`:"",t=(l.hasApiKey||l.hasToken)&&l.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";z+=`<div style="display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);"> </div>`);const h=document.getElementById("arr-setup-modal"),L=document.getElementById("arr-setup-btn"),R=document.getElementById("arr-setup-cancel"),S=document.getElementById("smart-connect-btn"),$=document.getElementById("smart-phase-detect"),P=document.getElementById("smart-phase-credentials"),N=document.getElementById("smart-phase-progress"),D=document.getElementById("smart-phase-results"),m=document.getElementById("smart-detect-results"),T=document.getElementById("smart-credential-inputs"),w=document.getElementById("smart-progress-steps"),B=document.getElementById("smart-results-content"),E=document.getElementById("smart-plex-libraries"),H=document.getElementById("smart-retry-btn");let C=null;const v={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},O={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function f(g){$.style.display=g==="detect"?"block":"none",P.style.display=g==="credentials"?"block":"none",N.style.display=g==="progress"?"block":"none",D.style.display=g==="results"?"block":"none"}function z(g){const M={connected:{bg:"var(--ok-fg)",icon:"&#10003;",text:"Connected"},needs_key:{bg:"#f39c12",icon:"&#128273;",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"&mdash;",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"&#10007;",text:"Error"}},r=M[g]||M.not_found;return`<span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: color-mix(in srgb, ${r.bg} 20%, transparent); color: ${r.bg};">${r.icon} ${r.text}</span>`}async function A(){f("detect"),m.style.display="none";try{if(C=await(await fetch("/api/v1/arr/smart-detect")).json(),!C.success){m.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Detection failed: ${escapeHtml(C.error)}</div>`,m.style.display="block";return}let M='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[c,d]of Object.entries(C.services)){const x=v[c]||"\u{1F4E6}",y=O[c]||c,t=d.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(d.source)}</span>`:"",e=d.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(d.version)}</span>`:"",s=(d.hasApiKey||d.hasToken)&&d.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";M+=`<div style="display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${w}</span> <span style="font-size: 1.1rem;">${x}</span>
<div style="flex: 1;"> <div style="flex: 1;">
<div style="font-weight: 500; font-size: 0.9rem;">${m}</div> <div style="font-weight: 500; font-size: 0.9rem;">${y}</div>
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;"> <div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
${n} ${e} ${t} ${t} ${e} ${s}
</div> </div>
</div> </div>
${N(l.status)} ${z(d.status)}
</div>`}z+="</div>";const i=L.summary;z+=`<div style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; font-size: 0.85rem;"> </div>`}M+="</div>";const r=C.summary;M+=`<div style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; font-size: 0.85rem;">
${escapeHtml(String(i.fullyConnected))}/${escapeHtml(String(i.totalDetected+(5-i.totalDetected)))} services detected &middot; ${escapeHtml(String(r.fullyConnected))}/${escapeHtml(String(r.totalDetected+(5-r.totalDetected)))} services detected &middot;
${escapeHtml(String(i.fullyConnected))} connected${i.needsApiKey>0?` &middot; <strong>${escapeHtml(String(i.needsApiKey))} needs API key</strong>`:""} ${escapeHtml(String(r.fullyConnected))} connected${r.needsApiKey>0?` &middot; <strong>${escapeHtml(String(r.needsApiKey))} needs API key</strong>`:""}
</div>`,p.innerHTML=z,p.style.display="block",D(L),setTimeout(()=>{v("credentials")},800)}catch(b){p.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(b.message)}</div>`,p.style.display="block"}}function D(b){let z="";const i=b.services,c=["radarr","sonarr","prowlarr"];for(const m of c){const n=i[m];if(!n||n.status==="not_found"&&!n.url)continue;const e=u[m],t=j[m],o=n.status==="connected";z+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${o?"var(--ok-fg)":"var(--border)"};"> </div>`,m.innerHTML=M,m.style.display="block",U(C),setTimeout(()=>{f("credentials")},800)}catch(g){m.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(g.message)}</div>`,m.style.display="block"}}function U(g){let M="";const r=g.services,c=["radarr","sonarr","prowlarr"];for(const y of c){const t=r[y];if(!t||t.status==="not_found"&&!t.url)continue;const e=v[y],s=O[y],n=t.status==="connected";M+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${n?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;"> <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
<span style="font-size: 1.1rem;">${e}</span> <span style="font-size: 1.1rem;">${e}</span>
<span style="font-weight: 500;">${t}</span> <span style="font-weight: 500;">${s}</span>
<span id="smart-${m}-status" style="margin-left: auto; font-size: 0.75rem;"> <span id="smart-${y}-status" style="margin-left: auto; font-size: 0.75rem;">
${o?'<span style="color: var(--ok-fg);">&#10003; Connected</span>':""} ${n?'<span style="color: var(--ok-fg);">&#10003; Connected</span>':""}
</span> </span>
</div> </div>
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px;"> <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px;">
<div> <div>
<label style="font-size: 0.75rem; color: var(--muted);">URL:</label> <label style="font-size: 0.75rem; color: var(--muted);">URL:</label>
<input type="text" id="smart-${m}-url" value="${escapeHtml(n.url||"")}" placeholder="https://seedbox.com/${m}/" <input type="text" id="smart-${y}-url" value="${escapeHtml(t.url||"")}" placeholder="https://seedbox.com/${y}/"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" /> style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div> </div>
<div> <div>
<label style="font-size: 0.75rem; color: var(--muted);">API Key:</label> <label style="font-size: 0.75rem; color: var(--muted);">API Key:</label>
<input type="password" id="smart-${m}-key" placeholder="${o?"(saved)":"Paste API key"}" <input type="password" id="smart-${y}-key" placeholder="${n?"(saved)":"Paste API key"}"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" /> style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div> </div>
</div> </div>
<button onclick="smartTestConnection('${m}')" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button> <button onclick="smartTestConnection('${y}')" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
</div>`}const l=i.plex;if(l){const m=l.status==="connected";z+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${m?"var(--ok-fg)":"var(--border)"}; margin-bottom: 10px;"> </div>`}const d=r.plex;if(d){const y=d.status==="connected";M+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${y?"var(--ok-fg)":"var(--border)"}; margin-bottom: 10px;">
<div style="display: flex; align-items: center; gap: 8px;"> <div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F3AC}</span> <span style="font-size: 1.1rem;">\u{1F3AC}</span>
<span style="font-weight: 500;">Plex</span> <span style="font-weight: 500;">Plex</span>
${N(l.status)} ${z(d.status)}
<span style="margin-left: auto; font-size: 0.75rem; color: var(--muted);">${escapeHtml(l.source||"")}</span> <span style="margin-left: auto; font-size: 0.75rem; color: var(--muted);">${escapeHtml(d.source||"")}</span>
</div> </div>
</div>`}const w=i.seerr;if(w){const m=w.status==="connected";let n="";if(w.configuredServices){const e=w.configuredServices;n=`<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;"> </div>`}const x=r.seerr;if(x){const y=x.status==="connected";let t="";if(x.configuredServices){const e=x.configuredServices;t=`<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">
Configured: ${e.radarr?"&#10003; Radarr":"&#10007; Radarr"} &middot; Configured: ${e.radarr?"&#10003; Radarr":"&#10007; Radarr"} &middot;
${e.sonarr?"&#10003; Sonarr":"&#10007; Sonarr"} &middot; ${e.sonarr?"&#10003; Sonarr":"&#10007; Sonarr"} &middot;
${e.plex?"&#10003; Plex":"&#10007; Plex"} ${e.plex?"&#10003; Plex":"&#10007; Plex"}
</div>`}z+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${m?"var(--ok-fg)":"var(--border)"};"> </div>`}M+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${y?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px;"> <div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F4CB}</span> <span style="font-size: 1.1rem;">\u{1F4CB}</span>
<span style="font-weight: 500;">Seerr</span> <span style="font-weight: 500;">Seerr</span>
${N(w.status)} ${z(x.status)}
</div> </div>
${n} ${t}
</div>`}T.innerHTML=z}window.smartTestConnection=async function(b){const z=document.getElementById(`smart-${b}-url`),i=document.getElementById(`smart-${b}-key`),c=document.getElementById(`smart-${b}-status`),l=z?.value.trim(),w=i?.value.trim();if(!l||!w){c.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}c.innerHTML='<span class="brand-spinner"></span>';try{const n=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:b,url:l,apiKey:w})})).json();n.success?c.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(n.appName||"Connected")} v${escapeHtml(n.version||"")}</span>`:c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(n.error)}</span>`}catch(m){c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(m.message)}</span>`}};async function B(){v("progress"),x.innerHTML='<div style="text-align: center; padding: 20px;"><span class="brand-spinner"></span><div style="color: var(--muted); margin-top: 8px;">Connecting services...</div></div>';const b={};for(const i of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${i}-url`)?.value.trim(),l=document.getElementById(`smart-${i}-key`)?.value.trim();l&&c?b[i]={apiKey:l,url:c}:l&&(b[i]={apiKey:l})}const z={services:Object.keys(b).length>0?b:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})).json();let l="";for(const w of c.steps||[]){const m=w.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',n=w.status==="success"?"var(--muted)":"var(--bad-fg)";l+=`<div style="display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;"> </div>`}T.innerHTML=M}window.smartTestConnection=async function(g){const M=document.getElementById(`smart-${g}-url`),r=document.getElementById(`smart-${g}-key`),c=document.getElementById(`smart-${g}-status`),d=M?.value.trim(),x=r?.value.trim();if(!d||!x){c.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}c.innerHTML='<span class="brand-spinner"></span>';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,url:d,apiKey:x})})).json();t.success?c.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}</span>`:c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(t.error)}</span>`}catch(y){c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(y.message)}</span>`}};async function p(){f("progress"),w.innerHTML='<div style="text-align: center; padding: 20px;"><span class="brand-spinner"></span><div style="color: var(--muted); margin-top: 8px;">Connecting services...</div></div>';const g={};for(const r of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${r}-url`)?.value.trim(),d=document.getElementById(`smart-${r}-key`)?.value.trim();d&&c?g[r]={apiKey:d,url:c}:d&&(g[r]={apiKey:d})}const M={services:Object.keys(g).length>0?g:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)})).json();let d="";for(const x of c.steps||[]){const y=x.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',t=x.status==="success"?"var(--muted)":"var(--bad-fg)";d+=`<div style="display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;">
${m} ${y}
<span>${escapeHtml(w.step)}</span> <span>${escapeHtml(x.step)}</span>
<span style="margin-left: auto; font-size: 0.75rem; color: ${n};">${escapeHtml(w.details||"")}</span> <span style="margin-left: auto; font-size: 0.75rem; color: ${t};">${escapeHtml(x.details||"")}</span>
</div>`}x.innerHTML=l,setTimeout(()=>f(c),500)}catch(i){x.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(i.message)}</div>`}}function f(b){v("results");const z=b.summary||{},i=z.failed===0&&z.succeeded>0,c=i?"var(--ok-fg)":"#f39c12",l=i?"&#10003;":"&#9888;",w=i?"All Connected!":`${escapeHtml(String(z.succeeded))}/${escapeHtml(String(z.totalSteps))} Steps Succeeded`;let m=`<div style="text-align: center; padding: 16px; background: color-mix(in srgb, ${c} 12%, transparent); border-radius: 10px; border: 1px solid ${c}; margin-bottom: 12px;"> </div>`}w.innerHTML=d,setTimeout(()=>u(c),500)}catch(r){w.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(r.message)}</div>`}}function u(g){f("results");const M=g.summary||{},r=M.failed===0&&M.succeeded>0,c=r?"var(--ok-fg)":"#f39c12",d=r?"&#10003;":"&#9888;",x=r?"All Connected!":`${escapeHtml(String(M.succeeded))}/${escapeHtml(String(M.totalSteps))} Steps Succeeded`;let y=`<div style="text-align: center; padding: 16px; background: color-mix(in srgb, ${c} 12%, transparent); border-radius: 10px; border: 1px solid ${c}; margin-bottom: 12px;">
<div style="font-size: 1.5rem; color: ${c};">${l}</div> <div style="font-size: 1.5rem; color: ${c};">${d}</div>
<div style="font-size: 1.1rem; font-weight: 600; color: ${c};">${w}</div> <div style="font-size: 1.1rem; font-weight: 600; color: ${c};">${x}</div>
<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(z.succeeded))} succeeded, ${escapeHtml(String(z.failed))} failed</div> <div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(M.succeeded))} succeeded, ${escapeHtml(String(M.failed))} failed</div>
</div>`;m+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const n of b.steps||[]){const e=n.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>';m+=`<div style="display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: 0.8rem;"> </div>`;y+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const t of g.steps||[]){const e=t.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>';y+=`<div style="display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: 0.8rem;">
${e} ${escapeHtml(n.step)} <span style="margin-left: auto; color: var(--muted); font-size: 0.75rem;">${escapeHtml(n.details||"")}</span> ${e} ${escapeHtml(t.step)} <span style="margin-left: auto; color: var(--muted); font-size: 0.75rem;">${escapeHtml(t.details||"")}</span>
</div>`}m+="</div>",$.innerHTML=m,H.style.display=z.failed>0?"block":"none",b.steps?.some(n=>n.step.includes("Plex")&&n.status==="success")&&I()}async function I(){try{const z=await(await fetch("/api/v1/plex/libraries")).json();if(z.success&&z.libraries?.length>0){let i=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);"> </div>`}y+="</div>",B.innerHTML=y,H.style.display=M.failed>0?"block":"none",g.steps?.some(t=>t.step.includes("Plex")&&t.status==="success")&&b()}async function b(){try{const M=await(await fetch("/api/v1/plex/libraries")).json();if(M.success&&M.libraries?.length>0){let r=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 8px; font-size: 0.85rem; color: var(--accent);">\u{1F3AC} ${escapeHtml(z.serverName)} Libraries</h4> <h4 style="margin: 0 0 8px; font-size: 0.85rem; color: var(--accent);">\u{1F3AC} ${escapeHtml(M.serverName)} Libraries</h4>
<div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const c of z.libraries){const l=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";i+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;"> <div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const c of M.libraries){const d=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";r+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
${l} <strong>${escapeHtml(c.title)}</strong> ${d} <strong>${escapeHtml(c.title)}</strong>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(String(c.count))} items</span> <span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(String(c.count))} items</span>
</div>`}i+="</div></div>",k.innerHTML=i,k.style.display="block"}}catch{}}C?.addEventListener("click",()=>{y.classList.add("show"),k.style.display="none",g()}),wireModal(y,O),E?.addEventListener("click",B),H?.addEventListener("click",B)})(),(function(){const y=new ErrorHandler;injectModal("notifications-modal",`<div id="notifications-modal" class="weather-modal"> </div>`}r+="</div></div>",E.innerHTML=r,E.style.display="block"}}catch{}}L?.addEventListener("click",()=>{h.classList.add("show"),E.style.display="none",A()}),wireModal(h,R),S?.addEventListener("click",p),H?.addEventListener("click",p)})(),(function(){const h=new ErrorHandler;injectModal("notifications-modal",`<div id="notifications-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;"> <div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F514} Notification Settings</h3> <h3>\u{1F514} Notification Settings</h3>
@@ -1013,15 +1000,15 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="notifications-save" class="btn-accent">Save Settings</button> <button id="notifications-save" class="btn-accent">Save Settings</button>
</div> </div>
</div> </div>
</div>`);const C=document.getElementById("notifications-modal"),O=document.getElementById("manage-notifications"),E=document.getElementById("notifications-save"),M=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const H=document.getElementById(`${k}-enabled`),L=document.getElementById(`${k}-config`);H?.addEventListener("change",()=>{L.style.display=H.checked?"block":"none"})});const R=document.getElementById("health-check-enabled"),P=document.getElementById("health-check-config");R?.addEventListener("change",()=>{P.style.opacity=R.checked?"1":"0.5"});async function A(){try{const H=await(await fetch("/api/v1/notifications/config")).json();if(H.success){const L=H.config;document.getElementById("notifications-enabled").checked=L.enabled,document.getElementById("discord-enabled").checked=L.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=L.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=L.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=L.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=L.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=L.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=L.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=L.providers?.email?.enabled?"block":"none",L.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=L.providers.ntfy.serverUrl),L.providers?.email?.host&&(document.getElementById("email-host").value=L.providers.email.host),L.providers?.email?.from&&(document.getElementById("email-from").value=L.providers.email.from),document.getElementById("health-check-enabled").checked=L.healthCheck?.enabled||!1,L.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=L.healthCheck.intervalMinutes),L.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(L.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=L.events?.containerDown!==!1,document.getElementById("event-container-up").checked=L.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=L.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=L.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=L.events?.resourceAlert!==!1}}catch(k){y.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function p(){try{const H=await(await fetch("/api/v1/notifications/history?limit=10")).json(),L=document.getElementById("notification-history");H.success&&H.history?.length>0?L.innerHTML=H.history.map(u=>{const j=new Date(u.timestamp).toLocaleString();return` </div>`);const L=document.getElementById("notifications-modal"),R=document.getElementById("manage-notifications"),S=document.getElementById("notifications-save"),$=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(E=>{const H=document.getElementById(`${E}-enabled`),C=document.getElementById(`${E}-config`);H?.addEventListener("change",()=>{C.style.display=H.checked?"block":"none"})});const P=document.getElementById("health-check-enabled"),N=document.getElementById("health-check-config");P?.addEventListener("change",()=>{N.style.opacity=P.checked?"1":"0.5"});async function D(){try{const H=await(await fetch("/api/v1/notifications/config")).json();if(H.success){const C=H.config;document.getElementById("notifications-enabled").checked=C.enabled,document.getElementById("discord-enabled").checked=C.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=C.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=C.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=C.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=C.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=C.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=C.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=C.providers?.email?.enabled?"block":"none",C.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=C.providers.ntfy.serverUrl),C.providers?.email?.host&&(document.getElementById("email-host").value=C.providers.email.host),C.providers?.email?.from&&(document.getElementById("email-from").value=C.providers.email.from),document.getElementById("health-check-enabled").checked=C.healthCheck?.enabled||!1,C.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=C.healthCheck.intervalMinutes),C.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(C.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=C.events?.containerDown!==!1,document.getElementById("event-container-up").checked=C.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=C.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=C.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=C.events?.resourceAlert!==!1}}catch(E){h.logError("[Notifications] Load Config",E,{function:"loadConfig"})}}async function m(){try{const H=await(await fetch("/api/v1/notifications/history?limit=10")).json(),C=document.getElementById("notification-history");H.success&&H.history?.length>0?C.innerHTML=H.history.map(v=>{const O=new Date(v.timestamp).toLocaleString();return`
<div style="padding: 6px 8px; border-bottom: 1px solid var(--border); display: flex; gap: 8px; align-items: flex-start;"> <div style="padding: 6px 8px; border-bottom: 1px solid var(--border); display: flex; gap: 8px; align-items: flex-start;">
<span style="color: ${{success:"var(--ok-fg)",error:"var(--bad-fg)",warning:"#f39c12",info:"var(--accent)"}[u.type]||"var(--muted)"}">${u.type==="success"?"\u2713":u.type==="error"?"\u2717":"\u2139"}</span> <span style="color: ${{success:"var(--ok-fg)",error:"var(--bad-fg)",warning:"#f39c12",info:"var(--accent)"}[v.type]||"var(--muted)"}">${v.type==="success"?"\u2713":v.type==="error"?"\u2717":"\u2139"}</span>
<div style="flex: 1; min-width: 0;"> <div style="flex: 1; min-width: 0;">
<div style="font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(u.title)}</div> <div style="font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(v.title)}</div>
<div style="font-size: 0.7rem; color: var(--muted);">${j}</div> <div style="font-size: 0.7rem; color: var(--muted);">${O}</div>
</div> </div>
</div> </div>
`}).join(""):L.innerHTML='<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>'}catch(k){y.logError("[Notifications] Load History",k,{function:"loadHistory"})}}async function T(){try{const k={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},L=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();L.success?(showNotification("Notification settings saved","success",3e3),C.classList.remove("show")):showNotification(`Failed to save: ${L.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function x(k){try{const L=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:k})})).json();L.success?showNotification(`Test ${k} notification sent!`,"success",3e3):showNotification(`Test failed: ${L.error}`,"error",3e3)}catch(H){showNotification(`Error: ${H.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>x("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>x("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>x("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>x("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const H=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();H.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(H.lastCheck).toLocaleString()} (${H.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),O?.addEventListener("click",()=>{C.classList.add("show"),A(),p()}),E?.addEventListener("click",T),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),H=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const u=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();u.success?(showNotification("Test notification sent!","success",3e3),$()):showNotification(`Test failed: ${u.results?.map(j=>`${j.provider}: ${j.error||"ok"}`).join(", ")}`,"error",5e3)}catch(L){showNotification(`Error: ${L.message}`,"error",3e3)}finally{k.textContent=H,k.disabled=!1}});async function $(){try{const H=await(await fetch("/api/v1/notifications/status")).json();if(H.success&&H.lastSent){const L=document.getElementById("last-notification-sent");L&&(L.textContent=`Last sent: ${new Date(H.lastSent).toLocaleString()}`)}}catch{}}wireModal(C,M)})(),(function(){document.addEventListener("click",y=>{const C=y.target.closest(".panel-tab");if(!C)return;const O=C.dataset.panel;if(!O)return;const E=C.closest(".panel-tabs"),M=E.closest(".weather-modal-content");E.querySelectorAll(".panel-tab").forEach(P=>P.classList.remove("active")),C.classList.add("active"),M.querySelectorAll(".panel-section").forEach(P=>P.classList.remove("active"));const R=M.querySelector("#"+O);R&&R.classList.add("active")})})(),(function(){var y=["dashcaddy_site_config","dashca Line truncated `}).join(""):C.innerHTML='<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>'}catch(E){h.logError("[Notifications] Load History",E,{function:"loadHistory"})}}async function T(){try{const E={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},C=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)})).json();C.success?(showNotification("Notification settings saved","success",3e3),L.classList.remove("show")):showNotification(`Failed to save: ${C.error}`,"error",3e3)}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}}async function w(E){try{const C=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:E})})).json();C.success?showNotification(`Test ${E} notification sent!`,"success",3e3):showNotification(`Test failed: ${C.error}`,"error",3e3)}catch(H){showNotification(`Error: ${H.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>w("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>w("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>w("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>w("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const H=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();H.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(H.lastCheck).toLocaleString()} (${H.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}}),R?.addEventListener("click",()=>{L.classList.add("show"),D(),m()}),S?.addEventListener("click",T),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const E=document.getElementById("notifications-send-test"),H=E.textContent;E.textContent="Sending...",E.disabled=!0;try{const v=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();v.success?(showNotification("Test notification sent!","success",3e3),B()):showNotification(`Test failed: ${v.results?.map(O=>`${O.provider}: ${O.error||"ok"}`).join(", ")}`,"error",5e3)}catch(C){showNotification(`Error: ${C.message}`,"error",3e3)}finally{E.textContent=H,E.disabled=!1}});async function B(){try{const H=await(await fetch("/api/v1/notifications/status")).json();if(H.success&&H.lastSent){const C=document.getElementById("last-notification-sent");C&&(C.textContent=`Last sent: ${new Date(H.lastSent).toLocaleString()}`)}}catch{}}wireModal(L,$)})(),(function(){document.addEventListener("click",h=>{const L=h.target.closest(".panel-tab");if(!L)return;const R=L.dataset.panel;if(!R)return;const S=L.closest(".panel-tabs"),$=S.closest(".weather-modal-content");S.querySelectorAll(".panel-tab").forEach(N=>N.classList.remove("active")),L.classList.add("active"),$.querySelectorAll(".panel-section").forEach(N=>N.classList.remove("active"));const P=$.querySelector("#"+R);P&&P.classList.add("active")})})(),(function(){var h=["dashcaddy_site_config","dashca Line truncated
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;"> <div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F4BE} Backup & Restore</h3> <h3>\u{1F4BE} Backup & Restore</h3>
<p class="modal-subtitle"> <p class="modal-subtitle">
@@ -1127,9 +1114,9 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="backup-cancel">Close</button> <button id="backup-cancel">Close</button>
</div> </div>
</div> </div>
</div>`);var R=document.getElementById("backup-modal"),P=document.getElementById("backup-restore-btn"),A=document.getElementById("backup-cancel"),p=document.getElementById("backup-export-btn"),T=document.getElementById("backup-select-file"),x=document.getElementById("backup-file-input"),$=document.getElementById("backup-file-name"),k=document.getElementById("backup-preview"),H=document.getElementById("backup-preview-content"),L=document.getElementById("backup-do-restore-btn"),u=document.getElementById("backup-result"),j=document.getElementById("backup-schedules-container"),v=document.getElementById("backup-history-container"),N=document.getElementById("backup-disk-container"),g=document.getElementById("pointintime-container"),D=null;P?.addEventListener("click",function(){R.classList.add("show"),u&&(u.style.display="none"),k&&(k.style.display="none"),$&&($.style.display="none"),D=null}),wireModal(R,A),p?.addEventListener("click",async function(){p.disabled=!0,p.innerHTML='<span class="brand-spinner"></span> Exporting...';try{var e=await fetch("/api/v1/backup/export"),t=await e.json();t.browserState=C();var o=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),r=URL.createObjectURL(o),a=document.createElement("a");a.href=r,a.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r);var s=Object.keys(t.browserState).length,d=t.themes?Object.keys(t.themes).length:0;u.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+s+" browser settings"+(d?" + "+d+" themes":""),u.style.display="block",u.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",u.style.border="1px solid var(--ok-fg)"}catch(S){u.innerHTML="\u274C Export failed: "+escapeHtml(S.message),u.style.display="block",u.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",u.style.border="1px solid var(--bad-fg)"}p.disabled=!1,p.innerHTML="\u2B07\uFE0F Download Full Backup"}),T?.addEventListener("click",function(){x.click()}),x?.addEventListener("change",async function(e){var t=e.target.files[0];if(t){$.textContent="\u{1F4C4} "+t.name,$.style.display="block",u.style.display="none";try{var o=await t.text(),r=JSON.parse(o);if(E(r)){D=r;var a='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(r.version)+")</div>";a+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',r.services?.length&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4CB} '+r.services.length+" services</span>"),r.customApps?.length&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4E6} '+r.customApps.length+" custom apps</span>"),r.theme&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(r.theme)+"</span>"),r.userThemes&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} '+Object.keys(r.userThemes).length+" custom themes</span>"),a+="</div>",H.innerHTML=a,k.style.display="block";return}var s=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),d=await s.json();if(d.success){D=r;var a='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(r.exportedAt).toLocaleString()+" (v"+escapeHtml(r.version)+")</div>";a+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',a+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var S in d.preview.files){var h=d.preview.files[S],U=h.action==="create"?"\u{1F195}":"\u{1F4DD}";a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+U+" "+escapeHtml(h.description)+"</span>"}a+="</div>",d.preview.serviceCount&&(a+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+d.preview.serviceCount+" services</div>"),d.preview.themeCount&&(a+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+d.preview.themeCount+" custom themes</div>"),d.preview.browserStateCount&&(a+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',a+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+d.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),H.innerHTML=a,k.style.display="block"}else u.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(d.error),u.style.display="block",u.style.background="color-mix(in srgb, #f39c12 15%, transparent)",u.style.border="1px solid #f39c12",k.style.display="none"}catch(_){u.innerHTML="\u274CLine truncated </div>`);var P=document.getElementById("backup-modal"),N=document.getElementById("backup-restore-btn"),D=document.getElementById("backup-cancel"),m=document.getElementById("backup-export-btn"),T=document.getElementById("backup-select-file"),w=document.getElementById("backup-file-input"),B=document.getElementById("backup-file-name"),E=document.getElementById("backup-preview"),H=document.getElementById("backup-preview-content"),C=document.getElementById("backup-do-restore-btn"),v=document.getElementById("backup-result"),O=document.getElementById("backup-schedules-container"),f=document.getElementById("backup-history-container"),z=document.getElementById("backup-disk-container"),A=document.getElementById("pointintime-container"),U=null;N?.addEventListener("click",function(){P.classList.add("show"),v&&(v.style.display="none"),E&&(E.style.display="none"),B&&(B.style.display="none"),U=null}),wireModal(P,D),m?.addEventListener("click",async function(){m.disabled=!0,m.innerHTML='<span class="brand-spinner"></span> Exporting...';try{var e=await fetch("/api/v1/backup/export"),s=await e.json();s.browserState=L();var n=new Blob([JSON.stringify(s,null,2)],{type:"application/json"}),i=URL.createObjectURL(n),a=document.createElement("a");a.href=i,a.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i);var o=Object.keys(s.browserState).length,l=s.themes?Object.keys(s.themes).length:0;v.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+o+" browser settings"+(l?" + "+l+" themes":""),v.style.display="block",v.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",v.style.border="1px solid var(--ok-fg)"}catch(k){v.innerHTML="\u274C Export failed: "+escapeHtml(k.message),v.style.display="block",v.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",v.style.border="1px solid var(--bad-fg)"}m.disabled=!1,m.innerHTML="\u2B07\uFE0F Download Full Backup"}),T?.addEventListener("click",function(){w.click()}),w?.addEventListener("change",async function(e){var s=e.target.files[0];if(s){B.textContent="\u{1F4C4} "+s.name,B.style.display="block",v.style.display="none";try{var n=await s.text(),i=JSON.parse(n);if(S(i)){U=i;var a='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(i.version)+")</div>";a+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',i.services?.length&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4CB} '+i.services.length+" services</span>"),i.customApps?.length&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4E6} '+i.customApps.length+" custom apps</span>"),i.theme&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(i.theme)+"</span>"),i.userThemes&&(a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} '+Object.keys(i.userThemes).length+" custom themes</span>"),a+="</div>",H.innerHTML=a,E.style.display="block";return}var o=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),l=await o.json();if(l.success){U=i;var a='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(i.exportedAt).toLocaleString()+" (v"+escapeHtml(i.version)+")</div>";a+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',a+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var k in l.preview.files){var I=l.preview.files[k],j=I.action==="create"?"\u{1F195}":"\u{1F4DD}";a+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+j+" "+escapeHtml(I.description)+"</span>"}a+="</div>",l.preview.serviceCount&&(a+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+l.preview.serviceCount+" services</div>"),l.preview.themeCount&&(a+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+l.preview.themeCount+" custom themes</div>"),l.preview.browserStateCount&&(a+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',a+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+l.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),H.innerHTML=a,E.style.display="block"}else v.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(l.error),v.style.display="block",v.style.background="color-mix(in srgb, #f39c12 15%, transparent)",v.style.border="1px solid #f39c12",E.style.display="none"}catch(_){v.innerHTML="\u274CLine truncated
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var o=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),r=await o.json();r.success?(showNotification(e+" restored to "+t,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(r.error||"Unknown"),"error")}catch(a){showNotification("Restore error: "+a.message,"error")}}})(),(function(){injectModal("stats-modal",`<div id="stats-modal" class="weather-modal"> This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var n=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(s),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),i=await n.json();i.success?(showNotification(e+" restored to "+s,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(i.error||"Unknown"),"error")}catch(a){showNotification("Restore error: "+a.message,"error")}}})(),(function(){injectModal("stats-modal",`<div id="stats-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;"> <div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u{1F4CA} Resource Monitor</h3> <h3>\u{1F4CA} Resource Monitor</h3>
<p class="modal-subtitle"> <p class="modal-subtitle">
@@ -1209,10 +1196,10 @@ This will replace current configuration, credentials, and data. Containers will
<button id="stats-cancel">Close</button> <button id="stats-cancel">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("stats-modal"),C=document.getElementById("container-stats-btn"),O=document.getElementById("stats-cancel"),E=document.getElementById("stats-refresh-btn"),M=document.getElementById("stats-auto-refresh"),R=document.getElementById("stats-container"),P=document.getElementById("stats-aggregated-container"),A=document.getElementById("stats-alerts-container"),p=document.getElementById("stats-last-update");let T=null,x=null;function $(l){if(l===0||!l)return"0 B";const w=1024,m=["B","KB","MB","GB"],n=Math.floor(Math.log(l)/Math.log(w));return parseFloat((l/Math.pow(w,n)).toFixed(1))+" "+m[n]}function k(l){return l<30?"#2ecc71":l<70?"#f39c12":"#e74c3c"}function H(l){return l<50?"#2ecc71":l<80?"#f39c12":"#e74c3c"}async function L(){try{let l=null,w=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(l=e.stats,w=!0,x=e.stats)}catch{}if(!w){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){l={};for(const t of e.stats)l[t.name]={name:t.name,current:{cpu:t.cpu,memory:{percent:t.memory.percent,usage:t.memory.used,limit:t.memory.limit,usageMB:Math.round(t.memory.used/1048576),limitMB:Math.round(t.memory.limit/1048576)},network:{rxBytes:t.network.rx,txBytes:t.network.tx,rxMB:(t.network.rx/1048576).toFixed(1),txMB:(t.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:t.status};x=l}}if(!l||Object.keys(l).length===0){R.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">No running containers found</div>';return}let m='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[n,e]of Object.entries(l)){const t=e.current||e,o=t.cpu?.percent||0,r=t.memory?.percent||0,a=k(o),s=H(r),d=t.memory?.usage||t.memory?.used||0,S=t.memory?.limit||0,h=t.network?.rxBytes||t.network?.rx||0,U=t.network?.txBytes||t.network?.tx||0,_=e.aggregated;m+=` </div>`);const h=document.getElementById("stats-modal"),L=document.getElementById("container-stats-btn"),R=document.getElementById("stats-cancel"),S=document.getElementById("stats-refresh-btn"),$=document.getElementById("stats-auto-refresh"),P=document.getElementById("stats-container"),N=document.getElementById("stats-aggregated-container"),D=document.getElementById("stats-alerts-container"),m=document.getElementById("stats-last-update");let T=null,w=null;function B(d){if(d===0||!d)return"0 B";const x=1024,y=["B","KB","MB","GB"],t=Math.floor(Math.log(d)/Math.log(x));return parseFloat((d/Math.pow(x,t)).toFixed(1))+" "+y[t]}function E(d){return d<30?"#2ecc71":d<70?"#f39c12":"#e74c3c"}function H(d){return d<50?"#2ecc71":d<80?"#f39c12":"#e74c3c"}async function C(){try{let d=null,x=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(d=e.stats,x=!0,w=e.stats)}catch{}if(!x){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){d={};for(const s of e.stats)d[s.name]={name:s.name,current:{cpu:s.cpu,memory:{percent:s.memory.percent,usage:s.memory.used,limit:s.memory.limit,usageMB:Math.round(s.memory.used/1048576),limitMB:Math.round(s.memory.limit/1048576)},network:{rxBytes:s.network.rx,txBytes:s.network.tx,rxMB:(s.network.rx/1048576).toFixed(1),txMB:(s.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:s.status};w=d}}if(!d||Object.keys(d).length===0){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">No running containers found</div>';return}let y='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[t,e]of Object.entries(d)){const s=e.current||e,n=s.cpu?.percent||0,i=s.memory?.percent||0,a=E(n),o=H(i),l=s.memory?.usage||s.memory?.used||0,k=s.memory?.limit||0,I=s.network?.rxBytes||s.network?.rx||0,j=s.network?.txBytes||s.network?.tx||0,_=e.aggregated;y+=`
<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);"> <div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 10px;"> <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 10px;">
<span style="font-weight: 600; flex: 1;">${e.name||n}</span> <span style="font-weight: 600; flex: 1;">${e.name||t}</span>
${_?`<span style="font-size: 0.65rem; color: var(--muted); padding: 2px 6px; background: color-mix(in srgb, var(--accent) 10%, transparent); border-radius: 4px;">avg ${_.cpu?.avg?.toFixed(0)||0}% cpu</span>`:""} ${_?`<span style="font-size: 0.65rem; color: var(--muted); padding: 2px 6px; background: color-mix(in srgb, var(--accent) 10%, transparent); border-radius: 4px;">avg ${_.cpu?.avg?.toFixed(0)||0}% cpu</span>`:""}
<span style="font-size: 0.75rem; color: var(--muted); background: var(--base); padding: 2px 8px; border-radius: 4px;">${e.status||"running"}</span> <span style="font-size: 0.75rem; color: var(--muted); background: var(--base); padding: 2px 8px; border-radius: 4px;">${e.status||"running"}</span>
</div> </div>
@@ -1221,32 +1208,32 @@ This will replace current configuration, credentials, and data. Containers will
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">CPU</div> <div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">CPU</div>
<div style="display: flex; align-items: center; gap: 8px;"> <div style="display: flex; align-items: center; gap: 8px;">
<div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;"> <div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${Math.min(o,100)}%; background: ${a}; border-radius: 3px; transition: width 0.3s;"></div> <div style="height: 100%; width: ${Math.min(n,100)}%; background: ${a}; border-radius: 3px; transition: width 0.3s;"></div>
</div> </div>
<span style="font-size: 0.8rem; font-weight: 500; color: ${a}; min-width: 45px; text-align: right;">${o.toFixed(1)}%</span> <span style="font-size: 0.8rem; font-weight: 500; color: ${a}; min-width: 45px; text-align: right;">${n.toFixed(1)}%</span>
</div> </div>
</div> </div>
<div> <div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Memory</div> <div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Memory</div>
<div style="display: flex; align-items: center; gap: 8px;"> <div style="display: flex; align-items: center; gap: 8px;">
<div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;"> <div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${Math.min(r,100)}%; background: ${s}; border-radius: 3px; transition: width 0.3s;"></div> <div style="height: 100%; width: ${Math.min(i,100)}%; background: ${o}; border-radius: 3px; transition: width 0.3s;"></div>
</div> </div>
<span style="font-size: 0.8rem; font-weight: 500; color: ${s}; min-width: 45px; text-align: right;">${r.toFixed(1)}%</span> <span style="font-size: 0.8rem; font-weight: 500; color: ${o}; min-width: 45px; text-align: right;">${i.toFixed(1)}%</span>
</div> </div>
<div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${$(d)} / ${$(S)}</div> <div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${B(l)} / ${B(k)}</div>
</div> </div>
<div> <div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Network</div> <div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Network</div>
<div style="font-size: 0.8rem;"> <div style="font-size: 0.8rem;">
<span style="color: #3498db;">\u2193 ${$(h)}</span> <span style="color: #3498db;">\u2193 ${B(I)}</span>
<span style="color: var(--muted); margin: 0 4px;">/</span> <span style="color: var(--muted); margin: 0 4px;">/</span>
<span style="color: #e74c3c;">\u2191 ${$(U)}</span> <span style="color: #e74c3c;">\u2191 ${B(j)}</span>
</div> </div>
</div> </div>
</div> </div>
</div>`}m+="</div>",R.innerHTML=m,p.textContent="Updated: "+new Date().toLocaleTimeString()}catch(l){R.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(l.message)}</div>`}}async function u(){if(!P)return;const l=x;if(!l||Object.keys(l).length===0){P.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4C8}</span>No monitoring data available. Open the Live Stats tab first.</div>';return}let w='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[m,n]of Object.entries(l)){const e=n.aggregated;e&&(w+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);"> </div>`}y+="</div>",P.innerHTML=y,m.textContent="Updated: "+new Date().toLocaleTimeString()}catch(d){P.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(d.message)}</div>`}}async function v(){if(!N)return;const d=w;if(!d||Object.keys(d).length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4C8}</span>No monitoring data available. Open the Live Stats tab first.</div>';return}let x='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[y,t]of Object.entries(d)){const e=t.aggregated;e&&(x+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="font-weight: 600; margin-bottom: 10px;">${n.name||m}</div> <div style="font-weight: 600; margin-bottom: 10px;">${t.name||y}</div>
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;"> <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;">
<div class="stat-mini-card"><span class="stat-val">${e.cpu?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg CPU</span></div> <div class="stat-mini-card"><span class="stat-val">${e.cpu?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${e.cpu?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max CPU</span></div> <div class="stat-mini-card"><span class="stat-val">${e.cpu?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max CPU</span></div>
@@ -1254,27 +1241,27 @@ This will replace current configuration, credentials, and data. Containers will
<div class="stat-mini-card"><span class="stat-val">${e.memory?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max Mem</span></div> <div class="stat-mini-card"><span class="stat-val">${e.memory?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max Mem</span></div>
</div> </div>
${e.dataPoints?`<div style="font-size: 0.7rem; color: var(--muted); margin-top: 6px;">${e.dataPoints} data points over ${e.timeRange||24}h</div>`:""} ${e.dataPoints?`<div style="font-size: 0.7rem; color: var(--muted); margin-top: 6px;">${e.dataPoints} data points over ${e.timeRange||24}h</div>`:""}
</div>`)}w+="</div>",P.innerHTML=w}async function j(){if(!A)return;A.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const l=x;if(!l||Object.keys(l).length===0){A.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let w=!1;try{w=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{w=!1}let m=[];try{const s=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();s.success&&(m=s.history||[])}catch{}let n={};try{const s=await(await fetch("/api/v1/monitoring/alerts/config")).json();s.success&&(n=s.configs||{})}catch{}const t=Object.entries(l).map(([a,s])=>{const d=n[a]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return` </div>`)}x+="</div>",N.innerHTML=x}async function O(){if(!D)return;D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const d=w;if(!d||Object.keys(d).length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let x=!1;try{x=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{x=!1}let y=[];try{const o=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();o.success&&(y=o.history||[])}catch{}let t={};try{const o=await(await fetch("/api/v1/monitoring/alerts/config")).json();o.success&&(t=o.configs||{})}catch{}const s=Object.entries(d).map(([a,o])=>{const l=t[a]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return`
<tr data-container="${a}"> <tr data-container="${a}">
<td style="font-weight: 600; padding: 8px;">${s.name||a}</td> <td style="font-weight: 600; padding: 8px;">${o.name||a}</td>
<td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${d.cpuThreshold??80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${w?"":"disabled"} /></td> <td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${l.cpuThreshold??80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${x?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${d.memoryThreshold??90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${w?"":"disabled"} /></td> <td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${l.memoryThreshold??90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${x?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${d.diskIOThreshold??50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${w?"":"disabled"} /></td> <td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${l.diskIOThreshold??50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${x?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${d.autoRestart?"checked":""} ${w?"":"disabled"} /></td> <td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${l.autoRestart?"checked":""} ${x?"":"disabled"} /></td>
<td style="padding: 4px 8px;"> <td style="padding: 4px 8px;">
<button class="alert-test-btn btn-xs" data-container="${a}" data-name="${s.name||a}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button> <button class="alert-test-btn btn-xs" data-container="${a}" data-name="${o.name||a}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button>
</td> </td>
</tr> </tr>
`}).join(""),o=m.map(a=>{const s=new Date(a.timestamp).toLocaleString(),d=a.notified?"\u2713":"\u2014";return` `}).join(""),n=y.map(a=>{const o=new Date(a.timestamp).toLocaleString(),l=a.notified?"\u2713":"\u2014";return`
<tr> <tr>
<td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${s}</td> <td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${o}</td>
<td style="padding: 6px 8px; font-weight: 500;">${a.containerName||a.containerId}</td> <td style="padding: 6px 8px; font-weight: 500;">${a.containerName||a.containerId}</td>
<td style="padding: 6px 8px; text-transform: capitalize;">${a.metric||a.type}</td> <td style="padding: 6px 8px; text-transform: capitalize;">${a.metric||a.type}</td>
<td style="padding: 6px 8px;">${typeof a.value=="number"?a.value.toFixed(1):a.value}${a.metric==="disk"?" MB/s":"%"}</td> <td style="padding: 6px 8px;">${typeof a.value=="number"?a.value.toFixed(1):a.value}${a.metric==="disk"?" MB/s":"%"}</td>
<td style="padding: 6px 8px; text-align: center;">${d}</td> <td style="padding: 6px 8px; text-align: center;">${l}</td>
<td style="padding: 6px 8px; font-size: 0.75rem; color: ${a.autoRestartTriggered?"#f39c12":"var(--muted)"};">${a.autoRestartTriggered?"\u21BB":""}</td> <td style="padding: 6px 8px; font-size: 0.75rem; color: ${a.autoRestartTriggered?"#f39c12":"var(--muted)"};">${a.autoRestartTriggered?"\u21BB":""}</td>
</tr> </tr>
`}).join(""),r=w?` `}).join(""),i=x?`
<div style="margin-bottom: 20px;"> <div style="margin-bottom: 20px;">
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;"> <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
<h4 style="margin: 0; font-size: 0.9rem;">\u2699\uFE0F Alert Configuration</h4> <h4 style="margin: 0; font-size: 0.9rem;">\u2699\uFE0F Alert Configuration</h4>
@@ -1292,7 +1279,7 @@ This will replace current configuration, credentials, and data. Containers will
<th style="padding: 6px 8px;"></th> <th style="padding: 6px 8px;"></th>
</tr> </tr>
</thead> </thead>
<tbody>${t}</tbody> <tbody>${s}</tbody>
</table> </table>
</div> </div>
<div style="margin-top: 12px; display: flex; justify-content: flex-end;"> <div style="margin-top: 12px; display: flex; justify-content: flex-end;">
@@ -1305,11 +1292,11 @@ This will replace current configuration, credentials, and data. Containers will
<p style="margin: 6px 0 0; font-size: 0.75rem; color: var(--muted);">Upgrade to configure resource alert thresholds per container.</p> <p style="margin: 6px 0 0; font-size: 0.75rem; color: var(--muted);">Upgrade to configure resource alert thresholds per container.</p>
<button id="upgrade-for-alerts" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; background: #f1c40f; color: #000; border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Upgrade Now</button> <button id="upgrade-for-alerts" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; background: #f1c40f; color: #000; border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Upgrade Now</button>
</div> </div>
`;A.innerHTML=` `;D.innerHTML=`
${r} ${i}
<div> <div>
<h4 style="margin: 0 0 10px; font-size: 0.9rem;">\u{1F4CB} Recent Alerts</h4> <h4 style="margin: 0 0 10px; font-size: 0.9rem;">\u{1F4CB} Recent Alerts</h4>
${o?` ${n?`
<div style="overflow-x: auto;"> <div style="overflow-x: auto;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.8rem;"> <table style="width: 100%; border-collapse: collapse; font-size: 0.8rem;">
<thead> <thead>
@@ -1322,26 +1309,26 @@ This will replace current configuration, credentials, and data. Containers will
<th style="padding: 6px 8px;"></th> <th style="padding: 6px 8px;"></th>
</tr> </tr>
</thead> </thead>
<tbody>${o}</tbody> <tbody>${n}</tbody>
</table> </table>
</div> </div>
`:'<div style="color: var(--muted); text-align: center; padding: 20px;">No alerts recorded yet.</div>'} `:'<div style="color: var(--muted); text-align: center; padding: 20px;">No alerts recorded yet.</div>'}
</div> </div>
`,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const a={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(s=>{const d=s.dataset.container;a[d]={cpuThreshold:parseInt(s.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(s.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(s.querySelector(".alert-disk")?.value)||50,autoRestart:!!s.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const d=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:a})})).json(),S=document.getElementById("save-all-alerts");S.textContent=d.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{S.textContent="Save All"},2e3)}catch{const d=document.getElementById("save-all-alerts");d.textContent="\u274C Error",setTimeout(()=>{d.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",a=>{a.preventDefault(),y.classList.remove("show"),N(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(a=>{a.addEventListener("click",async()=>{const s=a.textContent;a.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${a.dataset.container}/test`,{method:"POST"}),a.textContent="\u2705",showNotification("Test alert sent for "+a.dataset.name,"success",3e3)}catch{a.textContent="\u274C"}setTimeout(()=>{a.textContent=s},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{y.classList.remove("show"),N(),typeof openLicenseModal=="function"&&openLicenseModal()})}function v(){T&&clearInterval(T),M?.checked&&(T=setInterval(L,DC.POLL.STATS))}function N(){T&&(clearInterval(T),T=null)}C?.addEventListener("click",()=>{y.classList.add("show"),L(),v()}),O?.addEventListener("click",()=>{y.classList.remove("show"),N()}),y?.addEventListener("click",l=>{l.target===y&&(y.classList.remove("show"),N())}),E?.addEventListener("click",L),M?.addEventListener("change",()=>{M.checked?v():N()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",u),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",j);const g=document.getElementById("stats-history-container"),D=document.getElementById("stats-history-container-area"),B=document.querySelectorAll(".stats-range-btn");let f="1h";function I(l){switch(l){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function b(l){return l==="raw"?"live (10s samples)":l==="hourly"?"hourly average":l==="daily"?"daily average":l}function z(l,w,m,n,e){if(!l||l.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(n)}</div>`;const t=l.map(w).filter(W=>W!=null);if(t.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(n)}</div>`;const o=Math.max(...t,1),r=Math.min(...t,0),a=o-r||1,s=600,d=80,S=4,h=(s-S*2)/Math.max(t.length-1,1),U=t.map((W,J)=>{const X=S+J*h,Q=d-S-(W-r)/a*(d-S*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),_=t[t.length-1],F=t.reduce((W,J)=>W+J,0)/t.length;return` `,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const a={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(o=>{const l=o.dataset.container;a[l]={cpuThreshold:parseInt(o.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(o.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(o.querySelector(".alert-disk")?.value)||50,autoRestart:!!o.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const l=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:a})})).json(),k=document.getElementById("save-all-alerts");k.textContent=l.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{k.textContent="Save All"},2e3)}catch{const l=document.getElementById("save-all-alerts");l.textContent="\u274C Error",setTimeout(()=>{l.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",a=>{a.preventDefault(),h.classList.remove("show"),z(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(a=>{a.addEventListener("click",async()=>{const o=a.textContent;a.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${a.dataset.container}/test`,{method:"POST"}),a.textContent="\u2705",showNotification("Test alert sent for "+a.dataset.name,"success",3e3)}catch{a.textContent="\u274C"}setTimeout(()=>{a.textContent=o},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{h.classList.remove("show"),z(),typeof openLicenseModal=="function"&&openLicenseModal()})}function f(){T&&clearInterval(T),$?.checked&&(T=setInterval(C,DC.POLL.STATS))}function z(){T&&(clearInterval(T),T=null)}L?.addEventListener("click",()=>{h.classList.add("show"),C(),f()}),R?.addEventListener("click",()=>{h.classList.remove("show"),z()}),h?.addEventListener("click",d=>{d.target===h&&(h.classList.remove("show"),z())}),S?.addEventListener("click",C),$?.addEventListener("change",()=>{$.checked?f():z()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",v),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",O);const A=document.getElementById("stats-history-container"),U=document.getElementById("stats-history-container-area"),p=document.querySelectorAll(".stats-range-btn");let u="1h";function b(d){switch(d){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function g(d){return d==="raw"?"live (10s samples)":d==="hourly"?"hourly average":d==="daily"?"daily average":d}function M(d,x,y,t,e){if(!d||d.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(t)}</div>`;const s=d.map(x).filter(q=>q!=null);if(s.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(t)}</div>`;const n=Math.max(...s,1),i=Math.min(...s,0),a=n-i||1,o=600,l=80,k=4,I=(o-k*2)/Math.max(s.length-1,1),j=s.map((q,G)=>{const X=k+G*I,Q=l-k-(q-i)/a*(l-k*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),_=s[s.length-1],F=s.reduce((q,G)=>q+G,0)/s.length;return`
<div style="margin-bottom: 14px;"> <div style="margin-bottom: 14px;">
<div style="display: flex; align-items: baseline; gap: 12px; margin-bottom: 4px;"> <div style="display: flex; align-items: baseline; gap: 12px; margin-bottom: 4px;">
<span style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(n)}</span> <span style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(t)}</span>
<span style="font-size: 0.75rem; color: var(--muted);">last ${_.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${o.toFixed(1)}${e}</span> <span style="font-size: 0.75rem; color: var(--muted);">last ${_.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${n.toFixed(1)}${e}</span>
</div> </div>
<svg viewBox="0 0 ${s} ${d}" preserveAspectRatio="none" style="width: 100%; height: ${d}px; background: var(--base); border-radius: 4px;"> <svg viewBox="0 0 ${o} ${l}" preserveAspectRatio="none" style="width: 100%; height: ${l}px; background: var(--base); border-radius: 4px;">
<polyline fill="none" stroke="${m}" stroke-width="1.5" points="${U}" /> <polyline fill="none" stroke="${y}" stroke-width="1.5" points="${j}" />
</svg> </svg>
</div> </div>
`}function i(){if(!g)return;const l=x||{},w=g.value,m=Object.entries(l);if(m.length===0){g.innerHTML='<option value="">No containers</option>';return}g.innerHTML=m.map(([n,e])=>`<option value="${escapeHtml(n)}">${escapeHtml(e.name||n)}</option>`).join(""),w&&l[w]&&(g.value=w)}async function c(){if(!D||!g)return;const l=g.value;if(!l){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No container selected.</div>';return}const w=Date.now(),m=w-I(f);D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading history...</div>';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(l)}?startTime=${m}&endTime=${w}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const t=e.samples||[],o=e.tier||"raw";if(t.length===0){D.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No data for the last ${f}. Tier: ${b(o)}.</div>`;return}const r=o==="raw",a=r?U=>U.cpu?.percent:U=>U.cpu?.avg,s=r?U=>U.memory?.percent:U=>U.memory?.avgPercent,d=r?U=>U.network?.rxMB||0:U=>U.network?.rxMB||0,S=r?U=>U.network?.txMB||0:U=>U.network?.txMB||0;let h=` `}function r(){if(!A)return;const d=w||{},x=A.value,y=Object.entries(d);if(y.length===0){A.innerHTML='<option value="">No containers</option>';return}A.innerHTML=y.map(([t,e])=>`<option value="${escapeHtml(t)}">${escapeHtml(e.name||t)}</option>`).join(""),x&&d[x]&&(A.value=x)}async function c(){if(!U||!A)return;const d=A.value;if(!d){U.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No container selected.</div>';return}const x=Date.now(),y=x-b(u);U.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading history...</div>';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${y}&endTime=${x}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const s=e.samples||[],n=e.tier||"raw";if(s.length===0){U.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No data for the last ${u}. Tier: ${g(n)}.</div>`;return}const i=n==="raw",a=i?j=>j.cpu?.percent:j=>j.cpu?.avg,o=i?j=>j.memory?.percent:j=>j.memory?.avgPercent,l=i?j=>j.network?.rxMB||0:j=>j.network?.rxMB||0,k=i?j=>j.network?.txMB||0:j=>j.network?.txMB||0;let I=`
<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;"> <div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">
${t.length} samples \xB7 ${escapeHtml(b(o))} \xB7 ${new Date(m).toLocaleString()} \u2192 ${new Date(w).toLocaleString()} ${s.length} samples \xB7 ${escapeHtml(g(n))} \xB7 ${new Date(y).toLocaleString()} \u2192 ${new Date(x).toLocaleString()}
</div> </div>
`;h+=z(t,a,"#2ecc71","CPU","%"),h+=z(t,s,"#3498db","Memory","%"),h+=z(t,d,"#9b59b6","Network RX"," MB"),h+=z(t,S,"#e67e22","Network TX"," MB"),D.innerHTML=h}catch(n){D.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u26A0\uFE0F</span>Failed to load history: ${escapeHtml(n.message)}</div>`}}B.forEach(l=>{l.addEventListener("click",()=>{B.forEach(w=>w.classList.remove("active")),l.classList.add("active"),f=l.dataset.range,c()})}),g?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{i(),c()})})(),(function(){injectModal("health-modal",`<div id="health-modal" class="weather-modal"> `;I+=M(s,a,"#2ecc71","CPU","%"),I+=M(s,o,"#3498db","Memory","%"),I+=M(s,l,"#9b59b6","Network RX"," MB"),I+=M(s,k,"#e67e22","Network TX"," MB"),U.innerHTML=I}catch(t){U.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u26A0\uFE0F</span>Failed to load history: ${escapeHtml(t.message)}</div>`}}p.forEach(d=>{d.addEventListener("click",()=>{p.forEach(x=>x.classList.remove("active")),d.classList.add("active"),u=d.dataset.range,c()})}),A?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{r(),c()})})(),(function(){injectModal("health-modal",`<div id="health-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 800px; max-width: 1000px;"> <div class="weather-modal-content" style="min-width: 800px; max-width: 1000px;">
<h3>\u{1F3E5} Health Check Dashboard</h3> <h3>\u{1F3E5} Health Check Dashboard</h3>
<p class="modal-subtitle"> <p class="modal-subtitle">
@@ -1378,7 +1365,7 @@ This will replace current configuration, credentials, and data. Containers will
<div id="health-global-settings" style="margin-top: 16px; padding: 16px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card-base);"> <div id="health-global-settings" style="margin-top: 16px; padding: 16px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card-base);">
<h4 style="margin: 0 0 4px;">\u{1F30D} Global Settings</h4> <h4 style="margin: 0 0 4px;">\u{1F30D} Global Settings</h4>
<p class="text-muted-sm" style="margin: 0 0 12px;">Applies to all health checks. Settings are stored locally in this browser.</p> <p class="text-muted-sm" style="margin: 0 0 12px;">Applies to all health checks. Settings are stored locally in this browser.</p>
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px;"> <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
<div> <div>
<label class="text-muted-sm">Data Retention (days)</label> <label class="text-muted-sm">Data Retention (days)</label>
<input type="number" id="health-setting-retention" value="30" min="1" max="3650" class="form-input" /> <input type="number" id="health-setting-retention" value="30" min="1" max="3650" class="form-input" />
@@ -1389,6 +1376,11 @@ This will replace current configuration, credentials, and data. Containers will
<input type="number" id="health-setting-interval" value="30" min="5" max="3600" class="form-input" /> <input type="number" id="health-setting-interval" value="30" min="5" max="3600" class="form-input" />
<div style="font-size: 0.72rem; color: var(--muted); margin-top: 2px;">How often each service is checked.</div> <div style="font-size: 0.72rem; color: var(--muted); margin-top: 2px;">How often each service is checked.</div>
</div> </div>
<div>
<label class="text-muted-sm">Max Entries Per Service</label>
<input type="number" id="health-setting-max-entries" value="500" min="10" max="100000" class="form-input" />
<div style="font-size: 0.72rem; color: var(--muted); margin-top: 2px;">Cap on stored history records per service.</div>
</div>
<div> <div>
<label class="text-muted-sm">Disk-Usage Warning (%)</label> <label class="text-muted-sm">Disk-Usage Warning (%)</label>
<input type="number" id="health-setting-disk-threshold" value="80" min="50" max="99" class="form-input" /> <input type="number" id="health-setting-disk-threshold" value="80" min="50" max="99" class="form-input" />
@@ -1455,24 +1447,24 @@ This will replace current configuration, credentials, and data. Containers will
<button id="health-cancel">Close</button> <button id="health-cancel">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("health-modal"),C=document.getElementById("health-check-btn"),O=document.getElementById("health-cancel"),E=document.getElementById("health-refresh-btn"),M=document.getElementById("health-status-container"),R=document.getElementById("health-incidents-container"),P=document.getElementById("health-config-container"),A=document.getElementById("health-last-update"),p=document.getElementById("health-add-btn"),T=document.getElementById("health-config-form"),x=document.getElementById("health-form-title"),$=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save"),H="dashcaddy-health-settings",L={retentionDays:30,pollingInterval:30,diskUsageThreshold:80},u=document.getElementById("health-global-save"),j=document.getElementById("health-global-reset"),v=document.getElementById("health-global-status"),N=document.getElementById("health-setting-retention"),g=document.getElementById("health-setting-interval"),D=document.getElementById("health-setting-disk-threshold");function B(){try{const t=safeGet(H),o=t?JSON.parse(t):{};return Object.assign({},L,o)}catch{return Object.assign({},L)}}function f(){const t=B();N&&(N.value=t.retentionDays),g&&(g.value=t.pollingInterval),D&&(D.value=t.diskUsageThreshold)}function I(){const t={retentionDays:Math.max(1,Math.min(3650,parseInt(N?.value)||L.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(g?.value)||L.pollingInterval)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(D?.value)||L.diskUsageThreshold))};try{safeSet(H,JSON.stringify(t)),f(),v&&(v.textContent="Saved \u2713",v.style.color="var(--ok-fg)",setTimeout(()=>{v&&(v.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(o){v&&(v.textContent="Save failed",v.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+o.message,"error")}}function b(){try{safeSet(H,JSON.stringify(L))}catch{}f(),v&&(v.textContent="Reset to defaults \u2713",v.style.color="var(--ok-fg)",setTimeout(()=>{v&&(v.textContent="")},2500))}f(),u?.addEventListener("click",I),j?.addEventListener("click",b);let z=null;function i(t){return t>=99.9?"var(--ok-fg)":t>=95?"#f39c12":"var(--bad-fg)"}function c(t){const o={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`<span style="padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: ${o[t]||"var(--muted)"}20; color: ${o[t]||"var(--muted)"};">${t}</span>`}async function l(){try{const o=await(await fetch("/api/v1/health-checks/status")).json();if(!o.success||!o.status||Object.keys(o.status).length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F3E5}</span>No health checks configured. Go to the Configure tab to add services.</div>';return}const r=Object.values(o.status);let a='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';a+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',a+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',a+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',a+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const s of r){const d=s.status==="up",S=d?"var(--dot-ok)":"var(--dot-bad)",h=s.uptime?.["24h"]??"-",U=s.uptime?.["7d"]??"-",_=s.avgResponseTime!=null?Math.round(s.avgResponseTime)+"ms":"-",F=s.timestamp?timeAgo(s.timestamp):"-";a+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(s.serviceId)}">`,a+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(s.name||s.serviceId)}</td>`,a+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${S}; margin-right: 6px;"></span>${d?"Up":"Down"}</td>`,a+=`<td style="padding: 8px; color: ${typeof h=="number"?i(h):"var(--muted)"};">${typeof h=="number"?h.toFixed(1)+"%":h}</td>`,a+=`<td style="padding: 8px; color: ${typeof U=="number"?i(U):"var(--muted)"};">${typeof U=="number"?U.toFixed(1)+"%":U}</td>`,a+=`<td style="padding: 8px;">${_}</td>`,a+=`<td style="padding: 8px; color: var(--muted);">${F}</td>`,a+="</tr>",a+=`<tr id="health-detail-${escapeHtml(s.serviceId)}" style="display: none;"><td colspan="6" style="padding: 12px; background: var(--bg); border-bottom: 1px solid var(--border);"><div class="panel-empty"><span class="brand-spinner"></span> Loading details...</div></td></tr>`}a+="</table>",M.innerHTML=a,A.textContent="Updated "+new Date().toLocaleTimeString(),M.querySelectorAll("tr[data-health-id]").forEach(s=>{s.addEventListener("click",async()=>{const d=s.dataset.healthId,S=document.getElementById("health-detail-"+d);if(S){if(S.style.display!=="none"){S.style.display="none";return}S.style.display="";try{const U=await(await fetch(`/api/v1/health-checks/${d}/Line truncated </div>`);const h=document.getElementById("health-modal"),L=document.getElementById("health-check-btn"),R=document.getElementById("health-cancel"),S=document.getElementById("health-refresh-btn"),$=document.getElementById("health-status-container"),P=document.getElementById("health-incidents-container"),N=document.getElementById("health-config-container"),D=document.getElementById("health-last-update"),m=document.getElementById("health-add-btn"),T=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),B=document.getElementById("health-form-cancel"),E=document.getElementById("health-form-save"),H="dashcaddy-health-settings",C={retentionDays:30,pollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},v=document.getElementById("health-global-save"),O=document.getElementById("health-global-reset"),f=document.getElementById("health-global-status"),z=document.getElementById("health-setting-retention"),A=document.getElementById("health-setting-interval"),U=document.getElementById("health-setting-max-entries"),p=document.getElementById("health-setting-disk-threshold");function u(){try{const n=safeGet(H),i=n?JSON.parse(n):{};return Object.assign({},C,i)}catch{return Object.assign({},C)}}function b(){const n=u();z&&(z.value=n.retentionDays),A&&(A.value=n.pollingInterval),U&&(U.value=n.maxEntriesPerService),p&&(p.value=n.diskUsageThreshold)}function g(){const n={retentionDays:Math.max(1,Math.min(3650,parseInt(z?.value)||C.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(A?.value)||C.pollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(U?.value)||C.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(p?.value)||C.diskUsageThreshold))};try{safeSet(H,JSON.stringify(n)),b(),f&&(f.textContent="Saved \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(i){f&&(f.textContent="Save failed",f.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+i.message,"error")}}function M(){try{safeSet(H,JSON.stringify(C))}catch{}b(),f&&(f.textContent="Reset to defaults \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500))}b(),v?.addEventListener("click",g),O?.addEventListener("click",M);let r=null;function c(n){return n>=99.9?"var(--ok-fg)":n>=95?"#f39c12":"var(--bad-fg)"}function d(n){const i={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`<span style="padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: ${i[n]||"var(--muted)"}20; color: ${i[n]||"var(--muted)"};">${n}</span>`}async function x(){try{const i=await(await fetch("/api/v1/health-checks/status")).json();if(!i.success||!i.status||Object.keys(i.status).length===0){$.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F3E5}</span>No health checks configured. Go to the Configure tab to add services.</div>';return}const a=Object.values(i.status);let o='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';o+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',o+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',o+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',o+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const l of a){const k=l.status==="up",I=k?"var(--dot-ok)":"var(--dot-bad)",j=l.uptime?.["24h"]??"-",_=l.uptime?.["7d"]??"-",F=l.avgResponseTime!=null?Math.round(l.avgResponseTime)+"ms":"-",q=l.timestamp?timeAgo(l.timestamp):"-";o+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(l.serviceId)}">`,o+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(l.name||l.serviceId)}</td>`,o+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${I}; margin-right: 6px;"></span>${k?"Up":"Down"}</td>`,o+=`<td style="padding: 8px; color: ${typeof j=="number"?c(j):"var(--muted)"};">${typeof j=="number"?j.toFixed(1)+"%":j}</td>`,o+=`<td style="padding: 8px; color: ${typeof _=="number"?c(_):"var(--muted)"};">${typeof _=="number"?_.toFixed(1)+"%":_}</td>`,o+=`<td style="padding: 8px;">${F}</td>`,o+=`<td style="padding: 8px; color: var(--muted);">${q}</td>`,o+="</tr>",o+=`<tr id="health-detail-${escapeHtml(l.serviceId)}" style="display: none;"><td colspan="6" style="padding: 12px; background: var(--bg); border-bottom: 1px solid var(--border);"><div class="panel-empty"><span class="brand-spinner"></span> Loading details...</div></td></tr>`}o+="</table>",$.innerHTML=o,D.textContent="Updated "+new Date().toLocaleTimeString(),$.querySelectorAll("tr[data-health-id]").forEach(l=>{l.addEventListener("click",async()=>{const kLine truncated
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; font-size: 0.82rem;"> <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; font-size: 0.82rem;">
<div><span style="color: var(--muted);">Total Checks</span><br><strong>${_.totalChecks||0}</strong></div> <div><span style="color: var(--muted);">Total Checks</span><br><strong>${F.totalChecks||0}</strong></div>
<div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${i(_.uptime||0)};">${(_.uptime||0).toFixed(2)}%</strong></div> <div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${c(F.uptime||0)};">${(F.uptime||0).toFixed(2)}%</strong></div>
<div><span style="color: var(--muted);">Avg Response</span><br><strong>${Math.round(F.avg||0)}ms</strong></div> <div><span style="color: var(--muted);">Avg Response</span><br><strong>${Math.round(q.avg||0)}ms</strong></div>
<div><span style="color: var(--muted);">P95 / P99</span><br><strong>${Math.round(F.p95||0)}ms / ${Math.round(F.p99||0)}ms</strong></div> <div><span style="color: var(--muted);">P95 / P99</span><br><strong>${Math.round(q.p95||0)}ms / ${Math.round(q.p99||0)}ms</strong></div>
<div><span style="color: var(--muted);">Min Response</span><br><strong>${Math.round(F.min||0)}ms</strong></div> <div><span style="color: var(--muted);">Min Response</span><br><strong>${Math.round(q.min||0)}ms</strong></div>
<div><span style="color: var(--muted);">Max Response</span><br><strong>${Math.round(F.max||0)}ms</strong></div> <div><span style="color: var(--muted);">Max Response</span><br><strong>${Math.round(q.max||0)}ms</strong></div>
<div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${_.upChecks||0}</strong></div> <div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${F.upChecks||0}</strong></div>
<div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${_.downChecks||0}</strong></div> <div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${F.downChecks||0}</strong></div>
</div>`}else S.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(h){S.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(h.message)}</div>`}}})})}catch(t){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(t.message)}</div>`}}async function w(){try{const[t,o]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),r=await t.json(),a=await o.json();let s="";const d=r.success&&r.incidents?r.incidents:[];if(d.length>0){s+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+d.length+")</h4>";for(const h of d)s+=`<div style="padding: 10px 12px; margin-bottom: 8px; border: 1px solid var(--bad-fg)30; border-radius: 8px; background: var(--bad-bg);"> </div>`}else I.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(j){I.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(j.message)}</div>`}}})})}catch(n){$.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(n.message)}</div>`}}async function y(){try{const[n,i]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),a=await n.json(),o=await i.json();let l="";const k=a.success&&a.incidents?a.incidents:[];if(k.length>0){l+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+k.length+")</h4>";for(const j of k)l+=`<div style="padding: 10px 12px; margin-bottom: 8px; border: 1px solid var(--bad-fg)30; border-radius: 8px; background: var(--bad-bg);">
<div style="display: flex; justify-content: space-between; align-items: center;"> <div style="display: flex; justify-content: space-between; align-items: center;">
<span style="font-weight: 500;">${escapeHtml(h.serviceId)}</span> <span style="font-weight: 500;">${escapeHtml(j.serviceId)}</span>
<span>${c(h.severity)}</span> <span>${d(j.severity)}</span>
</div> </div>
<div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(h.message)}</div> <div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(j.message)}</div>
<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(h.createdAt)} \xB7 ${h.occurrences||1} occurrence(s)</div> <div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(j.createdAt)} \xB7 ${j.occurrences||1} occurrence(s)</div>
</div>`;s+="</div>"}else s+='<div style="padding: 12px; margin-bottom: 16px; border: 1px solid var(--ok-fg)30; border-radius: 8px; background: var(--ok-bg); text-align: center; color: var(--ok-fg); font-size: 0.9rem;">All services operational \u2014 no open incidents</div>';const S=a.success&&a.history?a.history:[];if(S.length>0){s+='<h4 style="margin: 0 0 8px; color: var(--muted);">Incident History</h4>',s+='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',s+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Service</th><th style="padding: 6px; text-align: left;">Type</th><th style="padding: 6px; text-align: left;">Severity</th><th style="padding: 6px; text-align: left;">Status</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">When</th></tr>';for(const h of S){const U=h.status==="resolved",_=U&&h.duration?h.duration<6e4?Math.round(h.duration/1e3)+"s":Math.round(h.duration/6e4)+"m":"-";s+='<tr style="border-bottom: 1px solid var(--border);">',s+=`<td style="padding: 6px;">${escapeHtml(h.serviceId)}</td>`,s+=`<td style="padding: 6px;">${escapeHtml(h.type)}</td>`,s+=`<td style="padding: 6px;">${c(h.severity)}</td>`,s+=`<td style="padding: 6px;"><span style="color: ${U?"var(--ok-fg)":"var(--bad-fg)"};">${h.status}</span></td>`,s+=`<td style="padding: 6px;">${_}</td>`,s+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(h.createdAt)}</td>`,s+="</tr>"}s+="</table>"}R.innerHTML=s||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(t){R.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(t.message)}</div>`}}async function m(){try{const o=await(await fetch("/api/v1/health-checks/status")).json(),r=o.success&&o.status?Object.values(o.status):[];if(r.length===0){P.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span>No health checks configured yet. Click "Add Health Check" below.</div>';return}let a='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';a+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Service</th><th style="padding: 8px; text-align: left;">Status</th><th style="padding: 8px; text-align: left;">SLA Target</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const s of r){const d=s.status==="up";a+='<tr style="border-bottom: 1px solid var(--border);">',a+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(s.name||s.serviceId)}</td>`,a+=`<td style="padding: 8px; color: ${d?"var(--ok-fg)":"var(--bad-fg)"};">${d?"Up":"Down"}</td>`,a+=`<td style="padding: 8px;">${s.sla?.target?s.sla.target+"%":"-"}</td>`,a+='<td style="padding: 8px; text-align: right;">',a+=`<button onclick="document.dispatchEvent(new CustomEvent('health-edit', {detail:'${escapeHtml(s.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`,a+=`<button onclick="document.dispatchEvent(new CustomEvent('health-delete', {detail:'${escapeHtml(s.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`,a+="</td></tr>"}a+="</table>",P.innerHTML=a}catch(t){P.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(t.message)}</div>`}}function n(t,o,r,a,s,d,S){z=t||null,x.textContent=t?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=t||"",document.getElementById("health-form-id").disabled=!!t,document.getElementById("health-form-name").value=o||"",document.getElementById("health-form-url").value=r||"",document.getElementById("health-form-timeout").value=a||1e4,document.getElementById("health-form-codes").value=s||"200",document.getElementById("health-form-sla").value=d||99.9,document.getElementById("health-form-slow").value=S||5e3,T.style.display="",p.style.display="none"}function e(){T.style.display="none",p.style.display="",z=null}p?.addEventListener("click",()=>n("","","",1e4,"200",99.9,5e3)),$?.addEventListener("click",e),k?.addEventListener("click",async()=>{const t=z||document.getElementById("health-form-id").value.trim();if(!t)return showNotification("Service ID is required","warning");const o=document.getElementById("health-form-url").value.trim();if(!o)return showNotification("URL is required","warning");const r=document.getElementById("health-form-codes").value.split(",").map(s=>parseInt(s.trim())).filter(Boolean),a={name:document.getElementById("health-form-name").value.trim()||t,url:o,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:r.length?r:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)|Line truncated </div>`;l+="</div>"}else l+='<div style="padding: 12px; margin-bottom: 16px; border: 1px solid var(--ok-fg)30; border-radius: 8px; background: var(--ok-bg); text-align: center; color: var(--ok-fg); font-size: 0.9rem;">All services operational \u2014 no open incidents</div>';const I=o.success&&o.history?o.history:[];if(I.length>0){l+='<h4 style="margin: 0 0 8px; color: var(--muted);">Incident History</h4>',l+='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',l+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Service</th><th style="padding: 6px; text-align: left;">Type</th><th style="padding: 6px; text-align: left;">Severity</th><th style="padding: 6px; text-align: left;">Status</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">When</th></tr>';for(const j of I){const _=j.status==="resolved",F=_&&j.duration?j.duration<6e4?Math.round(j.duration/1e3)+"s":Math.round(j.duration/6e4)+"m":"-";l+='<tr style="border-bottom: 1px solid var(--border);">',l+=`<td style="padding: 6px;">${escapeHtml(j.serviceId)}</td>`,l+=`<td style="padding: 6px;">${escapeHtml(j.type)}</td>`,l+=`<td style="padding: 6px;">${d(j.severity)}</td>`,l+=`<td style="padding: 6px;"><span style="color: ${_?"var(--ok-fg)":"var(--bad-fg)"};">${j.status}</span></td>`,l+=`<td style="padding: 6px;">${F}</td>`,l+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(j.createdAt)}</td>`,l+="</tr>"}l+="</table>"}P.innerHTML=l||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(n){P.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(n.message)}</div>`}}async function t(){try{const i=await(await fetch("/api/v1/health-checks/status")).json(),a=i.success&&i.status?Object.values(i.status):[];if(a.length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span>No health checks configured yet. Click "Add Health Check" below.</div>';return}let o='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';o+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Service</th><th style="padding: 8px; text-align: left;">Status</th><th style="padding: 8px; text-align: left;">SLA Target</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const l of a){const k=l.status==="up";o+='<tr style="border-bottom: 1px solid var(--border);">',o+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(l.name||l.serviceId)}</td>`,o+=`<td style="padding: 8px; color: ${k?"var(--ok-fg)":"var(--bad-fg)"};">${k?"Up":"Down"}</td>`,o+=`<td style="padding: 8px;">${l.sla?.target?l.sla.target+"%":"-"}</td>`,o+='<td style="padding: 8px; text-align: right;">',o+=`<button onclick="document.dispatchEvent(new CustomEvent('health-edit', {detail:'${escapeHtml(l.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`,o+=`<button onclick="document.dispatchEvent(new CustomEvent('health-delete', {detail:'${escapeHtml(l.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`,o+="</td></tr>"}o+="</table>",N.innerHTML=o}catch(n){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(n.message)}</div>`}}function e(n,i,a,o,l,k,I){r=n||null,w.textContent=n?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=n||"",document.getElementById("health-form-id").disabled=!!n,document.getElementById("health-form-name").value=i||"",document.getElementById("health-form-url").value=a||"",document.getElementById("health-form-timeout").value=o||1e4,document.getElementById("health-form-codes").value=l||"200",document.getElementById("health-form-sla").value=k||99.9,document.getElementById("health-form-slow").value=I||5e3,T.style.display="",m.style.display="none"}function s(){T.style.display="none",m.style.display="",r=null}m?.addEventListener("click",()=>e("","","",1e4,"200",99.9,5e3)),B?.addEventListener("click",s),E?.addEventListener("click",async()=>{const n=r||document.getElementById("health-form-id").value.trim();if(!n)return showNotification("Service ID is required","warning");const i=document.getElementById("health-form-url").value.trim();if(!i)return showNotification("URL is required","warning");const a=document.getElementById("health-form-codes").value.split(",").map(l=>parseInt(l.trim())).filter(Boolean),o={name:document.getElementById("health-form-name").value.trim()||n,url:i,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:a.length?a:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)|Line truncated
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;"> <div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u2B06\uFE0F Update Management</h3> <h3>\u2B06\uFE0F Update Management</h3>
<p class="modal-subtitle"> <p class="modal-subtitle">
@@ -1546,17 +1538,17 @@ This will replace current configuration, credentials, and data. Containers will
<button id="updates-cancel">Close</button> <button id="updates-cancel">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("updates-modal"),C=document.getElementById("updates-btn"),O=document.getElementById("updates-cancel"),E=document.getElementById("updates-check-btn"),M=document.getElementById("updates-available-container"),R=document.getElementById("updates-history-container"),P=document.getElementById("updates-auto-container"),A=document.getElementById("updates-last-check");async function p(){try{const n=await(await fetch("/api/v1/updates/available")).json();if(!n.success)throw new Error(n.error);const e=n.updates||[];if(e.length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',A.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let t='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';t+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const a of e){const s=(()=>{const d=window.APPS||[];for(const S of d)if(S.containerId===a.containerId||S.name===a.containerName||S.id===a.containerName)return S.id;return a.containerName})();t+=`<tr data-app-id="${escapeHtml(s)}" style="border-bottom: 1px solid var(--border);">`,t+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(a.containerName)}</td>`,t+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(a.imageName)}</td>`,t+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(a.currentDigest)}</code></td>`,t+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(a.latestDigest)}</code></td>`,t+='<td style="padding: 8px; text-align: right;">',t+=`<button class="update-now-btn" data-id="${escapeHtml(a.containerId)}" data-name="${escapeHtml(a.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,t+=`<button class="rollback-btn" data-id="${escapeHtml(a.containerId)}" data-name="${escapeHtml(a.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,t+="</td></tr>"}t+="</table>",M.innerHTML=t,A.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),r=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),r&&e.length>0&&(r.style.display=""),window._pendingUpdates=e,M.querySelectorAll(".update-now-btn").forEach(a=>{a.addEventListener("click",async()=>{const s=a.dataset.id,d=a.dataset.name;if(confirm(`Update "${d}" to the latest version? The container will restart.`)){a.textContent="Updating...",a.disabled=!0;try{const h=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(h.success)a.textContent="Done!",a.style.background="var(--ok-fg)",setTimeout(()=>p(),2e3);else throw new Error(h.error||"Update failed")}catch(S){a.textContent="Failed",a.style.color="var(--bad-fg)",showNotification("Update error: "+S.message,"error"),setTimeout(()=>{a.textContent="Update",a.disabled=!1,a.style.color="",a.style.background=""},3e3)}}})}),M.querySelectorAll(".rollback-btn").forEach(a=>{a.addEventListener("click",async()=>{const s=a.dataset.id,d=a.dataset.name;if(confirm(`Rollback "${d}" to its previous version?`)){a.textContent="Rolling back...",a.disabled=!0;try{const h=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(s)}`,{method:"POST"})).json();if(h.success)a.textContent="Rolled back!",setTimeout(()=>p(),2e3);else throw new Error(h.error||"Rollback failed")}catch(S){a.textContent="Failed",showNotification("Rollback error: "+S.message,"error"),setTimeout(()=>{a.textContent="Rollback",a.disabled=!1},3e3)}}})})}catch(m){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(m.message)}</div>`}}async function T(){const m=window._pendingUpdates||[];if(!m.length)return;const n=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${m.length} containers? Each will restart.`))return;n.textContent="\u23F3 Updating...",n.disabled=!0;let e=0,t=0;for(const o of m)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:t++}catch{t++}n.textCLine truncated </div>`);const h=document.getElementById("updates-modal"),L=document.getElementById("updates-btn"),R=document.getElementById("updates-cancel"),S=document.getElementById("updates-check-btn"),$=document.getElementById("updates-available-container"),P=document.getElementById("updates-history-container"),N=document.getElementById("updates-auto-container"),D=document.getElementById("updates-last-check");async function m(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){$.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',D.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let s='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';s+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const a of e){const o=(()=>{const l=window.APPS||[];for(const k of l)if(k.containerId===a.containerId||k.name===a.containerName||k.id===a.containerName)return k.id;return a.containerName})();s+=`<tr data-app-id="${escapeHtml(o)}" style="border-bottom: 1px solid var(--border);">`,s+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(a.containerName)}</td>`,s+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(a.imageName)}</td>`,s+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(a.currentDigest)}</code></td>`,s+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(a.latestDigest)}</code></td>`,s+='<td style="padding: 8px; text-align: right;">',s+=`<button class="update-now-btn" data-id="${escapeHtml(a.containerId)}" data-name="${escapeHtml(a.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,s+=`<button class="rollback-btn" data-id="${escapeHtml(a.containerId)}" data-name="${escapeHtml(a.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,s+="</td></tr>"}s+="</table>",$.innerHTML=s,D.textContent=e.length+" update(s) available";const n=document.getElementById("updates-count-badge"),i=document.getElementById("updates-update-all-btn");n&&(n.textContent=e.length+" pending",n.style.display=""),i&&e.length>0&&(i.style.display=""),window._pendingUpdates=e,$.querySelectorAll(".update-now-btn").forEach(a=>{a.addEventListener("click",async()=>{const o=a.dataset.id,l=a.dataset.name;if(confirm(`Update "${l}" to the latest version? The container will restart.`)){a.textContent="Updating...",a.disabled=!0;try{const I=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(I.success)a.textContent="Done!",a.style.background="var(--ok-fg)",setTimeout(()=>m(),2e3);else throw new Error(I.error||"Update failed")}catch(k){a.textContent="Failed",a.style.color="var(--bad-fg)",showNotification("Update error: "+k.message,"error"),setTimeout(()=>{a.textContent="Update",a.disabled=!1,a.style.color="",a.style.background=""},3e3)}}})}),$.querySelectorAll(".rollback-btn").forEach(a=>{a.addEventListener("click",async()=>{const o=a.dataset.id,l=a.dataset.name;if(confirm(`Rollback "${l}" to its previous version?`)){a.textContent="Rolling back...",a.disabled=!0;try{const I=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(o)}`,{method:"POST"})).json();if(I.success)a.textContent="Rolled back!",setTimeout(()=>m(),2e3);else throw new Error(I.error||"Rollback failed")}catch(k){a.textContent="Failed",showNotification("Rollback error: "+k.message,"error"),setTimeout(()=>{a.textContent="Rollback",a.disabled=!1},3e3)}}})})}catch(y){$.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(y.message)}</div>`}}async function T(){const y=window._pendingUpdates||[];if(!y.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${y.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,s=0;for(const n of y)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(n.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:s++}catch{s++}t.textCLine truncated
<select class="auto-schedule" data-id="${escapeHtml(S)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;"> <select class="auto-schedule" data-id="${escapeHtml(k)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<option value=""${U?"":" selected"}>Disabled</option> <option value=""${j?"":" selected"}>Disabled</option>
<option value="daily"${U==="daily"?" selected":""}>Daily</option> <option value="daily"${j==="daily"?" selected":""}>Daily</option>
<option value="weekly"${U==="weekly"?" selected":""}>Weekly</option> <option value="weekly"${j==="weekly"?" selected":""}>Weekly</option>
<option value="monthly"${U==="monthly"?" selected":""}>Monthly</option> <option value="monthly"${j==="monthly"?" selected":""}>Monthly</option>
</select></td>`,a+=`<td style="padding: 8px;"><input type="text" class="auto-window" data-id="${escapeHtml(S)}" value="${escapeHtml(F)}" placeholder="02:00-04:00" style="width: 90px; padding: 3px 6px; font-size: 0.78rem; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg);" /></td>`,a+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(S)}"${_?" checked":""} /></td>`,a+=`<td style="padding: 8px; font-size: 0.78rem; color: var(--muted);">${W}</td>`,a+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(S)}" data-name="${escapeHtml(d)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,a+="</tr>"}a+="</table>",P.innerHTML=a,P.querySelectorAll(".save-auto-btn").forEach(s=>{s.addEventListener("click",async()=>{const d=s.dataset.id,S=s.closest("tr"),h=S.querySelector(".auto-schedule").value,U=S.querySelector(".auto-rollback").checked,_=S.querySelector(".auto-window").value.trim();s.textContent="Saving...",s.disabled=!0;try{const W=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(d)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!h,schedule:h||"weekly",autoRollback:U,maintenanceWindow:_||void 0})})).json();if(W.success)s.textContent="\u2713 Saved";else throw new Error(W.error)}catch(F){s.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{s.textContent="Save",s.disabled=!1},2e3)})})}catch(m){P.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(m.message)}</div>`}}const H=document.getElementById("dashcaddy-current-version"),L=document.getElementById("dashcaddy-update-badge"),u=document.getElementById("dashcaddy-update-details"),j=document.getElementById("dashcaddy-new-version"),v=document.getElementById("dashcaddy-changelog"),N=document.getElementById("dashcaddy-apply-btn"),g=document.getElementById("dashcaddy-check-btn"),D=document.getElementById("dashcaddy-rollback-btn"),B=document.getElementById("dashcaddy-status-bar"),f=document.getElementById("dashcaddy-history-container");let I=null;function b(m,n){B&&(B.style.display="block",B.style.background=n==="error"?"var(--bad-bg)":n==="success"?"var(--ok-bg)":"var(--bg)",B.style.color=n==="error"?"var(--bad-fg)":n==="success"?"var(--ok-fg)":"var(--fg)",B.textContent=m)}async function z(){try{const n=await(await fetch("/api/v1/system/version")).json();if(n.success){const e=n.commit&&n.commit!=="unknown"?n.commit:null;H.textContent="v"+n.version+(e?" ("+e.substring(0,7)+")":"")}}catch{H.textContent="Unable to fetch version"}}async function i(m){m||(g.textContent="Checking...",g.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(I=e,e.success&&e.available&&e.remote){L.style.display="",u.style.display="",j.textContent="v"+e.remote.version,v.textContent=e.remote.changelog||"No changelog available.";const t=document.getElementById("updates-btn");if(t&&!t.querySelector(".update-dot")){const r=document.createElement("span");r.className="update-dot",r.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",t.style.position="relative",t.appendChild(r)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const r=document.createElement("span");r.className="update-dot",r.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(r)}}else L.style.display="none",u.style.display="none",await z(),m||b("You are running the latest version.","success");m||(g.textContent="Check for Updates",g.disabled=!1)}catch(n){m||(b("Failed to check: "+n.message,"error"),g.textContent="Check for Updates",g.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;N.textContent="Updating...",N.disabled=!0,b("Downloading and applying update...","info");try{const n=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(n.success)return b("Update initiated: v"+(n.fromVersion||"?")+" \u2192 v"+(n.toVersion||"?")+". The container will restart shortly.","success"),N.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(n.error||"Update failed")}catch(m){throw b("Update failed: "+m.message,"error"),N.textContent="Update Now",N.disabled=!1,m}}async function l(){try{const n=await(await fetch("/api/v1/system/update-history")).json(),e=n.success&&n.history?n.history:[];if(e.length===0){f.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let t='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';t+='<tr style="border-bottom: 1px solid var(--border); color: var(--mutLine truncated </select></td>`,a+=`<td style="padding: 8px;"><input type="text" class="auto-window" data-id="${escapeHtml(k)}" value="${escapeHtml(F)}" placeholder="02:00-04:00" style="width: 90px; padding: 3px 6px; font-size: 0.78rem; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg);" /></td>`,a+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(k)}"${_?" checked":""} /></td>`,a+=`<td style="padding: 8px; font-size: 0.78rem; color: var(--muted);">${q}</td>`,a+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(k)}" data-name="${escapeHtml(l)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,a+="</tr>"}a+="</table>",N.innerHTML=a,N.querySelectorAll(".save-auto-btn").forEach(o=>{o.addEventListener("click",async()=>{const l=o.dataset.id,k=o.closest("tr"),I=k.querySelector(".auto-schedule").value,j=k.querySelector(".auto-rollback").checked,_=k.querySelector(".auto-window").value.trim();o.textContent="Saving...",o.disabled=!0;try{const q=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!I,schedule:I||"weekly",autoRollback:j,maintenanceWindow:_||void 0})})).json();if(q.success)o.textContent="\u2713 Saved";else throw new Error(q.error)}catch(F){o.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{o.textContent="Save",o.disabled=!1},2e3)})})}catch(y){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(y.message)}</div>`}}const H=document.getElementById("dashcaddy-current-version"),C=document.getElementById("dashcaddy-update-badge"),v=document.getElementById("dashcaddy-update-details"),O=document.getElementById("dashcaddy-new-version"),f=document.getElementById("dashcaddy-changelog"),z=document.getElementById("dashcaddy-apply-btn"),A=document.getElementById("dashcaddy-check-btn"),U=document.getElementById("dashcaddy-rollback-btn"),p=document.getElementById("dashcaddy-status-bar"),u=document.getElementById("dashcaddy-history-container");let b=null;function g(y,t){p&&(p.style.display="block",p.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",p.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",p.textContent=y)}async function M(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;H.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{H.textContent="Unable to fetch version"}}async function r(y){y||(A.textContent="Checking...",A.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(b=e,e.success&&e.available&&e.remote){C.style.display="",v.style.display="",O.textContent="v"+e.remote.version,f.textContent=e.remote.changelog||"No changelog available.";const s=document.getElementById("updates-btn");if(s&&!s.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",s.style.position="relative",s.appendChild(i)}const n=document.getElementById("updates-dashcaddy-tab");if(n&&!n.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",n.appendChild(i)}}else C.style.display="none",v.style.display="none",await M(),y||g("You are running the latest version.","success");y||(A.textContent="Check for Updates",A.disabled=!1)}catch(t){y||(g("Failed to check: "+t.message,"error"),A.textContent="Check for Updates",A.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;z.textContent="Updating...",z.disabled=!0,g("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return g("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),z.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(y){throw g("Update failed: "+y.message,"error"),z.textContent="Update Now",z.disabled=!1,y}}async function d(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){u.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let s='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';s+='<tr style="border-bottom: 1px solid var(--border); color: var(--mutLine truncated
`+e.join(` `+e.join(`
`)+` `)+`
Enter version to rollback to:`);if(!t)return;if(!e.includes(t)){showNotification("Invalid version: "+t,"error");return}if(!confirm("Rollback DashCaddy to v"+t+"? The container will restart."))return;b("Rolling back to v"+t+"...","info");const r=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:t})})).json();if(r.success)b("Rollback to v"+t+" initiated. Container will restart.","success");else throw new Error(r.error||"Rollback failed")}catch(m){b("Rollback failed: "+m.message,"error")}}g?.addEventListener("click",()=>i(!1)),N?.addEventListener("click",()=>c().catch(()=>{})),D?.addEventListener("click",w),E?.addEventListener("click",x),C?.addEventListener("click",()=>{y?.classList.add("show"),p()}),wireModal(y,O),window.openUpdateModal=function(m){y?.classList.add("show"),p().then(()=>{if(!m)return;const n=M.querySelector(`[data-app-id="${m}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{n.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",$),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{z(),l(),I||i(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=i,setTimeout(()=>i(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`<div id="docker-resources-modal" class="weather-modal"> Enter version to rollback to:`);if(!s)return;if(!e.includes(s)){showNotification("Invalid version: "+s,"error");return}if(!confirm("Rollback DashCaddy to v"+s+"? The container will restart."))return;g("Rolling back to v"+s+"...","info");const i=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:s})})).json();if(i.success)g("Rollback to v"+s+" initiated. Container will restart.","success");else throw new Error(i.error||"Rollback failed")}catch(y){g("Rollback failed: "+y.message,"error")}}A?.addEventListener("click",()=>r(!1)),z?.addEventListener("click",()=>c().catch(()=>{})),U?.addEventListener("click",x),S?.addEventListener("click",w),L?.addEventListener("click",()=>{h?.classList.add("show"),m()}),wireModal(h,R),window.openUpdateModal=function(y){h?.classList.add("show"),m().then(()=>{if(!y)return;const t=$.querySelector(`[data-app-id="${y}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",B),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",E),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{M(),d(),b||r(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=r,setTimeout(()=>r(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`<div id="docker-resources-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;"> <div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u{1F433} Docker Resources</h3> <h3>\u{1F433} Docker Resources</h3>
<p class="modal-subtitle">Manage volumes, networks, and view disk usage.</p> <p class="modal-subtitle">Manage volumes, networks, and view disk usage.</p>
@@ -1605,7 +1597,7 @@ Enter version to rollback to:`);if(!t)return;if(!e.includes(t)){showNotification
<button id="dr-close">Close</button> <button id="dr-close">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("docker-resources-modal"),C=document.getElementById("docker-resources-btn"),O=document.getElementById("dr-close");function E(A){if(!A||A===0)return"0 B";const p=["B","KB","MB","GB","TB"],T=Math.floor(Math.log(Math.abs(A))/Math.log(1024));return(A/Math.pow(1024,T)).toFixed(1)+" "+p[T]}async function M(){const A=document.getElementById("dr-vol-list");try{const T=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(T.length===0){A.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No volumes found.</div>';return}let x='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';x+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const $ of T){const k=$.name==="buildkit"||$.name.length===64;x+='<tr style="border-bottom: 1px solid var(--border);">',x+=`<td style="padding: 6px; font-weight: 500; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml($.name)}">${escapeHtml($.name.length>40?$.name.substring(0,37)+"...":$.name)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.driver)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.scope)}</td>`,x+='<td style="padding: 6px; text-align: right;">',k||(x+=`<button class="dr-vol-del" data-name="${escapeHtml($.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),x+="</td></tr>"}x+="</table>",A.innerHTML=x,A.querySelectorAll(".dr-vol-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete volume "${$.dataset.name}"? Data will be lost.`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent($.dataset.name)}?force=true`),M()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(p){A.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const A=document.getElementById("dr-vol-name"),p=A.value.trim();if(!p){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:p}),A.value="",showNotification(`Volume "${p}" created`,"success"),M()}catch(T){showNotification("Create failed: "+T.message,"error")}});async function R(){const A=document.getElementById("dr-net-list");try{const T=(await getJSON("/api/v1/docker/networks")).networks||[];if(T.length===0){A.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F310}</span>No networks found.</div>';return}let x='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';x+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px;">Containers</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const $ of T){const k=["bridge","host","none"].includes($.name);x+='<tr style="border-bottom: 1px solid var(--border);">',x+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml($.name)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.driver)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.scope)}</td>`,x+=`<td style="padding: 6px; text-align: center;">${$.containers}</td>`,x+='<td style="padding: 6px; text-align: right;">',k||(x+=`<button class="dr-net-del" data-id="${escapeHtml($.id)}" data-name="${escapeHtml($.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),x+="</td></tr>"}x+="</table>",A.innerHTML=x,A.querySelectorAll(".dr-net-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete network "${$.dataset.name}"?`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent($.dataset.id)}`),R()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(p){A.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const A=document.getElementById("dr-net-name"),p=document.getElementById("dr-net-driver"),T=A.value.trim();if(!T){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:T,driver:p.value}),A.value="",showNotification(`Network "${T}" created`,"success"),R()}catch(x){showNotification("Create failed: "+x.message,"error")}});async fuLine truncated </div>`);const h=document.getElementById("docker-resources-modal"),L=document.getElementById("docker-resources-btn"),R=document.getElementById("dr-close");function S(D){if(!D||D===0)return"0 B";const m=["B","KB","MB","GB","TB"],T=Math.floor(Math.log(Math.abs(D))/Math.log(1024));return(D/Math.pow(1024,T)).toFixed(1)+" "+m[T]}async function $(){const D=document.getElementById("dr-vol-list");try{const T=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(T.length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No volumes found.</div>';return}let w='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';w+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const B of T){const E=B.name==="buildkit"||B.name.length===64;w+='<tr style="border-bottom: 1px solid var(--border);">',w+=`<td style="padding: 6px; font-weight: 500; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml(B.name)}">${escapeHtml(B.name.length>40?B.name.substring(0,37)+"...":B.name)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(B.driver)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(B.scope)}</td>`,w+='<td style="padding: 6px; text-align: right;">',E||(w+=`<button class="dr-vol-del" data-name="${escapeHtml(B.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),w+="</td></tr>"}w+="</table>",D.innerHTML=w,D.querySelectorAll(".dr-vol-del").forEach(B=>{B.addEventListener("click",async()=>{if(confirm(`Delete volume "${B.dataset.name}"? Data will be lost.`)){B.textContent="...",B.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(B.dataset.name)}?force=true`),$()}catch(E){showNotification("Delete failed: "+E.message,"error"),B.textContent="Delete",B.disabled=!1}}})})}catch(m){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(m.message)}</div>`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const D=document.getElementById("dr-vol-name"),m=D.value.trim();if(!m){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:m}),D.value="",showNotification(`Volume "${m}" created`,"success"),$()}catch(T){showNotification("Create failed: "+T.message,"error")}});async function P(){const D=document.getElementById("dr-net-list");try{const T=(await getJSON("/api/v1/docker/networks")).networks||[];if(T.length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F310}</span>No networks found.</div>';return}let w='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';w+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px;">Containers</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const B of T){const E=["bridge","host","none"].includes(B.name);w+='<tr style="border-bottom: 1px solid var(--border);">',w+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(B.name)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(B.driver)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(B.scope)}</td>`,w+=`<td style="padding: 6px; text-align: center;">${B.containers}</td>`,w+='<td style="padding: 6px; text-align: right;">',E||(w+=`<button class="dr-net-del" data-id="${escapeHtml(B.id)}" data-name="${escapeHtml(B.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),w+="</td></tr>"}w+="</table>",D.innerHTML=w,D.querySelectorAll(".dr-net-del").forEach(B=>{B.addEventListener("click",async()=>{if(confirm(`Delete network "${B.dataset.name}"?`)){B.textContent="...",B.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent(B.dataset.id)}`),P()}catch(E){showNotification("Delete failed: "+E.message,"error"),B.textContent="Delete",B.disabled=!1}}})})}catch(m){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(m.message)}</div>`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const D=document.getElementById("dr-net-name"),m=document.getElementById("dr-net-driver"),T=D.value.trim();if(!T){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:T,driver:m.value}),D.value="",showNotification(`Network "${T}" created`,"success"),P()}catch(w){showNotification("Create failed: "+w.message,"error")}});async fuLine truncated
<div class="weather-modal-content" style="min-width: 650px; max-width: 800px;"> <div class="weather-modal-content" style="min-width: 650px; max-width: 800px;">
<h3>\u{1F4E6} Import Docker Compose</h3> <h3>\u{1F4E6} Import Docker Compose</h3>
<p class="modal-subtitle">Paste a docker-compose.yml to import and deploy services.</p> <p class="modal-subtitle">Paste a docker-compose.yml to import and deploy services.</p>
@@ -1646,8 +1638,8 @@ Enter version to rollback to:`);if(!t)return;if(!e.includes(t)){showNotification
<div id="compose-progress-content"></div> <div id="compose-progress-content"></div>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("compose-import-modal"),C=document.getElementById("compose-import-btn"),O=document.getElementById("compose-cancel");wireModal(y,O);let E=null;function M(P){document.getElementById("compose-step-paste").style.display=P==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=P==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=P==="progress"?"":"none"}C?.addEventListener("click",()=>{M("paste"),E=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",y?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",P=>{const A=P.target.files[0];if(!A)return;const p=new FileReader;p.onload=()=>{document.getElementById("compose-yaml").value=p.result},p.readAsText(A)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const P=document.getElementById("compose-yaml").value.trim(),A=document.getElementById("compose-stack-name").value.trim()||"stack";if(!P){showNotification("Paste a docker-compose.yml","warning");return}const p=document.getElementById("compose-parse-btn"),T=p.textContent;p.textContent="Parsing...",p.disabled=!0;try{const x=await postJSON("/api/v1/apps/import-compose",{yaml:P,stackName:A});E=x,E.stackName=A,R(x),M("preview")}catch(x){showNotification("Parse failed: "+x.message,"error")}finally{p.textContent=T,p.disabled=!1}});function R(P){const A=document.getElementById("compose-preview-content");let p="";P.networks&&P.networks.length>0&&(p+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Networks: ${P.networks.map(T=>`<code>${escapeHtml(T)}</code>`).join(", ")}</div>`),P.volumes&&P.volumes.length>0&&(p+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Volumes: ${P.volumes.map(T=>`<code>${escapeHtml(T)}</code>`).join(", ")}</div>`),p+=`<div style="font-weight: 600; margin-bottom: 8px;">${P.services.length} service(s)</div>`,p+='<div class="scroll-container" style="max-height: 350px;">';for(const T of P.services){const x=T.skip?"var(--bad-fg)":"var(--border)";if(p+=`<div style="padding: 10px 14px; border: 1px solid ${x}; border-radius: 8px; margin-bottom: 8px; background: var(--bg);">`,p+=`<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(T.name)}`,T.skip&&(p+=` <span style="color: var(--bad-fg); font-weight: 400; font-size: 0.78rem;">\u2014 skipped: ${escapeHtml(T.reason)}</span>`),p+="</div>",!T.skip&&(p+=`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Image: <code>${escapeHtml(T.image)}</code></div>`,T.ports?.length&&(p+=`<div style="font-size: 0.8rem; color: var(--muted);">Ports: ${T.ports.map($=>`${$.host}:${$.container}`).join(", ")}</div>`),T.volumes?.length&&(p+=`<div style="font-size: 0.8rem; color: var(--muted);">Volumes: ${T.volumes.length}</div>`),Object.keys(T.environment||{}).length&&(p+=`<div style="font-size: 0.8rem; color: var(--muted);">Env vars: ${Object.keys(T.environment).length}</div>`),T.envFileWarning&&(p+=`<div style="font-size: 0.78rem; color: var(--bad-fg);">\u26A0 ${escapeHtml(T.envFileWarning)}</div>`),T.resources?.cpus||T.resources?.memory)){const $=[];T.resources.cpus&&$.push(`CPU: ${T.resources.cpus}`),T.resources.memory&&$.push(`Mem: ${T.resources.memory}MB`),p+=`<div style="font-size: 0.8rem; color: var(--muted);">Limits: ${$.join(", ")}</div>`}p+="</div>"}p+="</div>",A.innerHTML=p}document.getElementById("compose-back-btn")?.addEventListener("click",()=>M("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!E)return;const P=document.getElementById("compose-deploy-btn");P.textContent="Deploying...",P.disabled=!0,M("progress");const A=document.getElementById("compose-progress-content");A.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Deploying services...</div>';try{const p=await postJSON("/api/v1/apps/deploy-compose",{services:E.services,networks:E.networks,stackName:E.stackName});let T=`<div style="font-weight: 600; margin-bottom: 12px;">Stack "${escapeHtml(p.stackName)}" \u2014 Deployment Complete</div>`;T+='<div class="scroll-container" style="max-height: 350px;">';for(const x of p.results){const $=x.status==="deployed"||x.status==="created"?"\u2705":x.status==="exists"?"\u26A1":x.status==="skipped"?"\u23ED":"\u274C";T+='<div style="padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 0.85rem;">',T+=`${$} <strong>${escapeHtml(x.name)}</strong> (${x.type}) \u2014 ${escapeHtml(x.status)}`,x.error&&(T+=` <span style="color: var(--bad-fg);">${escapeHtml(x.error)}</span>`),x.subdomain&&(T+=` \u2192 <code>${escapeHtml(x.subdomain)}</code>`),x.reason&&(T+=` <span style="color: var(--muted);">(${escapeHtml(x.reason)})</span>`),T+="</div>"}T+="</div>",T+='<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-done-btn">Done</button></div>Line truncated </div>`);const h=document.getElementById("compose-import-modal"),L=document.getElementById("compose-import-btn"),R=document.getElementById("compose-cancel");wireModal(h,R);let S=null;function $(N){document.getElementById("compose-step-paste").style.display=N==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=N==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=N==="progress"?"":"none"}L?.addEventListener("click",()=>{$("paste"),S=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",h?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",N=>{const D=N.target.files[0];if(!D)return;const m=new FileReader;m.onload=()=>{document.getElementById("compose-yaml").value=m.result},m.readAsText(D)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const N=document.getElementById("compose-yaml").value.trim(),D=document.getElementById("compose-stack-name").value.trim()||"stack";if(!N){showNotification("Paste a docker-compose.yml","warning");return}const m=document.getElementById("compose-parse-btn"),T=m.textContent;m.textContent="Parsing...",m.disabled=!0;try{const w=await postJSON("/api/v1/apps/import-compose",{yaml:N,stackName:D});S=w,S.stackName=D,P(w),$("preview")}catch(w){showNotification("Parse failed: "+w.message,"error")}finally{m.textContent=T,m.disabled=!1}});function P(N){const D=document.getElementById("compose-preview-content");let m="";N.networks&&N.networks.length>0&&(m+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Networks: ${N.networks.map(T=>`<code>${escapeHtml(T)}</code>`).join(", ")}</div>`),N.volumes&&N.volumes.length>0&&(m+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Volumes: ${N.volumes.map(T=>`<code>${escapeHtml(T)}</code>`).join(", ")}</div>`),m+=`<div style="font-weight: 600; margin-bottom: 8px;">${N.services.length} service(s)</div>`,m+='<div class="scroll-container" style="max-height: 350px;">';for(const T of N.services){const w=T.skip?"var(--bad-fg)":"var(--border)";if(m+=`<div style="padding: 10px 14px; border: 1px solid ${w}; border-radius: 8px; margin-bottom: 8px; background: var(--bg);">`,m+=`<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(T.name)}`,T.skip&&(m+=` <span style="color: var(--bad-fg); font-weight: 400; font-size: 0.78rem;">\u2014 skipped: ${escapeHtml(T.reason)}</span>`),m+="</div>",!T.skip&&(m+=`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Image: <code>${escapeHtml(T.image)}</code></div>`,T.ports?.length&&(m+=`<div style="font-size: 0.8rem; color: var(--muted);">Ports: ${T.ports.map(B=>`${B.host}:${B.container}`).join(", ")}</div>`),T.volumes?.length&&(m+=`<div style="font-size: 0.8rem; color: var(--muted);">Volumes: ${T.volumes.length}</div>`),Object.keys(T.environment||{}).length&&(m+=`<div style="font-size: 0.8rem; color: var(--muted);">Env vars: ${Object.keys(T.environment).length}</div>`),T.envFileWarning&&(m+=`<div style="font-size: 0.78rem; color: var(--bad-fg);">\u26A0 ${escapeHtml(T.envFileWarning)}</div>`),T.resources?.cpus||T.resources?.memory)){const B=[];T.resources.cpus&&B.push(`CPU: ${T.resources.cpus}`),T.resources.memory&&B.push(`Mem: ${T.resources.memory}MB`),m+=`<div style="font-size: 0.8rem; color: var(--muted);">Limits: ${B.join(", ")}</div>`}m+="</div>"}m+="</div>",D.innerHTML=m}document.getElementById("compose-back-btn")?.addEventListener("click",()=>$("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!S)return;const N=document.getElementById("compose-deploy-btn");N.textContent="Deploying...",N.disabled=!0,$("progress");const D=document.getElementById("compose-progress-content");D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Deploying services...</div>';try{const m=await postJSON("/api/v1/apps/deploy-compose",{services:S.services,networks:S.networks,stackName:S.stackName});let T=`<div style="font-weight: 600; margin-bottom: 12px;">Stack "${escapeHtml(m.stackName)}" \u2014 Deployment Complete</div>`;T+='<div class="scroll-container" style="max-height: 350px;">';for(const w of m.results){const B=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";T+='<div style="padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 0.85rem;">',T+=`${B} <strong>${escapeHtml(w.name)}</strong> (${w.type}) \u2014 ${escapeHtml(w.status)}`,w.error&&(T+=` <span style="color: var(--bad-fg);">${escapeHtml(w.error)}</span>`),w.subdomain&&(T+=` \u2192 <code>${escapeHtml(w.subdomain)}</code>`),w.reason&&(T+=` <span style="color: var(--muted);">(${escapeHtml(w.reason)})</span>`),T+="</div>"}T+="</div>",T+='<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-done-btn">Done</button></div>Line truncated
<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-retry-btn">Back</button></div>`,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>M("paste"))}finally{P.textContent="Deploy All",P.disabled=!1}})})(),(function(){injectModal("exec-modal",`<div id="exec-modal" class="weather-modal"> <div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-retry-btn">Back</button></div>`,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>$("paste"))}finally{N.textContent="Deploy All",N.disabled=!1}})})(),(function(){injectModal("exec-modal",`<div id="exec-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 700px; max-width: 900px; padding-bottom: 0;"> <div class="weather-modal-content" style="min-width: 700px; max-width: 900px; padding-bottom: 0;">
<h3 id="exec-title">Terminal</h3> <h3 id="exec-title">Terminal</h3>
<div id="exec-terminal" style="height: 420px; border-radius: 6px; overflow: hidden; background: #1e1e1e;"></div> <div id="exec-terminal" style="height: 420px; border-radius: 6px; overflow: hidden; background: #1e1e1e;"></div>
@@ -1655,11 +1647,11 @@ Enter version to rollback to:`);if(!t)return;if(!e.includes(t)){showNotification
<button id="exec-close">Close</button> <button id="exec-close">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("exec-modal"),C=document.getElementById("exec-terminal"),O=document.getElementById("exec-close");let E=null,M=null,R=null;function P(){if(M){try{M.close()}catch{}M=null}if(E){try{E.dispose()}catch{}E=null}R=null,C.innerHTML=""}function A(p,T){if(P(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${T||p}`,y?.classList.add("show"),typeof Terminal>"u"){C.innerHTML='<div style="color: #f44; padding: 20px; font-family: monospace;">xterm.js not loaded</div>';return}E=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(R=new FitAddon.FitAddon,E.loadAddon(R)),E.open(C),R&&setTimeout(()=>R.fit(),50);const x=location.protocol==="https:"?"wss:":"ws:";M=new WebSocket(`${x}//${location.host}/ws/exec/${encodeURIComponent(p)}`),M.binaryType="arraybuffer",M.onopen=()=>{if(E.writeln("\x1B[32mConnecting...\x1B[0m"),R){const k=R.proposeDimensions();k&&M.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}},M.onmessage=k=>{if(typeof k.data=="string"){try{const H=JSON.parse(k.data);if(H.type==="connected"){E.writeln(`\x1B[32mConnected (${H.shell})\x1B[0m\r </div>`);const h=document.getElementById("exec-modal"),L=document.getElementById("exec-terminal"),R=document.getElementById("exec-close");let S=null,$=null,P=null;function N(){if($){try{$.close()}catch{}$=null}if(S){try{S.dispose()}catch{}S=null}P=null,L.innerHTML=""}function D(m,T){if(N(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${T||m}`,h?.classList.add("show"),typeof Terminal>"u"){L.innerHTML='<div style="color: #f44; padding: 20px; font-family: monospace;">xterm.js not loaded</div>';return}S=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(P=new FitAddon.FitAddon,S.loadAddon(P)),S.open(L),P&&setTimeout(()=>P.fit(),50);const w=location.protocol==="https:"?"wss:":"ws:";$=new WebSocket(`${w}//${location.host}/ws/exec/${encodeURIComponent(m)}`),$.binaryType="arraybuffer",$.onopen=()=>{if(S.writeln("\x1B[32mConnecting...\x1B[0m"),P){const E=P.proposeDimensions();E&&$.send(JSON.stringify({type:"resize",cols:E.cols,rows:E.rows}))}},$.onmessage=E=>{if(typeof E.data=="string"){try{const H=JSON.parse(E.data);if(H.type==="connected"){S.writeln(`\x1B[32mConnected (${H.shell})\x1B[0m\r
`);return}if(H.type==="error"){E.writeln(`\x1B[31mError: ${H.message}\x1B[0m`);return}if(H.type==="exit"){E.writeln(`\r `);return}if(H.type==="error"){S.writeln(`\x1B[31mError: ${H.message}\x1B[0m`);return}if(H.type==="exit"){S.writeln(`\r
\x1B[33mSession ended.\x1B[0m`);return}}catch{}E.write(k.data)}else E.write(new Uint8Array(k.data))},M.onclose=()=>{E&&E.writeln(`\r \x1B[33mSession ended.\x1B[0m`);return}}catch{}S.write(E.data)}else S.write(new Uint8Array(E.data))},$.onclose=()=>{S&&S.writeln(`\r
\x1B[33mDisconnected.\x1B[0m`)},M.onerror=()=>{E&&E.writeln(`\r \x1B[33mDisconnected.\x1B[0m`)},$.onerror=()=>{S&&S.writeln(`\r
\x1B[31mConnection error.\x1B[0m`)},E.onData(k=>{M&&M.readyState===WebSocket.OPEN&&M.send(k)}),E.onResize(({cols:k,rows:H})=>{M&&M.readyState===WebSocket.OPEN&&M.send(JSON.stringify({type:"resize",cols:k,rows:H}))});const $=()=>{R&&R.fit()};window.addEventListener("resize",$),y._resizeHandler=$}O?.addEventListener("click",()=>{P(),y._resizeHandler&&window.removeEventListener("resize",y._resizeHandler),y?.classList.remove("show")}),y?.addEventListener("click",p=>{p.target===y&&(P(),y._resizeHandler&&window.removeEventListener("resize",y._resizeHandler),y?.classList.remove("show"))}),window.openExecModal=A})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal"> \x1B[31mConnection error.\x1B[0m`)},S.onData(E=>{$&&$.readyState===WebSocket.OPEN&&$.send(E)}),S.onResize(({cols:E,rows:H})=>{$&&$.readyState===WebSocket.OPEN&&$.send(JSON.stringify({type:"resize",cols:E,rows:H}))});const B=()=>{P&&P.fit()};window.addEventListener("resize",B),h._resizeHandler=B}R?.addEventListener("click",()=>{N(),h._resizeHandler&&window.removeEventListener("resize",h._resizeHandler),h?.classList.remove("show")}),h?.addEventListener("click",m=>{m.target===h&&(N(),h._resizeHandler&&window.removeEventListener("resize",h._resizeHandler),h?.classList.remove("show"))}),window.openExecModal=D})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 850px; max-width: 1050px;"> <div class="weather-modal-content" style="min-width: 850px; max-width: 1050px;">
<h3>\u{1F4DC} Audit Log</h3> <h3>\u{1F4DC} Audit Log</h3>
<p class="modal-subtitle"> <p class="modal-subtitle">
@@ -1695,7 +1687,7 @@ Enter version to rollback to:`);if(!t)return;if(!e.includes(t)){showNotification
<button id="audit-cancel">Close</button> <button id="audit-cancel">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("audit-modal"),C=document.getElementById("audit-log-btn"),O=document.getElementById("audit-cancel"),E=document.getElementById("audit-refresh-btn"),M=document.getElementById("audit-clear-btn"),R=document.getElementById("audit-filter"),P=document.getElementById("audit-log-container"),A=document.getElementById("audit-load-more");let p=0;const T=50;async function x($){try{$||(p=0,P.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const k=R.value;let H=`/api/v1/audit-logs?limit=${T}&offset=${p}`;k&&(H+=`&action=${encodeURIComponent(k)}`);const u=await(await fetch(H)).json(),j=u.success&&u.entries?u.entries:[];if(j.length===0&&!$){P.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>No audit log entries yet. Actions will be logged automatically.</div>',A.style.display="none";return}let v="";$||(v='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',v+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">When</th><th style="padding: 6px; text-align: left;">IP</th><th style="padding: 6px; text-align: left;">Action</th><th style="padding: 6px; text-align: left;">Resource</th><th style="padding: 6px; text-align: left;">Result</th></tr>');for(const N of j){const g=N.outcome==="success";v+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',v+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(N.timestamp)}</td>`,v+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(N.ip||"-")}</td>`,v+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(N.action||"-")}</td>`,v+=`<td style="padding: 6px;">${escapeHtml(N.resource||"-")}</td>`,v+=`<td style="padding: 6px;"><span style="color: ${g?"var(--ok-fg)":"var(--bad-fg)"};">${g?"\u2713":"\u2717"}</span></td>`,v+="</tr>",N.details&&Object.keys(N.details).length>0&&(v+=`<tr class="audit-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace;">${escapeHtml(JSON.stringify(N.details,null,2))}</pre></td></tr>`)}if(!$)v+="</table>",P.innerHTML=v;else{const N=P.querySelector("table");N&&N.insertAdjacentHTML("beforeend",v)}p+=j.length,A.style.display=j.length>=T?"":"none",P.querySelectorAll(".audit-row").forEach(N=>{N.dataset.wired||(N.dataset.wired="true",N.addEventListener("click",()=>{const g=N.nextElementSibling;g&&g.classList.contains("audit-detail")&&(g.style.display=g.style.display==="none"?"":"none")}))})}catch(k){P.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(k.message)}</div>`}}C?.addEventListener("click",()=>{y?.classList.add("show"),x(!1)}),wireModal(y,O),E?.addEventListener("click",()=>x(!1)),R?.addEventListener("change",()=>x(!1)),A?.addEventListener("click",()=>x(!0)),M?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const k=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"})).json();k.success?x(!1):showNotification("Error: "+(k.error||"Clear failed"),"error")}catch($){showNotification("Error: "+$.message,"error")}})})(),(function(){injectModal("security-modal",`<div id="security-modal" class="weather-modal"> </div>`);const h=document.getElementById("audit-modal"),L=document.getElementById("audit-log-btn"),R=document.getElementById("audit-cancel"),S=document.getElementById("audit-refresh-btn"),$=document.getElementById("audit-clear-btn"),P=document.getElementById("audit-filter"),N=document.getElementById("audit-log-container"),D=document.getElementById("audit-load-more");let m=0;const T=50;async function w(B){try{B||(m=0,N.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const E=P.value;let H=`/api/v1/audit-logs?limit=${T}&offset=${m}`;E&&(H+=`&action=${encodeURIComponent(E)}`);const v=await(await fetch(H)).json(),O=v.success&&v.entries?v.entries:[];if(O.length===0&&!B){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>No audit log entries yet. Actions will be logged automatically.</div>',D.style.display="none";return}let f="";B||(f='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',f+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">When</th><th style="padding: 6px; text-align: left;">IP</th><th style="padding: 6px; text-align: left;">Action</th><th style="padding: 6px; text-align: left;">Resource</th><th style="padding: 6px; text-align: left;">Result</th></tr>');for(const z of O){const A=z.outcome==="success";f+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',f+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(z.timestamp)}</td>`,f+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(z.ip||"-")}</td>`,f+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(z.action||"-")}</td>`,f+=`<td style="padding: 6px;">${escapeHtml(z.resource||"-")}</td>`,f+=`<td style="padding: 6px;"><span style="color: ${A?"var(--ok-fg)":"var(--bad-fg)"};">${A?"\u2713":"\u2717"}</span></td>`,f+="</tr>",z.details&&Object.keys(z.details).length>0&&(f+=`<tr class="audit-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace;">${escapeHtml(JSON.stringify(z.details,null,2))}</pre></td></tr>`)}if(!B)f+="</table>",N.innerHTML=f;else{const z=N.querySelector("table");z&&z.insertAdjacentHTML("beforeend",f)}m+=O.length,D.style.display=O.length>=T?"":"none",N.querySelectorAll(".audit-row").forEach(z=>{z.dataset.wired||(z.dataset.wired="true",z.addEventListener("click",()=>{const A=z.nextElementSibling;A&&A.classList.contains("audit-detail")&&(A.style.display=A.style.display==="none"?"":"none")}))})}catch(E){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(E.message)}</div>`}}L?.addEventListener("click",()=>{h?.classList.add("show"),w(!1)}),wireModal(h,R),S?.addEventListener("click",()=>w(!1)),P?.addEventListener("change",()=>w(!1)),D?.addEventListener("click",()=>w(!0)),$?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const E=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"})).json();E.success?w(!1):showNotification("Error: "+(E.error||"Clear failed"),"error")}catch(B){showNotification("Error: "+B.message,"error")}})})(),(function(){injectModal("security-modal",`<div id="security-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 980px; max-width: 1280px;"> <div class="weather-modal-content" style="min-width: 980px; max-width: 1280px;">
<h3>\u{1F6E1}\uFE0F Security Center</h3> <h3>\u{1F6E1}\uFE0F Security Center</h3>
<p class="modal-subtitle"> <p class="modal-subtitle">
@@ -1774,39 +1766,39 @@ Enter version to rollback to:`);if(!t)return;if(!e.includes(t)){showNotification
<button id="sec-cancel">Close</button> <button id="sec-cancel">Close</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("security-modal"),C=document.getElementById("security-center-btn"),O=document.getElementById("sec-cancel"),E=y.querySelectorAll(".sec-tab"),M=y.querySelectorAll(".sec-panel");let R=[],P=[],A=null;E.forEach(i=>{i.addEventListener("click",()=>{E.forEach(c=>c.classList.toggle("active",c===i)),M.forEach(c=>c.style.display=c.dataset.panel===i.dataset.tab?"":"none"),i.dataset.tab==="overview"&&$(),i.dataset.tab==="events"&&N(),i.dataset.tab==="hosts"&&f()})}),C&&C.addEventListener("click",()=>{y.classList.add("show"),$(),T()}),O.addEventListener("click",p),y.addEventListener("click",i=>{i.target===y&&p()});function p(){y.classList.remove("show"),x()}function T(){if(x(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{A=new EventSource("/api/v1/security/events/stream"),A.addEventListener("init",i=>{try{R=JSON.parse(i.data).events||[],g()}catch{}}),A.addEventListener("security",i=>{try{const c=JSON.parse(i.data);R.unshift(c),R.length>500&&(R.length=500);const l=y.querySelector(".sec-tab.active")?.dataset?.tab;l==="events"?g():l==="overview"&&$()}catch{}}),A.onerror=()=>{}}catch(i){console.warn("[security] SSE failed:",i.message)}}function x(){if(A){try{A.close()}catch{}A=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{y.classList.contains("show")&&T()});async function $(){try{const i=new Date(Date.now()-864e5).toISOString(),[c,l,w]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(i)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(i)}`)]),m=(await c.json()).data||{},n=(await l.json()).data?.hosts||[],e=(await w.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${m.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${m.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${m.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${n.length} hosts`,k("sec-top-actors",m.top_actors||[]),k("sec-top-targets",m.top_targets||[])}catch(i){console.warn("[security] refreshOverview failed:",i.message)}}function k(i,c){const l=document.getElementById(i);if(!c.length){l.innerHTML='<div class="panel-empty">No data</div>';return}l.innerHTML='<table style="width:100%;font-size:0.85rem;">'+c.map(w=>`<tr><td style="padding:3px 0;word-break:break-all;">${b(String(w.key))}</td><td style="text-align:right;color:var(--muted);">${w.count}</td></tr>`).join("")+"</table>"}const H=document.getElementById("sec-filter-source"),L=document.getElementById("sec-filter-severity"),u=document.getElementById("sec-filter-host"),j=document.getElementById("sec-filter-actor"),v=document.getElementById("sec-refresh-btn");[H,L,u].forEach(i=>i.addEventListener("change",N)),j.addEventListener("input",z(N,250)),v.addEventListener("click",N);async function N(){try{const i=new URLSearchParams;i.set("limit","200"),H.value&&i.set("source_type",H.value),L.value&&i.set("severity",L.value),u.value&&i.set("source_host",u.value),j.value&&i.set("actor_prefix",j.value),R=(await(await fetch(`/api/v1/security/events?${i}`)).json()).data.events||[],g(),(!u.options.length||u.options.length===1)&&await B()}catch(i){document.getElementById("sec-events-container").innerHTML='<div class="panel-empty">Load failed: '+b(i.message)+"</div>"}}function g(){const i=document.getElementById("sec-events-container");if(!R.length){i.innerHTML='<div class="panel-empty">No events</div>';return}i.innerHTML=R.slice(0,200).map(D).join("")}function D(i){const c=i.severity||"info",l={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",w=i.ts?new Date(i.ts).toLocaleTimeString():"",m=i.source_type||"",n=i.actor||"\u2014",e=i.target||"",t=i.action||"",o=i.outcome||"";return`<div class="sec-event-row" style="display:grid;grid-template-columns:84px 80px 1fr 1fr 100px 90px;gap:8px;padding:5px 8px;border-bottom:1px solid var(--border);font-size:0.82rem;align-items:center;"> </div>`);const h=document.getElementById("security-modal"),L=document.getElementById("security-center-btn"),R=document.getElementById("sec-cancel"),S=h.querySelectorAll(".sec-tab"),$=h.querySelectorAll(".sec-panel");let P=[],N=[],D=null;S.forEach(r=>{r.addEventListener("click",()=>{S.forEach(c=>c.classList.toggle("active",c===r)),$.forEach(c=>c.style.display=c.dataset.panel===r.dataset.tab?"":"none"),r.dataset.tab==="overview"&&B(),r.dataset.tab==="events"&&z(),r.dataset.tab==="hosts"&&u()})}),L&&L.addEventListener("click",()=>{h.classList.add("show"),B(),T()}),R.addEventListener("click",m),h.addEventListener("click",r=>{r.target===h&&m()});function m(){h.classList.remove("show"),w()}function T(){if(w(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{D=new EventSource("/api/v1/security/events/stream"),D.addEventListener("init",r=>{try{P=JSON.parse(r.data).events||[],A()}catch{}}),D.addEventListener("security",r=>{try{const c=JSON.parse(r.data);P.unshift(c),P.length>500&&(P.length=500);const d=h.querySelector(".sec-tab.active")?.dataset?.tab;d==="events"?A():d==="overview"&&B()}catch{}}),D.onerror=()=>{}}catch(r){console.warn("[security] SSE failed:",r.message)}}function w(){if(D){try{D.close()}catch{}D=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{h.classList.contains("show")&&T()});async function B(){try{const r=new Date(Date.now()-864e5).toISOString(),[c,d,x]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(r)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(r)}`)]),y=(await c.json()).data||{},t=(await d.json()).data?.hosts||[],e=(await x.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${y.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${y.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${y.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,E("sec-top-actors",y.top_actors||[]),E("sec-top-targets",y.top_targets||[])}catch(r){console.warn("[security] refreshOverview failed:",r.message)}}function E(r,c){const d=document.getElementById(r);if(!c.length){d.innerHTML='<div class="panel-empty">No data</div>';return}d.innerHTML='<table style="width:100%;font-size:0.85rem;">'+c.map(x=>`<tr><td style="padding:3px 0;word-break:break-all;">${g(String(x.key))}</td><td style="text-align:right;color:var(--muted);">${x.count}</td></tr>`).join("")+"</table>"}const H=document.getElementById("sec-filter-source"),C=document.getElementById("sec-filter-severity"),v=document.getElementById("sec-filter-host"),O=document.getElementById("sec-filter-actor"),f=document.getElementById("sec-refresh-btn");[H,C,v].forEach(r=>r.addEventListener("change",z)),O.addEventListener("input",M(z,250)),f.addEventListener("click",z);async function z(){try{const r=new URLSearchParams;r.set("limit","200"),H.value&&r.set("source_type",H.value),C.value&&r.set("severity",C.value),v.value&&r.set("source_host",v.value),O.value&&r.set("actor_prefix",O.value),P=(await(await fetch(`/api/v1/security/events?${r}`)).json()).data.events||[],A(),(!v.options.length||v.options.length===1)&&await p()}catch(r){document.getElementById("sec-events-container").innerHTML='<div class="panel-empty">Load failed: '+g(r.message)+"</div>"}}function A(){const r=document.getElementById("sec-events-container");if(!P.length){r.innerHTML='<div class="panel-empty">No events</div>';return}r.innerHTML=P.slice(0,200).map(U).join("")}function U(r){const c=r.severity||"info",d={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",x=r.ts?new Date(r.ts).toLocaleTimeString():"",y=r.source_type||"",t=r.actor||"\u2014",e=r.target||"",s=r.action||"",n=r.outcome||"";return`<div class="sec-event-row" style="display:grid;grid-template-columns:84px 80px 1fr 1fr 100px 90px;gap:8px;padding:5px 8px;border-bottom:1px solid var(--border);font-size:0.82rem;align-items:center;">
<span style="color:${l};font-weight:600;">${b(c)}</span> <span style="color:${d};font-weight:600;">${g(c)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${b(m)}</span> <span style="color:var(--muted);font-size:0.75rem;">${g(y)}</span>
<span title="${b(n)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${b(n)}</span> <span title="${g(t)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${g(t)}</span>
<span title="${b(e)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${b(t)} ${b(e)}</span> <span title="${g(e)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${g(s)} ${g(e)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${b(o)}</span> <span style="color:var(--muted);font-size:0.75rem;">${g(n)}</span>
<span style="color:var(--muted);font-size:0.75rem;text-align:right;">${b(w)}</span> <span style="color:var(--muted);font-size:0.75rem;text-align:right;">${g(x)}</span>
</div>`}async function B(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],l=u.value;u.innerHTML='<option value="">All hosts</option>'+c.map(w=>`<option value="${b(w.id)}">${b(w.label||w.id)}</option>`).join(""),l&&(u.value=l)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",I),document.getElementById("sec-hosts-refresh").addEventListener("click",f);async function f(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];P=c;const l=document.getElementById("sec-hosts-container");if(!c.length){l.innerHTML='<div class="panel-empty">No hosts registered. Click \u2795 Register Host to add one.</div>';return}l.innerHTML=c.map(w=>{const m=w.enabled?w.last_seen_at?Date.now()-Date.parse(w.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`<div style="padding:10px 12px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;"> </div>`}async function p(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],d=v.value;v.innerHTML='<option value="">All hosts</option>'+c.map(x=>`<option value="${g(x.id)}">${g(x.label||x.id)}</option>`).join(""),d&&(v.value=d)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",b),document.getElementById("sec-hosts-refresh").addEventListener("click",u);async function u(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];N=c;const d=document.getElementById("sec-hosts-container");if(!c.length){d.innerHTML='<div class="panel-empty">No hosts registered. Click \u2795 Register Host to add one.</div>';return}d.innerHTML=c.map(x=>{const y=x.enabled?x.last_seen_at?Date.now()-Date.parse(x.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`<div style="padding:10px 12px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
<div> <div>
<strong>${b(w.label||w.id)}</strong> <strong>${g(x.label||x.id)}</strong>
<span style="color:var(--muted);margin-left:8px;font-size:0.8rem;">${b(w.type)}</span> <span style="color:var(--muted);margin-left:8px;font-size:0.8rem;">${g(x.type)}</span>
<div style="color:var(--muted);font-size:0.78rem;margin-top:2px;"> <div style="color:var(--muted);font-size:0.78rem;margin-top:2px;">
id: ${b(w.id)} \xB7 id: ${g(x.id)} \xB7
registered ${new Date(w.registered_at).toLocaleDateString()} \xB7 registered ${new Date(x.registered_at).toLocaleDateString()} \xB7
last seen ${w.last_seen_at?new Date(w.last_seen_at).toLocaleString():"never"} last seen ${x.last_seen_at?new Date(x.last_seen_at).toLocaleString():"never"}
</div> </div>
</div> </div>
<div> <div>
<span style="font-size:0.85rem;margin-right:12px;">${m}</span> <span style="font-size:0.85rem;margin-right:12px;">${y}</span>
${w.id==="self"?"":`<button class="btn-sm sec-host-del" data-id="${b(w.id)}" style="color:var(--bad-fg);">Remove</button>`} ${x.id==="self"?"":`<button class="btn-sm sec-host-del" data-id="${g(x.id)}" style="color:var(--bad-fg);">Remove</button>`}
</div> </div>
</div>`}).join(""),l.querySelectorAll(".sec-host-del").forEach(w=>{w.addEventListener("click",async()=>{confirm(`Remove host ${w.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(w.dataset.id)}`,{method:"DELETE"}),f())})})}catch(i){document.getElementById("sec-hosts-container").innerHTML='<div class="panel-empty">Load failed: '+b(i.message)+"</div>"}}async function I(){const i=prompt("Host id (lowercase, no spaces):");if(!i)return;const c=prompt("Display label:",i)||i,l=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const w=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,label:c,type:l})}),m=await w.json();if(!w.ok){alert("Failed: "+(m?.error?.message||w.statusText));return}alert(`\u2705 Host registered! </div>`}).join(""),d.querySelectorAll(".sec-host-del").forEach(x=>{x.addEventListener("click",async()=>{confirm(`Remove host ${x.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(x.dataset.id)}`,{method:"DELETE"}),u())})})}catch(r){document.getElementById("sec-hosts-container").innerHTML='<div class="panel-empty">Load failed: '+g(r.message)+"</div>"}}async function b(){const r=prompt("Host id (lowercase, no spaces):");if(!r)return;const c=prompt("Display label:",r)||r,d=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const x=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:r,label:c,type:d})}),y=await x.json();if(!x.ok){alert("Failed: "+(y?.error?.message||x.statusText));return}alert(`\u2705 Host registered!
id: ${m.data.host.id} id: ${y.data.host.id}
label: ${m.data.host.label} label: ${y.data.host.label}
type: ${m.data.host.type} type: ${y.data.host.type}
\u{1F511} API KEY (save this NOW \u2014 won't be shown again): \u{1F511} API KEY (save this NOW \u2014 won't be shown again):
${m.data.api_key} ${y.data.api_key}
Send this key as: Authorization: Bearer <api_key> Send this key as: Authorization: Bearer <api_key>
To endpoint: POST /api/v1/security/events/ingest or /events/batch`),f()}catch(w){alert("Failed: "+w.message)}}function b(i){return String(i).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}function z(i,c){let l;return function(){clearTimeout(l),l=setTimeout(()=>i.apply(this,arguments),c)}}})(),(function(){const y=new ErrorHandler;injectModal("weather-modal",`<div id="weather-modal" class="weather-modal"><div class="weather-modal-content"><h3>Weather Settings</h3> To endpoint: POST /api/v1/security/events/ingest or /events/batch`),u()}catch(x){alert("Failed: "+x.message)}}function g(r){return String(r).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}function M(r,c){let d;return function(){clearTimeout(d),d=setTimeout(()=>r.apply(this,arguments),c)}}})(),(function(){const h=new ErrorHandler;injectModal("weather-modal",`<div id="weather-modal" class="weather-modal"><div class="weather-modal-content"><h3>Weather Settings</h3>
<label for="weather-location-input">Location:</label> <label for="weather-location-input">Location:</label>
<input type="text" id="weather-location-input" placeholder="City name or ZIP (e.g., Hamburg, 90210)" maxlength="100"> <input type="text" id="weather-location-input" placeholder="City name or ZIP (e.g., Hamburg, 90210)" maxlength="100">
<div style="font-size: 0.78rem; color: var(--muted); margin-top: 4px;">Enter a city name, postal code, or &ldquo;City, Country&rdquo;</div> <div style="font-size: 0.78rem; color: var(--muted); margin-top: 4px;">Enter a city name, postal code, or &ldquo;City, Country&rdquo;</div>
@@ -1817,23 +1809,23 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),f()}catch(w)
<label class="weather-unit-option"><input type="radio" name="weather-unit-radio" value="metric"><span class="weather-unit-card">&deg;C / km/h</span></label> <label class="weather-unit-option"><input type="radio" name="weather-unit-radio" value="metric"><span class="weather-unit-card">&deg;C / km/h</span></label>
</div> </div>
</div> </div>
<div class="weather-modal-buttons"><button id="weather-cancel">Cancel</button><button id="weather-save">Save</button></div></div></div>`);const C="weather-location",O="weather-zip",E="weather-geo",M="weather-unit";!safeGet(C)&&safeGet(O)&&safeSet(C,safeGet(O));function R(){return safeGet(M)||"imperial"}function P(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const A={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},p={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},T=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function x(v){return T[Math.round(v/22.5)%16]}async function $(v){const N=safeGet(E);if(N)try{const I=JSON.parse(N);if(I.query===v)return I}catch{}const g=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(v)}&count=1&language=en&format=json`);if(!g.ok)throw new Error("Geocoding failed");const D=await g.json();if(!D.results||!D.results.length)throw new Error("Location not found");const B=D.results[0],f={query:v,lat:B.latitude,lon:B.longitude,city:B.name,state:B.admin1||"",country:B.country||"",countryCode:B.country_code||""};return safeSet(E,JSON.stringify(f)),f}function k(v){return v.countryCode==="US"&&v.state?`${v.city}, ${v.state}`:v.country?`${v.city}, ${v.country}`:v.city}async function H(v){try{const N=await $(v),g=R(),D=g==="metric"?"celsius":"fahrenheit",B=g==="metric"?"kmh":"mph",f=`https://api.open-meteo.com/v1/forecast?latitude=${N.lat}&longitude=${N.lon}&current=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${D}&wind_speed_unit=${B}`,I=await fetch(f);if(!I.ok)throw new Error("Weather fetch failed");const z=(await I.json()).current,i=z.weather_code;return{temp:Math.round(z.temperature_2m),condition:A[i]||"Unknown",icon:p[i]||"\u{1F324}\uFE0F",locationStr:k(N),windSpeed:Math.round(z.wind_speed_10m),windDir:x(z.wind_direction_10m),unit:g}}catch(N){return console.warn("Weather fetch failed:",N),null}}async function L(){const v=P();if(!v.icon||!v.temp||!v.condition||!v.location||!v.wind){console.warn("Weather widget elements not found");return}const N=safeGet(C);if(!N){v.location.textContent="Set Location",v.temp.textContent="--\xB0",v.condition.textContent="Click \u2699\uFE0F to configure",v.wind.textContent="--",v.icon.innerHTML='<span class="weather-emoji">\u{1F324}\uFE0F</span>';return}try{const g=await H(N);if(g){const D=g.unit==="metric"?"\xB0C":"\xB0F",B=g.unit==="metric"?"km/h":"mph";v.location.textContent=g.locationStr,v.temp.textContent=`${g.temp}${D}`,v.condition.textContent=g.condition,v.wind.textContent=`Wind: ${g.windSpeed} ${B} ${g.windDir}`,v.icon.innerHTML=`<span class="weather-emoji">${escapeHtml(g.icon)}</span>`}}catch(g){y.logError("[Weather] Update Error",g,{function:"updateWeather"}),v.location.textContent="Weather Error",v.temp.textContent="Error",v.condition.textContent="Failed to load",v.wind.textContent="--"}}const u=document.getElementById("weather-modal"),j=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{j.value=safeGet(C)||"";const v=R(),N=u.querySelector(`input[name="weather-unit-radio"][value="${v}"]`);N&&(N.checked=!0),u.classList.add("show"),j.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{u.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const v=j.value.trim();if(v){safeGet(C)!==v&&safeSet(E,""),safeSet(C,v);const g=u.querySelector('input[name="weather-unit-radio"]:checked'),D=g?g.value:"imperial",B=R();safeSet(M,D),B!==D&&safeSet(E,""),u.classList.remove("show"),L()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(u),document.addEventListener("keydown",v=>{v.keyLine truncated <div class="weather-modal-buttons"><button id="weather-cancel">Cancel</button><button id="weather-save">Save</button></div></div></div>`);const L="weather-location",R="weather-zip",S="weather-geo",$="weather-unit";!safeGet(L)&&safeGet(R)&&safeSet(L,safeGet(R));function P(){return safeGet($)||"imperial"}function N(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const D={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},m={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},T=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function w(f){return T[Math.round(f/22.5)%16]}async function B(f){const z=safeGet(S);if(z)try{const b=JSON.parse(z);if(b.query===f)return b}catch{}const A=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(f)}&count=1&language=en&format=json`);if(!A.ok)throw new Error("Geocoding failed");const U=await A.json();if(!U.results||!U.results.length)throw new Error("Location not found");const p=U.results[0],u={query:f,lat:p.latitude,lon:p.longitude,city:p.name,state:p.admin1||"",country:p.country||"",countryCode:p.country_code||""};return safeSet(S,JSON.stringify(u)),u}function E(f){return f.countryCode==="US"&&f.state?`${f.city}, ${f.state}`:f.country?`${f.city}, ${f.country}`:f.city}async function H(f){try{const z=await B(f),A=P(),U=A==="metric"?"celsius":"fahrenheit",p=A==="metric"?"kmh":"mph",u=`https://api.open-meteo.com/v1/forecast?latitude=${z.lat}&longitude=${z.lon}&current=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${U}&wind_speed_unit=${p}`,b=await fetch(u);if(!b.ok)throw new Error("Weather fetch failed");const M=(await b.json()).current,r=M.weather_code;return{temp:Math.round(M.temperature_2m),condition:D[r]||"Unknown",icon:m[r]||"\u{1F324}\uFE0F",locationStr:E(z),windSpeed:Math.round(M.wind_speed_10m),windDir:w(M.wind_direction_10m),unit:A}}catch(z){return console.warn("Weather fetch failed:",z),null}}async function C(){const f=N();if(!f.icon||!f.temp||!f.condition||!f.location||!f.wind){console.warn("Weather widget elements not found");return}const z=safeGet(L);if(!z){f.location.textContent="Set Location",f.temp.textContent="--\xB0",f.condition.textContent="Click \u2699\uFE0F to configure",f.wind.textContent="--",f.icon.innerHTML='<span class="weather-emoji">\u{1F324}\uFE0F</span>';return}try{const A=await H(z);if(A){const U=A.unit==="metric"?"\xB0C":"\xB0F",p=A.unit==="metric"?"km/h":"mph";f.location.textContent=A.locationStr,f.temp.textContent=`${A.temp}${U}`,f.condition.textContent=A.condition,f.wind.textContent=`Wind: ${A.windSpeed} ${p} ${A.windDir}`,f.icon.innerHTML=`<span class="weather-emoji">${escapeHtml(A.icon)}</span>`}}catch(A){h.logError("[Weather] Update Error",A,{function:"updateWeather"}),f.location.textContent="Weather Error",f.temp.textContent="Error",f.condition.textContent="Failed to load",f.wind.textContent="--"}}const v=document.getElementById("weather-modal"),O=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{O.value=safeGet(L)||"";const f=P(),z=v.querySelector(`input[name="weather-unit-radio"][value="${f}"]`);z&&(z.checked=!0),v.classList.add("show"),O.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{v.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const f=O.value.trim();if(f){safeGet(L)!==f&&safeSet(S,""),safeSet(L,f);const A=v.querySelector('input[name="weather-unit-radio"]:checked'),U=A?A.value:"imperial",p=P();safeSet($,U),p!==U&&safeSet(S,""),v.classList.remove("show"),C()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(v),document.addEventListener("keydown",f=>{f.keyLine truncated
<circle cx="${s}" cy="${d}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/> <circle cx="${o}" cy="${l}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/>
${F} ${F}
${_} ${_}
<line x1="${s}" y1="${d}" x2="${s+28*Math.cos(U*Math.PI/180)}" y2="${d+28*Math.sin(U*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/> <line x1="${o}" y1="${l}" x2="${o+28*Math.cos(j*Math.PI/180)}" y2="${l+28*Math.sin(j*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/>
<line x1="${s}" y1="${d}" x2="${s+38*Math.cos(h*Math.PI/180)}" y2="${d+38*Math.sin(h*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/> <line x1="${o}" y1="${l}" x2="${o+38*Math.cos(I*Math.PI/180)}" y2="${l+38*Math.sin(I*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/>
<line x1="${s}" y1="${d}" x2="${s+42*Math.cos(S*Math.PI/180)}" y2="${d+42*Math.sin(S*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/> <line x1="${o}" y1="${l}" x2="${o+42*Math.cos(k*Math.PI/180)}" y2="${l+42*Math.sin(k*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/>
<circle cx="${s}" cy="${d}" r="3" fill="var(--fg)"/> <circle cx="${o}" cy="${l}" r="3" fill="var(--fg)"/>
</svg>`,J=n.getHours()>=12?"PM":"AM";C.innerHTML=`<div class="analog-clock-wrap">${W}<div class="analog-info"><span class="analog-digital">${n.getHours()%12||12}:${String(o).padStart(2,"0")} ${J}</span><span class="analog-date-sm">${H(n)}</span></div></div>`,T="analog"}function f(){const n=new Date,e=n.getHours()%12||12,t=n.getMinutes(),o=n.getSeconds(),r="clock-widget"+(R!=="default"?" "+R:"");switch(y.className!==r&&(y.className=r),R){case"lcd":v(n);break;case"lcd-blue":v(n);break;case"lcd-amber":v(n);break;case"lcd-retro":v(n);break;case"lcd-taxi":v(n);break;case"flip":N(n);break;case"binary":D(n);break;case"analog":B(n,!1);break;case"roman":B(n,!0);break;default:j(n)}t===0&&o===0&&e!==P&&(P=e,k(e)),t!==0&&(P=-1)}function I(){clearTimeout($);const n=document.hidden?6e4:1e3,e=n-Date.now()%n+25;$=setTimeout(()=>{f(),I()},e)}document.addEventListener("visibilitychange",()=>{p="",L(),f(),I()}),f(),I();const b=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let z='<div class="clock-style-grid">';b.forEach(n=>{z+=`<label class="clock-style-option"> </svg>`,G=t.getHours()>=12?"PM":"AM";L.innerHTML=`<div class="analog-clock-wrap">${q}<div class="analog-info"><span class="analog-digital">${t.getHours()%12||12}:${String(n).padStart(2,"0")} ${G}</span><span class="analog-date-sm">${H(t)}</span></div></div>`,T="analog"}function u(){const t=new Date,e=t.getHours()%12||12,s=t.getMinutes(),n=t.getSeconds(),i="clock-widget"+(P!=="default"?" "+P:"");switch(h.className!==i&&(h.className=i),P){case"lcd":f(t);break;case"lcd-blue":f(t);break;case"lcd-amber":f(t);break;case"lcd-retro":f(t);break;case"lcd-taxi":f(t);break;case"flip":z(t);break;case"binary":U(t);break;case"analog":p(t,!1);break;case"roman":p(t,!0);break;default:O(t)}s===0&&n===0&&e!==N&&(N=e,E(e)),s!==0&&(N=-1)}function b(){clearTimeout(B);const t=document.hidden?6e4:1e3,e=t-Date.now()%t+25;B=setTimeout(()=>{u(),b()},e)}document.addEventListener("visibilitychange",()=>{m="",C(),u(),b()}),u(),b();const g=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let M='<div class="clock-style-grid">';g.forEach(t=>{M+=`<label class="clock-style-option">
<input type="radio" name="clock-style-radio" value="${n.id}"> <input type="radio" name="clock-style-radio" value="${t.id}">
<span class="clock-style-card"><span class="clock-style-icon">${n.icon}</span><span class="clock-style-label">${n.label}</span></span> <span class="clock-style-card"><span class="clock-style-icon">${t.icon}</span><span class="clock-style-label">${t.label}</span></span>
</label>`}),z+="</div>",injectModal("clock-settings-modal",`<div id="clock-settings-modal" class="weather-modal"> </label>`}),M+="</div>",injectModal("clock-settings-modal",`<div id="clock-settings-modal" class="weather-modal">
<div class="weather-modal-content" style="max-width: 420px;"> <div class="weather-modal-content" style="max-width: 420px;">
<h3>Clock Settings</h3> <h3>Clock Settings</h3>
<div style="margin-bottom: 16px;"> <div style="margin-bottom: 16px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--fg);">Style</label> <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--fg);">Style</label>
${z} ${M}
</div> </div>
<div style="margin-bottom: 16px; padding-top: 12px; border-top: 1px solid var(--border);"> <div style="margin-bottom: 16px; padding-top: 12px; border-top: 1px solid var(--border);">
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; color: var(--fg);"> <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; color: var(--fg);">
@@ -1857,7 +1849,7 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),f()}catch(w)
<button id="clock-settings-save">Save</button> <button id="clock-settings-save">Save</button>
</div> </div>
</div> </div>
</div>`);const i=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),l=document.getElementById("clock-chime-volume"),w=document.getElementById("clock-volume-section");function m(){const n=safeGet("clock-style")||"default",e=i.querySelector(`input[value="${n}"]`);e&&(e.checked=!0),c.checked=safeGet("clock-chimes")==="true",l.value=safeGet("clock-chime-volume")||"50",w.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{w.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{m(),i.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const n=parseInt(l.value,10)/100,e=new Audio("/assets/sounds/church-bell.mp3");e.volume=n,e.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const n=i.querySelector('input[name="clock-style-radio"]:checked'),e=n?n.value:"default";safeSet("clock-style",e),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",l.value),R=e,p="",L(),f(),I(),i.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{i.classList.remove("show")}),wireModal(i),i?.querySelectorAll('input[name="clock-style-radio"]').forEach(n=>{n.addEventListener("change",()=>{R=n.value,p="",L(),f()})})})(),(function(){async function y(){try{const A=await(await fetch("/api/v1/health-checks/status")).json();if(!A.success||!A.status)return;for(const[p,T]of Object.entries(A.status)){const x=document.getElementById("uptime-"+p),$=document.getElementById("uptime-bar-"+p);if(!x)continue;const k=T.uptime?.["24h"];if(k!=null){const H=k.toFixed(1);x.textContent=`${H}% uptime`,x.className="uptime-chip",k>=99.9?x.classList.add("excellent"):k>=99?x.classList.add("good"):k>=95?x.classList.add("degraded"):x.classList.add("poor"),$&&($.style.width=H+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let C;try{C=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{C=new Set}let O=[];async function E(P){try{const p=await(await fetch("/api/v1/updates/available")).json();if(!p.success)return;document.querySelectorAll(".update-available-badge").forEach(x=>x.classList.remove("visible"));const T=p.updates||[];if(O=T,P&&T.length>0){const x=window._lastKnownUpdateCount||0;x>0&&T.length>x&&showNotification(`${T.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=T.length}if(!T.length)return;for(const x of T){const $=window.APPS||[];for(const k of $)if(k.containerId===x.containerId||k.id===x.containerName||k.name===x.containerName){if(C.has(k.id))break;const H=document.getElementById("update-badge-"+k.id),L=document.getElementById("update-btn-"+k.id);H&&(H.classList.add("visible"),H.title="Update available \u2014 click to open Update Management.",H.style.cursor="pointer",H.onclick=u=>{u.stopPropagation(),window.openUpdateModal&&window.openUpdateModal(k.id)}),L&&(L.style.background="#f97316",L.style.borderColor="#f97316",L.style.boxShadow="0 0 6px #f9731688",L.title="Update available \u2014 click to open Update Management.");break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function M(){setTimeout(()=>{y(),E()},5e3),setInterval(()=>{y(),E(!0)},6e4)}const R=window.refreshAll;R&&(window.refreshAll=async function(){try{await R(),setTimeout(y,1e3)}catch(P){console.warn("[Card Badges] Error in refreshAll hook:",P.message)}}),M()})(),(function(){var y=null,C=null,O={},E={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},M=[["bg","Background","base"],["card-base","Card","base"],["fg","Text","base"],["muted","Muted Text","base"],["border","Border","base"],["accent","Accent","accent"],["accent-strong","Accent Strong","accent"],["ok-bg","OK Background","status"],["ok-fg","OK Text","status"],["bad-bg","Error Bg","status"],["bad-fg","Error Text","status"],["dot-ok","Dot OK","status"],["dot-bad","Dot Error","status"],["uptime","Uptime Bar","status"],["hover","Hover","advanced"],["card-hover","Card Hover","advanced"],["base","Tags/Badges","advanced"],["fg-muted","Dim Text","advanced"],["success","Success","advanced"],["error","Error","advanced"],["warning","Warning","advanced"]],R=document.getElementById("theme");if(!R)return;var P=document.getElementById("theme-label");function A(o){if(E[o])return E[o];var r=safeGetJSON(window.USER_THEMES_KEY,{});return r[o]&&r[o].name||o}function p(){P&&(P.textContent=A(window.getActiveTheme()))}R.addEventListener("click",function(){var o=window.THEMES.slice(),r=window.getActiveTheme(),a=o.indexOf(r),s=o[(a+1)%o.length];window.applyTheme(s),p()}),p();function T(){var o={base:"Base Colors",accent:"Accent",status:"Status",advanced:"Advanced (auto-deriLine truncated </div>`);const r=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),d=document.getElementById("clock-chime-volume"),x=document.getElementById("clock-volume-section");function y(){const t=safeGet("clock-style")||"default",e=r.querySelector(`input[value="${t}"]`);e&&(e.checked=!0),c.checked=safeGet("clock-chimes")==="true",d.value=safeGet("clock-chime-volume")||"50",x.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{x.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{y(),r.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const t=parseInt(d.value,10)/100,e=new Audio("/assets/sounds/church-bell.mp3");e.volume=t,e.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const t=r.querySelector('input[name="clock-style-radio"]:checked'),e=t?t.value:"default";safeSet("clock-style",e),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",d.value),P=e,m="",C(),u(),b(),r.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{r.classList.remove("show")}),wireModal(r),r?.querySelectorAll('input[name="clock-style-radio"]').forEach(t=>{t.addEventListener("change",()=>{P=t.value,m="",C(),u()})})})(),(function(){async function h(){try{const D=await(await fetch("/api/v1/health-checks/status")).json();if(!D.success||!D.status)return;for(const[m,T]of Object.entries(D.status)){const w=document.getElementById("uptime-"+m),B=document.getElementById("uptime-bar-"+m);if(!w)continue;const E=T.uptime?.["24h"];if(E!=null){const H=E.toFixed(1);w.textContent=`${H}% uptime`,w.className="uptime-chip",E>=99.9?w.classList.add("excellent"):E>=99?w.classList.add("good"):E>=95?w.classList.add("degraded"):w.classList.add("poor"),B&&(B.style.width=H+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let L;try{L=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{L=new Set}let R=[];async function S(N){try{const m=await(await fetch("/api/v1/updates/available")).json();if(!m.success)return;document.querySelectorAll(".update-available-badge").forEach(w=>w.classList.remove("visible"));const T=m.updates||[];if(R=T,N&&T.length>0){const w=window._lastKnownUpdateCount||0;w>0&&T.length>w&&showNotification(`${T.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=T.length}if(!T.length)return;for(const w of T){const B=window.APPS||[];for(const E of B)if(E.containerId===w.containerId||E.id===w.containerName||E.name===w.containerName){if(L.has(E.id))break;const H=document.getElementById("update-badge-"+E.id),C=document.getElementById("update-btn-"+E.id);H&&(H.classList.add("visible"),H.title="Update available \u2014 click to open Update Management.",H.style.cursor="pointer",H.onclick=v=>{v.stopPropagation(),window.openUpdateModal&&window.openUpdateModal(E.id)}),C&&(C.style.background="#f97316",C.style.borderColor="#f97316",C.style.boxShadow="0 0 6px #f9731688",C.title="Update available \u2014 click to open Update Management.");break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function $(){setTimeout(()=>{h(),S()},5e3),setInterval(()=>{h(),S(!0)},6e4)}const P=window.refreshAll;P&&(window.refreshAll=async function(){try{await P(),setTimeout(h,1e3)}catch(N){console.warn("[Card Badges] Error in refreshAll hook:",N.message)}}),$()})(),(function(){var h=null,L=null,R={},S={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},$=[["bg","Background","base"],["card-base","Card","base"],["fg","Text","base"],["muted","Muted Text","base"],["border","Border","base"],["accent","Accent","accent"],["accent-strong","Accent Strong","accent"],["ok-bg","OK Background","status"],["ok-fg","OK Text","status"],["bad-bg","Error Bg","status"],["bad-fg","Error Text","status"],["dot-ok","Dot OK","status"],["dot-bad","Dot Error","status"],["uptime","Uptime Bar","status"],["hover","Hover","advanced"],["card-hover","Card Hover","advanced"],["base","Tags/Badges","advanced"],["fg-muted","Dim Text","advanced"],["success","Success","advanced"],["error","Error","advanced"],["warning","Warning","advanced"]],P=document.getElementById("theme");if(!P)return;var N=document.getElementById("theme-label");function D(n){if(S[n])return S[n];var i=safeGetJSON(window.USER_THEMES_KEY,{});return i[n]&&i[n].name||n}function m(){N&&(N.textContent=D(window.getActiveTheme()))}P.addEventListener("click",function(){var n=window.THEMES.slice(),i=window.getActiveTheme(),a=n.indexOf(i),o=n[(a+1)%n.length];window.applyTheme(o),m()}),m();function T(){var n={base:"Base Colors",accent:"Accent",status:"Status",advanced:"Advanced (auto-deriLine truncated
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;"> <div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3>DashCaddy License</h3> <h3>DashCaddy License</h3>
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;"> <p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
@@ -1894,16 +1886,16 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),f()}catch(w)
<button id="license-activate" class="btn-accent">Activate</button> <button id="license-activate" class="btn-accent">Activate</button>
</div> </div>
</div> </div>
</div>`);const y=document.getElementById("license-modal"),C=document.getElementById("license-code-input"),O=document.getElementById("license-activate"),E=document.getElementById("license-deactivate"),M=document.getElementById("license-error"),R=document.getElementById("license-success"),P=document.getElementById("license-badge-icon"),A=document.getElementById("license-badge-text"),p=document.getElementById("license-badge"),T=document.getElementById("license-details"),x=document.getElementById("license-feature-list"),$=document.getElementById("license-activate-section");let k=null;function H(){M.style.display="none",R.style.display="none"}function L(I){H(),M.textContent=I,M.style.display="block"}function u(I){H(),R.textContent=I,R.style.display="block"}function j(I){if(k=I,I.active){p.style.background="rgba(46,204,113,0.15)",p.style.color="var(--ok-fg)",P.textContent="\u2605",A.textContent="Premium Active";const i=I.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(I.expiresAt).toLocaleDateString()}</strong> (${I.daysRemaining} days remaining)</div>`;T.innerHTML=` </div>`);const h=document.getElementById("license-modal"),L=document.getElementById("license-code-input"),R=document.getElementById("license-activate"),S=document.getElementById("license-deactivate"),$=document.getElementById("license-error"),P=document.getElementById("license-success"),N=document.getElementById("license-badge-icon"),D=document.getElementById("license-badge-text"),m=document.getElementById("license-badge"),T=document.getElementById("license-details"),w=document.getElementById("license-feature-list"),B=document.getElementById("license-activate-section");let E=null;function H(){$.style.display="none",P.style.display="none"}function C(b){H(),$.textContent=b,$.style.display="block"}function v(b){H(),P.textContent=b,P.style.display="block"}function O(b){if(E=b,b.active){m.style.background="rgba(46,204,113,0.15)",m.style.color="var(--ok-fg)",N.textContent="\u2605",D.textContent="Premium Active";const r=b.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(b.expiresAt).toLocaleDateString()}</strong> (${b.daysRemaining} days remaining)</div>`;T.innerHTML=`
<div>Code: <code style="font-family: monospace;">${I.code||"***"}</code></div> <div>Code: <code style="font-family: monospace;">${b.code||"***"}</code></div>
${i} ${r}
`,$.style.display="none",O.style.display="none",E.style.display=""}else p.style.background="rgba(149,165,166,0.15)",p.style.color="var(--muted)",P.textContent="\u2606",A.textContent=I.expired?"License Expired":"Free Tier",T.innerHTML=I.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",$.style.display="",O.style.display="",E.style.display="none";const b=I.premiumFeatures||{},z=new Set(I.features||[]);x.innerHTML=Object.entries(b).map(([i,c])=>`<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border);"> `,B.style.display="none",R.style.display="none",S.style.display=""}else m.style.background="rgba(149,165,166,0.15)",m.style.color="var(--muted)",N.textContent="\u2606",D.textContent=b.expired?"License Expired":"Free Tier",T.innerHTML=b.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",B.style.display="",R.style.display="",S.style.display="none";const g=b.premiumFeatures||{},M=new Set(b.features||[]);w.innerHTML=Object.entries(g).map(([r,c])=>`<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${z.has(i)?"\u2705":"\u{1F512}"}</span> <span style="font-size: 1.1rem;">${M.has(r)?"\u2705":"\u{1F512}"}</span>
<div> <div>
<div style="font-weight: 600; font-size: 0.9rem;">${c.name}</div> <div style="font-weight: 600; font-size: 0.9rem;">${c.name}</div>
<div style="font-size: 0.78rem; color: var(--muted);">${c.description}</div> <div style="font-size: 0.78rem; color: var(--muted);">${c.description}</div>
</div> </div>
</div>`).join("")}async function v(){try{const b=await(await fetch("/api/v1/license/status")).json();b.success&&(j(b.license),D(b.license))}catch(I){console.warn("Failed to load license status:",I.message)}}async function N(){const I=C.value.trim();if(!I){L("Please enter a license code.");return}H(),O.disabled=!0,O.textContent="Activating...";try{const z=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:I})})).json();z.success?(u(z.message),C.value="",j(z.license),showNotification("License activated! Premium features unlocked.","success",5e3),D(z.license)):L(z.error||"Activation failed")}catch(b){L("Network error: "+b.message)}finally{O.disabled=!1,O.textContent="Activate"}}async function g(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){E.disabled=!0,E.textContent="Deactivating...";try{const b=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();b.success?(u(b.message),await v(),showNotification("License deactivated.","info",3e3),D({active:!1})):L(b.error||"Deactivation failed")}catch(I){L("Network error: "+I.message)}finally{E.disabled=!1,E.textContent="Deactivate"}}}function D(I){const b=document.getElementById("license-status-topbar"),z=document.getElementById("license-topbar-icon"),i=document.getElementById("license-topbar-text"),c=document.getElementById("license-topbar-time");if(b)if(b.className="license-status-topbar "+(I.active?"premium":"free"),I.active)if(z.textContent="\u2605",i.textContent="PREMIUM",I.lifetime)c.textContent="\xB7 LIFETIME";else{const l=I.daysRemaining;c.textContent=l!=null?"\xB7 "+l+"d remaining":""}else z.textContent="\u2606",i.textContent=I.expired?"EXPIRED":"FREE TIER",c.textContent=""}function B(){H(),v(),y.classList.add("show")}C.addEventListener("input",function(){let I=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(I.length>this._prevLength&&(I=I.replace(/-/g,""),I.length>2&&!I.startsWith("DC")&&(I="DC"+I),I.startsWith("DC")&&I.length>2)){const b=["DC"],z=I.substring(2);for(let i=0;i<z.length;i+=5)b.push(z.substring(i,i+5));I=b.join("-")}this._prevLength=I.length,this.value=I}),O.addEventListener("click",N),E.addEventListener("click",g),C.addEventListener("keydown",I=>{I.key==="Enter"&&N()}),wireModal(y,document.getElementById("license-cancel"));const f=document.getElementById("license-status-topbar");f&&f.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=B,window.checkPremiumFeature=async function(I){try{return(await(await fetch(`/api/v1/license/feature/${I}`)).json()).available}catch{return!1}},v().then(I=>{k&&D(k)})})(),(function(){"use strict";if(window.__dc_058_share_modal_loaded)return;window.__dc_058_share_modal_loaded=!0;const y=[{ms:3600*1e3,label:"1 hour"},{ms:1440*60*1e3,label:"24 hours"},{ms:10080*60*1e3,label:"7 days"}];injectModal("share-modal",` </div>`).join("")}async function f(){try{const g=await(await fetch("/api/v1/license/status")).json();g.success&&(O(g.license),U(g.license))}catch(b){console.warn("Failed to load license status:",b.message)}}async function z(){const b=L.value.trim();if(!b){C("Please enter a license code.");return}H(),R.disabled=!0,R.textContent="Activating...";try{const M=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:b})})).json();M.success?(v(M.message),L.value="",O(M.license),showNotification("License activated! Premium features unlocked.","success",5e3),U(M.license)):C(M.error||"Activation failed")}catch(g){C("Network error: "+g.message)}finally{R.disabled=!1,R.textContent="Activate"}}async function A(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){S.disabled=!0,S.textContent="Deactivating...";try{const g=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();g.success?(v(g.message),await f(),showNotification("License deactivated.","info",3e3),U({active:!1})):C(g.error||"Deactivation failed")}catch(b){C("Network error: "+b.message)}finally{S.disabled=!1,S.textContent="Deactivate"}}}function U(b){const g=document.getElementById("license-status-topbar"),M=document.getElementById("license-topbar-icon"),r=document.getElementById("license-topbar-text"),c=document.getElementById("license-topbar-time");if(g)if(g.className="license-status-topbar "+(b.active?"premium":"free"),b.active)if(M.textContent="\u2605",r.textContent="PREMIUM",b.lifetime)c.textContent="\xB7 LIFETIME";else{const d=b.daysRemaining;c.textContent=d!=null?"\xB7 "+d+"d remaining":""}else M.textContent="\u2606",r.textContent=b.expired?"EXPIRED":"FREE TIER",c.textContent=""}function p(){H(),f(),h.classList.add("show")}L.addEventListener("input",function(){let b=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(b.length>this._prevLength&&(b=b.replace(/-/g,""),b.length>2&&!b.startsWith("DC")&&(b="DC"+b),b.startsWith("DC")&&b.length>2)){const g=["DC"],M=b.substring(2);for(let r=0;r<M.length;r+=5)g.push(M.substring(r,r+5));b=g.join("-")}this._prevLength=b.length,this.value=b}),R.addEventListener("click",z),S.addEventListener("click",A),L.addEventListener("keydown",b=>{b.key==="Enter"&&z()}),wireModal(h,document.getElementById("license-cancel"));const u=document.getElementById("license-status-topbar");u&&u.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=p,window.checkPremiumFeature=async function(b){try{return(await(await fetch(`/api/v1/license/feature/${b}`)).json()).available}catch{return!1}},f().then(b=>{E&&U(E)})})(),(function(){"use strict";if(window.__dc_058_share_modal_loaded)return;window.__dc_058_share_modal_loaded=!0;const h=[{ms:3600*1e3,label:"1 hour"},{ms:1440*60*1e3,label:"24 hours"},{ms:10080*60*1e3,label:"7 days"}];injectModal("share-modal",`
<div id="share-modal" class="weather-modal" role="dialog" aria-labelledby="share-modal-title"> <div id="share-modal" class="weather-modal" role="dialog" aria-labelledby="share-modal-title">
<div class="weather-modal-content" style="min-width: 460px; max-width: 580px;"> <div class="weather-modal-content" style="min-width: 460px; max-width: 580px;">
<h3 id="share-modal-title">Share <span id="share-modal-service-name">\u2026</span></h3> <h3 id="share-modal-title">Share <span id="share-modal-service-name">\u2026</span></h3>
@@ -1925,7 +1917,7 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),f()}catch(w)
<div class="share-tab-panel" data-panel="public"> <div class="share-tab-panel" data-panel="public">
<label class="form-label-bold" for="share-public-ttl">Link duration:</label> <label class="form-label-bold" for="share-public-ttl">Link duration:</label>
<select id="share-public-ttl" style="width: 100%; padding: 8px 10px; margin: 6px 0 12px; background: var(--input-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;"> <select id="share-public-ttl" style="width: 100%; padding: 8px 10px; margin: 6px 0 12px; background: var(--input-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;">
${y.map(n=>`<option value="${n.ms}">${n.label}</option>`).join("")} ${h.map(t=>`<option value="${t.ms}">${t.label}</option>`).join("")}
</select> </select>
<button id="share-public-create" class="btn-accent" type="button" <button id="share-public-create" class="btn-accent" type="button"
style="width: 100%; padding: 10px; background: var(--accent); color: #04141f; border: 0; border-radius: 4px; font-weight: 600; cursor: pointer;"> style="width: 100%; padding: 10px; background: var(--accent); color: #04141f; border: 0; border-radius: 4px; font-weight: 600; cursor: pointer;">
@@ -1972,17 +1964,17 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),f()}catch(w)
</div> </div>
</div> </div>
</div> </div>
`);const C=document.getElementById("share-modal"),O=document.getElementById("share-modal-service-name"),E=document.getElementById("share-issued"),M=document.getElementById("share-issued-url"),R=document.getElementById("share-issued-copy"),P=document.getElementById("share-issued-meta"),A=document.getElementById("share-error"),p=document.getElementById("share-success"),T=document.getElementById("share-outstanding-list"),x=document.getElementById("share-cancel"),$=document.getElementById("share-public-create"),k=document.getElementById("share-ts-create"),H=document.getElementById("share-ts-email"),L=document.getElementById("share-public-ttl");let u=null,j="public";function v(){A.style.display="none",p.style.display="none",E.style.display="none"}function N(n){p.style.display="none",E.style.display="none",A.textContent=n,A.style.display="block"}function g(n){A.style.display="none",p.textContent=n,p.style.display="block"}function D(){return window.location.origin}function B(n){return n.startsWith("http")?n:D()+n}function f(n){if(!n)return"";const e=new Date(n);return Number.isNaN(e.getTime())?"":e.toLocaleString()}function I(n){if(n<=0)return"expired";const e=Math.floor(n/36e5);if(e>=24)return`${Math.floor(e/24)}d ${e%24}h left`;const t=Math.floor(n%36e5/6e4);return`${e}h ${t}m left`}function b(n){j=n,v(),C.querySelectorAll(".share-tab").forEach(e=>{const t=e.dataset.tab===n;e.classList.toggle("active",t),e.style.borderBottomColor=t?"var(--accent)":"transparent",e.style.color=t?"var(--fg)":"var(--muted)",e.style.fontWeight=t?"600":"400"}),C.querySelectorAll(".share-tab-panel").forEach(e=>{e.style.display=e.dataset.panel===n?"":"none"})}async function z(){T.innerHTML='<span style="color: var(--muted);">Loading\u2026</span>';try{const n=await fetch("/api/v1/share",{credentials:"same-origin"});if(!n.ok){T.innerHTML='<span style="color: var(--muted);">No shares listed.</span>';return}const e=await n.json(),o=(e&&e.data||[]).filter(r=>r.serviceId===u.id);if(o.length===0){T.innerHTML='<span style="color: var(--muted);">No outstanding shares for this service.</span>';return}T.innerHTML=o.map(r=>{const a=r.expiresAt?I(new Date(r.expiresAt).getTime()-Date.now()):"";return` `);const L=document.getElementById("share-modal"),R=document.getElementById("share-modal-service-name"),S=document.getElementById("share-issued"),$=document.getElementById("share-issued-url"),P=document.getElementById("share-issued-copy"),N=document.getElementById("share-issued-meta"),D=document.getElementById("share-error"),m=document.getElementById("share-success"),T=document.getElementById("share-outstanding-list"),w=document.getElementById("share-cancel"),B=document.getElementById("share-public-create"),E=document.getElementById("share-ts-create"),H=document.getElementById("share-ts-email"),C=document.getElementById("share-public-ttl");let v=null,O="public";function f(){D.style.display="none",m.style.display="none",S.style.display="none"}function z(t){m.style.display="none",S.style.display="none",D.textContent=t,D.style.display="block"}function A(t){D.style.display="none",m.textContent=t,m.style.display="block"}function U(){return window.location.origin}function p(t){return t.startsWith("http")?t:U()+t}function u(t){if(!t)return"";const e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleString()}function b(t){if(t<=0)return"expired";const e=Math.floor(t/36e5);if(e>=24)return`${Math.floor(e/24)}d ${e%24}h left`;const s=Math.floor(t%36e5/6e4);return`${e}h ${s}m left`}function g(t){O=t,f(),L.querySelectorAll(".share-tab").forEach(e=>{const s=e.dataset.tab===t;e.classList.toggle("active",s),e.style.borderBottomColor=s?"var(--accent)":"transparent",e.style.color=s?"var(--fg)":"var(--muted)",e.style.fontWeight=s?"600":"400"}),L.querySelectorAll(".share-tab-panel").forEach(e=>{e.style.display=e.dataset.panel===t?"":"none"})}async function M(){T.innerHTML='<span style="color: var(--muted);">Loading\u2026</span>';try{const t=await fetch("/api/v1/share",{credentials:"same-origin"});if(!t.ok){T.innerHTML='<span style="color: var(--muted);">No shares listed.</span>';return}const e=await t.json(),n=(e&&e.data||[]).filter(i=>i.serviceId===v.id);if(n.length===0){T.innerHTML='<span style="color: var(--muted);">No outstanding shares for this service.</span>';return}T.innerHTML=n.map(i=>{const a=i.expiresAt?b(new Date(i.expiresAt).getTime()-Date.now()):"";return`
<div class="share-row" data-share-id="${escapeHtml(r.id)}" <div class="share-row" data-share-id="${escapeHtml(i.id)}"
style="display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px dashed var(--border);"> style="display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px dashed var(--border);">
<span style="flex: 1;"> <span style="flex: 1;">
<strong>${r.kind==="tailscale"?"Tailscale":"Public"}</strong> <strong>${i.kind==="tailscale"?"Tailscale":"Public"}</strong>
<span style="color: var(--muted);"> \xB7 expires ${escapeHtml(f(r.expiresAt))} (${a})</span> <span style="color: var(--muted);"> \xB7 expires ${escapeHtml(u(i.expiresAt))} (${a})</span>
</span> </span>
<button class="share-revoke" data-share-id="${escapeHtml(r.id)}" type="button" <button class="share-revoke" data-share-id="${escapeHtml(i.id)}" type="button"
style="padding: 4px 10px; background: transparent; color: var(--bad-fg); border: 1px solid var(--bad-fg); border-radius: 4px; cursor: pointer; font-size: 0.8rem;"> style="padding: 4px 10px; background: transparent; color: var(--bad-fg); border: 1px solid var(--bad-fg); border-radius: 4px; cursor: pointer; font-size: 0.8rem;">
Revoke Revoke
</button> </button>
</div> </div>
`}).join(""),T.querySelectorAll(".share-revoke").forEach(r=>{r.addEventListener("click",()=>i(r.dataset.shareId))})}catch{T.innerHTML='<span style="color: var(--muted);">Could not load outstanding shares.</span>'}}async function i(n){try{const e=await fetch(`/api/v1/share/${encodeURIComponent(n)}`,{method:"DELETE",credentials:"same-origin"});if(!e.ok){const t=await e.json().catch(()=>({}));N(t&&t.error||`Revoke failed (HTTP ${e.status}).`);return}g("Share revoked."),z()}catch{N("Network error while revoking.")}}async function c(){if(!u)return;v(),$.disabled=!0;const n=$.textContent;$.textContent="Creating\u2026";try{const e=parseInt(L.value,10),t=await fetch("/api/v1/share",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:u.id,ttlMs:e})}),o=await t.json().catch(()=>({}));if(!t.ok||!o.success){w(t.status,o);return}const r=o.data.urlPath;M.value=B(r),P.textContent=`Public link \xB7 expires ${f(o.data.expiresAt)}`,E.style.display="block",g("Share link created."),z()}catch{N("Network error while creating share.")}finally{$.disabled=!1,$.textContent=n}}async function l(){if(!u)return;const n=(H.value||"").trim();if(!n||!n.includes("@")){N("A valid recipient email is required.");return}v(),k.disabled=!0;const e=k.textContent;k.textContent="Creating\u2026";try{const t=await fetch("/api/v1/share/tailscale",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:u.id,email:n})}),o=await t.json().catch(()=>({}));if(!t.ok||!o.success){w(t.status,o);return}const r=o.data&&o.data.urlPath;r?(M.value=B(r),P.textContent=`Tailscale invite \xB7 emailed to ${n} (or use this URL manually if delivery failed).`):(M.value="",P.textContent=`Tailscale invite sent to ${n}.`),E.style.display="block",g("Tailscale invite created."),H.value="",z()}catch{N("Network error while creating Tailscale invite.")}finally{k.disabled=!1,k.textContent=e}}function w(n,e){const t=e&&e.error||"";if(n===402){N("Share is a Pro feature. Activate a license to unlock.");return}if(n===400&&/tailscale/i.test(t)){N("Tailscale is not configured on this host. Set up Tailscale in the dashboard first.");return}if(n===403){N("You do not have permission to share services.");return}if(n===404){N("Service not found. It may have been deleted.");return}N(t||`Request failed (HTTP ${n}).`)}function m(n){!n||!n.id||(u={id:n.id,name:n.name||n.id},O.textContent=u.name,v(),b("public"),H.value="",L.value=String(y[1].ms),C.classList.add("show"),z())}C.querySelectorAll(".share-tab").forEach(n=>{n.addEventListener("click",()=>b(n.dataset.tab))}),$.addEventListener("click",c),k.addEventListener("click",l),x.addEventListener("click",()=>C.classList.remove("show")),wireModal(C,x),R.addEventListener("click",async()=>{const n=M.value;if(n)try{navigator.clipboard&&navigator.clipboard.writeText?await navigator.clipboard.writeText(n):(M.select(),document.execCommand("copy"));const e=R.textContent;R.textContent="Copied!",setTimeout(()=>{R.textContent=e},1200)}catch{N("Could not copy to clipboard. Select the URL manually.")}}),window.openShareModal=m})(),(function(){"use strict";const y="dashcaddy-language",O=["en","es","fr","de","ar"],E={en:"English",es:"Espa\xF1ol",fr:"Fran\xE7ais",de:"Deutsch",ar:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"};let M=localStorage.getItem(y)||"en",R={},P=!1;async function A(u){if(u==="en"){R={},P=!0;return}try{const j=await fetch(`/api/v1/i18n/translations/${u}`);j.ok&&(R=(await j.json()).translations||{},P=!0)}catch(j){console.warn("[i18n] Failed to load translations for",u,j)}}function p(u){return M==="en"?u:R[u]||u}function T(u){if(!O.includes(u))return;M=u,localStorage.setItem(y,u);const j=u==="ar";document.documentElement.dir=j?"rtl":"ltr",document.documentElement.lang=u,A(u).then(()=>{$()})}function x(){return M}function $(){document.querySelectorAll("[data-i18n]").forEach(u=>{const j=u.getAttribute("data-i18n"),v=p(j);v&&v!==j&&(u.textContent=v)}),document.querySelectorAll("[data-i18n-placeholder]").forEach(u=>{const j=u.getAttribute("data-i18n-placeholder"),v=p(j);v&&v!==j&&(u.placeholder=v)}),document.querySelectorAll("[data-i18n-title]").forEach(u=>{const j=u.getAttribute("data-i18n-title"),v=p(j);v&&v!==j&&(u.title=v)})}function k(){const u=document.querySelector(".header-actions")||document.querySelector("#auth-settings-btn")?.parentElement||document.querySelector(".top-bar-actions");if(!u){const j=document.getElementById("auth-settings-btn");return j&&j.parentElement?H(j.parentElement):null}return H(u)}function H(u){if(document.getElementById("dc-lang-selector"))return;const j=document.createElement("div");j.id="dc-lang-selector",j.style.cssText="display: inline-flex; align-items: center; gap: 4px; margin: 0 8px; position: relative;";const v=document.createElement("button");v.id="dc-lang-btn",v.className="lang-selector-btn",v.style.cssText="background: var(--card-base, #2a2a3e); border: 1px solid var(--border, Line truncated `}).join(""),T.querySelectorAll(".share-revoke").forEach(i=>{i.addEventListener("click",()=>r(i.dataset.shareId))})}catch{T.innerHTML='<span style="color: var(--muted);">Could not load outstanding shares.</span>'}}async function r(t){try{const e=await fetch(`/api/v1/share/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"});if(!e.ok){const s=await e.json().catch(()=>({}));z(s&&s.error||`Revoke failed (HTTP ${e.status}).`);return}A("Share revoked."),M()}catch{z("Network error while revoking.")}}async function c(){if(!v)return;f(),B.disabled=!0;const t=B.textContent;B.textContent="Creating\u2026";try{const e=parseInt(C.value,10),s=await fetch("/api/v1/share",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:v.id,ttlMs:e})}),n=await s.json().catch(()=>({}));if(!s.ok||!n.success){x(s.status,n);return}const i=n.data.urlPath;$.value=p(i),N.textContent=`Public link \xB7 expires ${u(n.data.expiresAt)}`,S.style.display="block",A("Share link created."),M()}catch{z("Network error while creating share.")}finally{B.disabled=!1,B.textContent=t}}async function d(){if(!v)return;const t=(H.value||"").trim();if(!t||!t.includes("@")){z("A valid recipient email is required.");return}f(),E.disabled=!0;const e=E.textContent;E.textContent="Creating\u2026";try{const s=await fetch("/api/v1/share/tailscale",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:v.id,email:t})}),n=await s.json().catch(()=>({}));if(!s.ok||!n.success){x(s.status,n);return}const i=n.data&&n.data.urlPath;i?($.value=p(i),N.textContent=`Tailscale invite \xB7 emailed to ${t} (or use this URL manually if delivery failed).`):($.value="",N.textContent=`Tailscale invite sent to ${t}.`),S.style.display="block",A("Tailscale invite created."),H.value="",M()}catch{z("Network error while creating Tailscale invite.")}finally{E.disabled=!1,E.textContent=e}}function x(t,e){const s=e&&e.error||"";if(t===402){z("Share is a Pro feature. Activate a license to unlock.");return}if(t===400&&/tailscale/i.test(s)){z("Tailscale is not configured on this host. Set up Tailscale in the dashboard first.");return}if(t===403){z("You do not have permission to share services.");return}if(t===404){z("Service not found. It may have been deleted.");return}z(s||`Request failed (HTTP ${t}).`)}function y(t){!t||!t.id||(v={id:t.id,name:t.name||t.id},R.textContent=v.name,f(),g("public"),H.value="",C.value=String(h[1].ms),L.classList.add("show"),M())}L.querySelectorAll(".share-tab").forEach(t=>{t.addEventListener("click",()=>g(t.dataset.tab))}),B.addEventListener("click",c),E.addEventListener("click",d),w.addEventListener("click",()=>L.classList.remove("show")),wireModal(L,w),P.addEventListener("click",async()=>{const t=$.value;if(t)try{navigator.clipboard&&navigator.clipboard.writeText?await navigator.clipboard.writeText(t):($.select(),document.execCommand("copy"));const e=P.textContent;P.textContent="Copied!",setTimeout(()=>{P.textContent=e},1200)}catch{z("Could not copy to clipboard. Select the URL manually.")}}),window.openShareModal=y})(),(function(){"use strict";const h="dashcaddy-language",R=["en","es","fr","de","ar"],S={en:"English",es:"Espa\xF1ol",fr:"Fran\xE7ais",de:"Deutsch",ar:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"};let $=localStorage.getItem(h)||"en",P={},N=!1;async function D(v){if(v==="en"){P={},N=!0;return}try{const O=await fetch(`/api/v1/i18n/translations/${v}`);O.ok&&(P=(await O.json()).translations||{},N=!0)}catch(O){console.warn("[i18n] Failed to load translations for",v,O)}}function m(v){return $==="en"?v:P[v]||v}function T(v){if(!R.includes(v))return;$=v,localStorage.setItem(h,v);const O=v==="ar";document.documentElement.dir=O?"rtl":"ltr",document.documentElement.lang=v,D(v).then(()=>{B()})}function w(){return $}function B(){document.querySelectorAll("[data-i18n]").forEach(v=>{const O=v.getAttribute("data-i18n"),f=m(O);f&&f!==O&&(v.textContent=f)}),document.querySelectorAll("[data-i18n-placeholder]").forEach(v=>{const O=v.getAttribute("data-i18n-placeholder"),f=m(O);f&&f!==O&&(v.placeholder=f)}),document.querySelectorAll("[data-i18n-title]").forEach(v=>{const O=v.getAttribute("data-i18n-title"),f=m(O);f&&f!==O&&(v.title=f)})}function E(){const v=document.querySelector(".header-actions")||document.querySelector("#auth-settings-btn")?.parentElement||document.querySelector(".top-bar-actions");if(!v){const O=document.getElementById("auth-settings-btn");return O&&O.parentElement?H(O.parentElement):null}return H(v)}function H(v){if(document.getElementById("dc-lang-selector"))return;const O=document.createElement("div");O.id="dc-lang-selector",O.style.cssText="display: inline-flex; align-items: center; gap: 4px; margin: 0 8px; position: relative;";const f=document.createElement("button");f.id="dc-lang-btn",f.className="lang-selector-btn",f.style.cssText="background: var(--card-base, #2a2a3e); border: 1px solid var(--border, Line truncated
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLy8gTG9nbyBDdXN0b21pemF0aW9uIFN5c3RlbVxuKGZ1bmN0aW9uKCkge1xuICAvLyBJbmplY3QgbW9kYWwgSFRNTFxuICBpbmplY3RNb2RhbCgnbG9nby1tb2RhbCcsIGA8ZGl2IGlkPVwibG9nby1tb2RhbFwiIGNsYXNzPVwid2VhdGhlci1tb2RhbFwiPlxuICAgIDxkaXYgY2xhc3M9XCJ3ZWF0aGVyLW1vZGFsLWNvbnRlbnRcIiBzdHlsZT1cIm1pbi13aWR0aDogNDAwcHg7IG1heC13aWR0aDogNTIwcHg7XCI+XG4gICAgICA8aDM+RGFzaGJvYXJkIFNldHRpbmdzPC9oMz5cbiAgICAgIDxwIHN0eWxlPVwiZm9udC1zaXplOiAwLjg1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW46IDAgMCAxNnB4O1wiPlxuICAgICAgICBDdXN0b21pemUgeW91ciBkYXNoYm9hcmQncyBhcHBlYXJhbmNlIGFuZCBzeXN0ZW0gcHJlZmVyZW5jZXMuXG4gICAgICA8L3A+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgZm9yPVwiZGFzaGJvYXJkLXRpdGxlXCIgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5EYXNoYm9hcmQgVGl0bGU6PC9sYWJlbD5cbiAgICAgICAgPGlucHV0IHR5cGU9XCJ0ZXh0XCIgaWQ9XCJkYXNoYm9hcmQtdGl0bGVcIiBwbGFjZWhvbGRlcj1cIkRhc2hDYWRkeVwiIG1heGxlbmd0aD1cIjUwXCIgc3R5bGU9XCJ3aWR0aDogMTAwJTsgcGFkZGluZzogMTBweCAxMnB4OyBib3JkZXI6IDFweCBzb2xpZCB2YXIoLS1ib3JkZXIpOyBib3JkZXItcmFkaXVzOiA0cHg7IGJhY2tncm91bmQ6IHZhcigtLWNhcmQtYmcpOyBjb2xvcjogdmFyKC0tZmcpOyBmb250LXNpemU6IDFyZW07XCIgLz5cbiAgICAgICAgPHAgY2xhc3M9XCJ0aW55LWhpbnRcIj5TaG93biBpbiBicm93c2VyIHRhYiBhbmQgaGVhZGVyIChtYXggNTAgY2hhcmFjdGVycyk8L3A+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGhyIGNsYXNzPVwiaHItZGl2aWRlclwiIC8+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5Mb2dvOjwvbGFiZWw+XG4gICAgICAgIDxwIGNsYXNzPVwidGlueS1oaW50XCIgc3R5bGU9XCJtYXJnaW4tdG9wOiAycHg7XCI+U2VwYXJhdGUgbG9nb3MgZm9yIGRhcmsgYW5kIGxpZ2h0IHRoZW1lcywgb3IgdXNlIHRoZSBzYW1lIGZvciBib3RoLjwvcD5cbiAgICAgIDwvZGl2PlxuXG4gICAgICA8ZGl2IHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4OyBtYXJnaW4tYm90dG9tOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogIzFhMWEyZTsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgyNTUsMjU1LDI1NSwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1kYXJrXCIgc3JjPVwiL2Fzc2V0cy9kYXNoY2FkZHktbG9nby1kYXJrLnBuZ1wiIGFsdD1cIkRhcmsgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjOWFhNmJmOyBtYXJnaW4tdG9wOiA2cHg7XCI+RGFyayB0aGVtZXM8L3A+XG4gICAgICAgIDwvZGl2PlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogI2YwZjBmMDsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgwLDAsMCwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1saWdodFwiIHNyYz1cIi9hc3NldHMvZGFzaGNhZGR5LWxvZ28tbGlnaHQucG5nXCIgYWx0PVwiTGlnaHQgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjNWY2YjdhOyBtYXJnaW4tdG9wOiA2cHg7XCI+TGlnaHQgdGhlbWVzPC9wPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIDwvZGl2PlxuICAgICAgPHAgaWQ9XCJsb2dvLXN0YXR1c1wiIHN0eWxlPVwiZm9udC1zaXplOiAwLjc1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW4tYm90dG9tOiAxMnB4OyB0ZXh0LWFsaWduOiBjZW50ZXI7XCI+VXNpbmcgZGVmYXVsdCBsb2dvczwvcD5cblxuICAgICAgPGRpdiBjbGFzcz1cIm1iLTE2XCI+XG4gICAgICAgIDxsYWJlbCBzdHlsZT1cImRpc3BsYXk6IGZsZXg7IGFsaWduLWl0ZW1zOiBjZW50ZXI7IGdhcDogOHB4OyBmb250LXNpemU6IDAuODJyZW07IGN1cnNvcjogcG9pbnRlcjsgdXNlci1zZWxlY3Q6IG5vbmU7XCI+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJjaGVja2JveFwiIGlkPVwibG9nby1zYW1lLWJvdGhcIiAvPiBVc2Ugc2FtZSBsb2dvIGZvciBib3RoXG4gICAgICAgIDwvbGFiZWw+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tZHVhbC11cGxvYWRzXCIgY2xhc3M9XCJtYi0xNlwiIHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTtcIj5cbiAgICAgICAgICA8bGFiZWwgZm9yPVwibG9nby11cGxvYWQtZGFya1wiIHN0eWxlPVwiZGlzcGxheTogYmxvY2s7IG1hcmdpbi1ib3R0b206IDZweDsgZm9udC1zaXplOiAwLjhyZW07XCI+RGFyayB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1kYXJrXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiBzdHlsZT1cImZvbnQtc2l6ZTogMC43NXJlbTtcIiAvPlxuICAgICAgICA8L2Rpdj5cbiAgICAgICAgPGRpdiBzdHlsZT1cImZsZXg6IDE7XCI+XG4gICAgICAgICAgPGxhYmVsIGZvcj1cImxvZ28tdXBsb2FkLWxpZ2h0XCIgc3R5bGU9XCJkaXNwbGF5OiBibG9jazsgbWFyZ2luLWJvdHRvbTogNnB4OyBmb250LXNpemU6IDAuOHJlbTtcIj5MaWdodCB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1saWdodFwiIGFjY2VwdD1cImltYWdlLypcIiBjbGFzcz1cImlucHV0LWNhcmQtYWx0XCIgc3R5bGU9XCJmb250LXNpemU6IDAuNzVyZW07XCIgLz5cbiAgICAgICAgPC9kaXY+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tc2luZ2xlLXVwbG9hZFwiIGNsYXNzPVwibWItMTZcIiBzdHlsZT1cImRpc3BsYXk6IG5vbmU7XCI+XG4gICAgICAgIDxsYWJlbCBmb3I9XCJsb2dvLXVwbG9hZC1zaW5nbGVcIiBzdHlsZT1cImRpc3BsYXk6IGJsb2NrOyBtYXJnaW4tYm90dG9tOiA2cHg7IGZvbnQtc2l6ZTogMC44cmVtO1wiPlVwbG9hZCBsb2dvOjwvbGFiZWw+XG4gICAgICAgIDxpbnB1dCB0eXBlPVwiZmlsZVwiIGlkPVwibG9nby11cGxvYWQtc2luZ2xlXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiAvPlxuICAgICAgICA8cCBjbGFzcz1cInRpbnktaGludFwiPlRoaXMgbG9nbyB3aWxsIGJlIHVzZWQgb24gYWxsIHRoZW1lc Line truncated //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLy8gTG9nbyBDdXN0b21pemF0aW9uIFN5c3RlbVxuKGZ1bmN0aW9uKCkge1xuICAvLyBJbmplY3QgbW9kYWwgSFRNTFxuICBpbmplY3RNb2RhbCgnbG9nby1tb2RhbCcsIGA8ZGl2IGlkPVwibG9nby1tb2RhbFwiIGNsYXNzPVwid2VhdGhlci1tb2RhbFwiPlxuICAgIDxkaXYgY2xhc3M9XCJ3ZWF0aGVyLW1vZGFsLWNvbnRlbnRcIiBzdHlsZT1cIm1pbi13aWR0aDogNDAwcHg7IG1heC13aWR0aDogNTIwcHg7XCI+XG4gICAgICA8aDM+RGFzaGJvYXJkIFNldHRpbmdzPC9oMz5cbiAgICAgIDxwIHN0eWxlPVwiZm9udC1zaXplOiAwLjg1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW46IDAgMCAxNnB4O1wiPlxuICAgICAgICBDdXN0b21pemUgeW91ciBkYXNoYm9hcmQncyBhcHBlYXJhbmNlIGFuZCBzeXN0ZW0gcHJlZmVyZW5jZXMuXG4gICAgICA8L3A+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgZm9yPVwiZGFzaGJvYXJkLXRpdGxlXCIgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5EYXNoYm9hcmQgVGl0bGU6PC9sYWJlbD5cbiAgICAgICAgPGlucHV0IHR5cGU9XCJ0ZXh0XCIgaWQ9XCJkYXNoYm9hcmQtdGl0bGVcIiBwbGFjZWhvbGRlcj1cIkRhc2hDYWRkeVwiIG1heGxlbmd0aD1cIjUwXCIgc3R5bGU9XCJ3aWR0aDogMTAwJTsgcGFkZGluZzogMTBweCAxMnB4OyBib3JkZXI6IDFweCBzb2xpZCB2YXIoLS1ib3JkZXIpOyBib3JkZXItcmFkaXVzOiA0cHg7IGJhY2tncm91bmQ6IHZhcigtLWNhcmQtYmcpOyBjb2xvcjogdmFyKC0tZmcpOyBmb250LXNpemU6IDFyZW07XCIgLz5cbiAgICAgICAgPHAgY2xhc3M9XCJ0aW55LWhpbnRcIj5TaG93biBpbiBicm93c2VyIHRhYiBhbmQgaGVhZGVyIChtYXggNTAgY2hhcmFjdGVycyk8L3A+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGhyIGNsYXNzPVwiaHItZGl2aWRlclwiIC8+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5Mb2dvOjwvbGFiZWw+XG4gICAgICAgIDxwIGNsYXNzPVwidGlueS1oaW50XCIgc3R5bGU9XCJtYXJnaW4tdG9wOiAycHg7XCI+U2VwYXJhdGUgbG9nb3MgZm9yIGRhcmsgYW5kIGxpZ2h0IHRoZW1lcywgb3IgdXNlIHRoZSBzYW1lIGZvciBib3RoLjwvcD5cbiAgICAgIDwvZGl2PlxuXG4gICAgICA8ZGl2IHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4OyBtYXJnaW4tYm90dG9tOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogIzFhMWEyZTsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgyNTUsMjU1LDI1NSwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1kYXJrXCIgc3JjPVwiL2Fzc2V0cy9kYXNoY2FkZHktbG9nby1kYXJrLnBuZ1wiIGFsdD1cIkRhcmsgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjOWFhNmJmOyBtYXJnaW4tdG9wOiA2cHg7XCI+RGFyayB0aGVtZXM8L3A+XG4gICAgICAgIDwvZGl2PlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogI2YwZjBmMDsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgwLDAsMCwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1saWdodFwiIHNyYz1cIi9hc3NldHMvZGFzaGNhZGR5LWxvZ28tbGlnaHQucG5nXCIgYWx0PVwiTGlnaHQgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjNWY2YjdhOyBtYXJnaW4tdG9wOiA2cHg7XCI+TGlnaHQgdGhlbWVzPC9wPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIDwvZGl2PlxuICAgICAgPHAgaWQ9XCJsb2dvLXN0YXR1c1wiIHN0eWxlPVwiZm9udC1zaXplOiAwLjc1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW4tYm90dG9tOiAxMnB4OyB0ZXh0LWFsaWduOiBjZW50ZXI7XCI+VXNpbmcgZGVmYXVsdCBsb2dvczwvcD5cblxuICAgICAgPGRpdiBjbGFzcz1cIm1iLTE2XCI+XG4gICAgICAgIDxsYWJlbCBzdHlsZT1cImRpc3BsYXk6IGZsZXg7IGFsaWduLWl0ZW1zOiBjZW50ZXI7IGdhcDogOHB4OyBmb250LXNpemU6IDAuODJyZW07IGN1cnNvcjogcG9pbnRlcjsgdXNlci1zZWxlY3Q6IG5vbmU7XCI+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJjaGVja2JveFwiIGlkPVwibG9nby1zYW1lLWJvdGhcIiAvPiBVc2Ugc2FtZSBsb2dvIGZvciBib3RoXG4gICAgICAgIDwvbGFiZWw+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tZHVhbC11cGxvYWRzXCIgY2xhc3M9XCJtYi0xNlwiIHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTtcIj5cbiAgICAgICAgICA8bGFiZWwgZm9yPVwibG9nby11cGxvYWQtZGFya1wiIHN0eWxlPVwiZGlzcGxheTogYmxvY2s7IG1hcmdpbi1ib3R0b206IDZweDsgZm9udC1zaXplOiAwLjhyZW07XCI+RGFyayB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1kYXJrXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiBzdHlsZT1cImZvbnQtc2l6ZTogMC43NXJlbTtcIiAvPlxuICAgICAgICA8L2Rpdj5cbiAgICAgICAgPGRpdiBzdHlsZT1cImZsZXg6IDE7XCI+XG4gICAgICAgICAgPGxhYmVsIGZvcj1cImxvZ28tdXBsb2FkLWxpZ2h0XCIgc3R5bGU9XCJkaXNwbGF5OiBibG9jazsgbWFyZ2luLWJvdHRvbTogNnB4OyBmb250LXNpemU6IDAuOHJlbTtcIj5MaWdodCB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1saWdodFwiIGFjY2VwdD1cImltYWdlLypcIiBjbGFzcz1cImlucHV0LWNhcmQtYWx0XCIgc3R5bGU9XCJmb250LXNpemU6IDAuNzVyZW07XCIgLz5cbiAgICAgICAgPC9kaXY+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tc2luZ2xlLXVwbG9hZFwiIGNsYXNzPVwibWItMTZcIiBzdHlsZT1cImRpc3BsYXk6IG5vbmU7XCI+XG4gICAgICAgIDxsYWJlbCBmb3I9XCJsb2dvLXVwbG9hZC1zaW5nbGVcIiBzdHlsZT1cImRpc3BsYXk6IGJsb2NrOyBtYXJnaW4tYm90dG9tOiA2cHg7IGZvbnQtc2l6ZTogMC44cmVtO1wiPlVwbG9hZCBsb2dvOjwvbGFiZWw+XG4gICAgICAgIDxpbnB1dCB0eXBlPVwiZmlsZVwiIGlkPVwibG9nby11cGxvYWQtc2luZ2xlXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiAvPlxuICAgICAgICA8cCBjbGFzcz1cInRpbnktaGludFwiPlRoaXMgbG9nbyB3aWxsIGJlIHVzZWQgb24gYWxsIHRoZW1lc Line truncated
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'dashcaddy-shell-c775f8444e'; const CACHE = 'dashcaddy-shell-d17fb082db';
const PRECACHE = [ const PRECACHE = [
'/', '/',
'/index.html', '/index.html',