@@ -127,7 +127,7 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
Timezone: ${c.replace(/_/g," ")}
- `,o+="
",u.innerHTML=o,D("setup-step-summary")}async function $(u){try{const o=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return o.ok?(await o.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${o.status}`),{function:"saveConfigToServer"}),!1)}catch(o){return errorHandler.logError("[SetupWizard] Save Config",o,{function:"saveConfigToServer"}),!1}}async function R(){const u={setupComplete:!0,configurationType:b,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(b==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const g=document.getElementById("setup-dns-provider")?.value||"technitium";u.dns=DnsProviderConfig.buildDnsConfig(g,document.getElementById("setup-dns-ip")?.value?.trim()||"",document.getElementById("setup-dns-port")?.value?.trim()||"",document.getElementById("setup-dns-token")?.value?.trim()||"",DC.DEFAULTS.DNS_PORT),u.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else b==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):b==="public"&&(u.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",u.email=document.getElementById("setup-public-email")?.value?.trim()||"",u.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u.defaults={dnsType:u.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const o=await $(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const c=b==="homelab"?"Professional Home Lab":b==="simple"?"Simple Setup":"Public Server",d=o?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${c}. Settings saved to: ${d}`,"success",5e3),setTimeout(()=>location.reload(),500)}const y=document.getElementById("setup-step-1-next");y&&(y.onclick=function(u){u.preventDefault();const o=document.querySelector('input[name="config-type"]:checked');o&&(b=o.value),D(b==="homelab"?"setup-step-homelab":b==="simple"?"setup-step-simple":b==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await $({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(u){const o=u.target.value||".home",c=document.getElementById("tld-preview"),d=document.getElementById("tld-preview-2");c&&(c.textContent=o),d&&(d.textContent=o)});const z=document.getElementById("setup-homelab-back");z&&(z.onclick=function(u){u.preventDefault(),D("setup-step-1")});const x=document.getElementById("setup-homelab-next");x&&(x.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-tld")?.value?.trim()||"",c=document.getElementById("setup-ca-name")?.value?.trim()||"",d=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!o||!o.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!c){showNotification("Please enter a Certificate Authority name","warning");return}if(!d){showNotification("Please enter your DNS server IP address","warning");return}M()});const C=document.getElementById("setup-simple-back");C&&(C.onclick=function(u){u.preventDefault(),D("setup-step-1")});const k=document.getElementById("setup-simple-next");k&&(k.onclick=function(u){u.preventDefault(),M()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var o=document.getElementById("dns-requirement-note");o&&(o.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const T=document.getElementById("setup-public-back");T&&(T.onclick=function(u){u.preventDefault(),D("setup-step-1")});const N=document.getElementById("setup-public-next");N&&(N.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-public-domain")?.value?.trim()||"",c=document.getElementById("setup-public-email")?.value?.trim()||"";if(!o){showNotification("Please enter your domain name","warning");return}if(!c||!c.includes("@")){showNotification("Please enter a valid email address","warning");return}M()});const f=document.getElementById("setup-summary-back");f&&(f.onclick=function(u){u.preventDefault(),b==="homelab"?D("setup-step-homelab"):b==="simple"?D("setup-step-simple"):b==="public"&&D("setup-step-public")});const B=document.getElementById("setup-summary-next");B&&(B.onclick=function(u){u.preventDefault(),D("setup-step-disk-safety")});const P=document.getElementById("setup-disk-safety-back");P&&(P.onclick=function(u){u.preventDefault(),D("setup-step-summary")});const O=document.getElementById("setup-disk-safety-finish");O&&(O.onclick=function(u){u.preventDefault(),R()}),window.getGlobalConfig=async function(){try{const o=await fetch("/api/v1/config");if(o.ok){const c=await o.json();if(c&&c.setupComplete)return c}}catch{console.warn("Could not fetch config from server")}const u=safeGet("dashcaddy-config");return u?JSON.parse(u):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}};const S={technitium:"\u2705 Full management \u2014 records, zones and health checks via the Technitium API. DashCaddy can create, delete, list and resolve records.",cloudflare:"\u2705 Full management \u2014 records via the Cloudflare API token. DashCaddy can create, delete, list and resolve records.",rfc2136:"\u26A0\uFE0F Partial (push-only protocol) \u2014 records can be created, deleted and resolved, and listed via AXFR zone transfer if the server permits transfers for your key (BIND: allow-transfer { key ; };). Listing requires that server-side setting.",powerdns:"\u2705 Full management \u2014 records and zones via the PowerDNS HTTP API (X-API-Key). Requires api=yes, webserver=yes and api-key in pdns.conf. DashCaddy can create, delete, list and resolve records.",manual:"\u2139\uFE0F No API control \u2014 DashCaddy shows the records you create yourself with your DNS provider's tools. Everything else (reverse proxy, SSL) works normally."};function I(){const u=document.getElementById("setup-dns-provider"),o=document.getElementById("setup-dns-provider-hints");!u||!o||(o.innerHTML=S[u.value]?`${H(u.selectedOptions[0]?.text||u.value)} ${S[u.value]}`:"")}function H(u){return String(u??"").replace(/&/g,"&").replace(//g,">")}const E=document.getElementById("setup-dns-provider");E&&(E.addEventListener("change",I),I())})(),(function(){const b=new ErrorHandler;injectModal("app-selector-modal",`
+ `,o+="
",u.innerHTML=o,D("setup-step-summary")}async function B(u){try{const o=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return o.ok?(await o.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${o.status}`),{function:"saveConfigToServer"}),!1)}catch(o){return errorHandler.logError("[SetupWizard] Save Config",o,{function:"saveConfigToServer"}),!1}}async function R(){const u={setupComplete:!0,configurationType:x,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(x==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const g=document.getElementById("setup-dns-provider")?.value||"technitium";try{u.dns=DnsProviderConfig.buildDnsConfig(g,document.getElementById("setup-dns-ip")?.value?.trim()||"",document.getElementById("setup-dns-port")?.value?.trim()||"",document.getElementById("setup-dns-token")?.value?.trim()||"",DC.DEFAULTS.DNS_PORT)}catch(p){showNotification(p.message,"error",6e3);return}u.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else x==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):x==="public"&&(u.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",u.email=document.getElementById("setup-public-email")?.value?.trim()||"",u.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u.defaults={dnsType:u.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const o=await B(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const c=x==="homelab"?"Professional Home Lab":x==="simple"?"Simple Setup":"Public Server",d=o?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${c}. Settings saved to: ${d}`,"success",5e3),setTimeout(()=>location.reload(),500)}const y=document.getElementById("setup-step-1-next");y&&(y.onclick=function(u){u.preventDefault();const o=document.querySelector('input[name="config-type"]:checked');o&&(x=o.value),D(x==="homelab"?"setup-step-homelab":x==="simple"?"setup-step-simple":x==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await B({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const k=document.getElementById("setup-tld");k&&(k.oninput=function(u){const o=u.target.value||".home",c=document.getElementById("tld-preview"),d=document.getElementById("tld-preview-2");c&&(c.textContent=o),d&&(d.textContent=o)});const M=document.getElementById("setup-homelab-back");M&&(M.onclick=function(u){u.preventDefault(),D("setup-step-1")});const w=document.getElementById("setup-homelab-next");w&&(w.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-tld")?.value?.trim()||"",c=document.getElementById("setup-ca-name")?.value?.trim()||"",d=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!o||!o.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!c){showNotification("Please enter a Certificate Authority name","warning");return}if(!d){showNotification("Please enter your DNS server IP address","warning");return}H()});const z=document.getElementById("setup-simple-back");z&&(z.onclick=function(u){u.preventDefault(),D("setup-step-1")});const b=document.getElementById("setup-simple-next");b&&(b.onclick=function(u){u.preventDefault(),H()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var o=document.getElementById("dns-requirement-note");o&&(o.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const C=document.getElementById("setup-public-back");C&&(C.onclick=function(u){u.preventDefault(),D("setup-step-1")});const N=document.getElementById("setup-public-next");N&&(N.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-public-domain")?.value?.trim()||"",c=document.getElementById("setup-public-email")?.value?.trim()||"";if(!o){showNotification("Please enter your domain name","warning");return}if(!c||!c.includes("@")){showNotification("Please enter a valid email address","warning");return}H()});const f=document.getElementById("setup-summary-back");f&&(f.onclick=function(u){u.preventDefault(),x==="homelab"?D("setup-step-homelab"):x==="simple"?D("setup-step-simple"):x==="public"&&D("setup-step-public")});const T=document.getElementById("setup-summary-next");T&&(T.onclick=function(u){u.preventDefault(),D("setup-step-disk-safety")});const P=document.getElementById("setup-disk-safety-back");P&&(P.onclick=function(u){u.preventDefault(),D("setup-step-summary")});const O=document.getElementById("setup-disk-safety-finish");O&&(O.onclick=function(u){u.preventDefault(),R()}),window.getGlobalConfig=async function(){try{const o=await fetch("/api/v1/config");if(o.ok){const c=await o.json();if(c&&c.setupComplete)return c}}catch{console.warn("Could not fetch config from server")}const u=safeGet("dashcaddy-config");return u?JSON.parse(u):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}};const S={technitium:"\u2705 Full management \u2014 records, zones and health checks via the Technitium API. DashCaddy can create, delete, list and resolve records.",cloudflare:"\u2705 Full management \u2014 records via the Cloudflare API token. DashCaddy can create, delete, list and resolve records.",rfc2136:"\u26A0\uFE0F Partial (push-only protocol) \u2014 records can be created, deleted and resolved, and listed via AXFR zone transfer if the server permits transfers for your key (BIND: allow-transfer { key ; };). Listing requires that server-side setting.",powerdns:"\u2705 Full management \u2014 records and zones via the PowerDNS HTTP API (X-API-Key). Requires api=yes, webserver=yes and api-key in pdns.conf. DashCaddy can create, delete, list and resolve records.",manual:"\u2139\uFE0F No API control \u2014 DashCaddy shows the records you create yourself with your DNS provider's tools. Everything else (reverse proxy, SSL) works normally."};function I(){const u=document.getElementById("setup-dns-provider"),o=document.getElementById("setup-dns-provider-hints");!u||!o||(o.innerHTML=S[u.value]?`${$(u.selectedOptions[0]?.text||u.value)} ${S[u.value]}`:"")}function $(u){return String(u??"").replace(/&/g,"&").replace(//g,">")}const E=document.getElementById("setup-dns-provider");E&&(E.addEventListener("change",I),I())})(),(function(){const x=new ErrorHandler;injectModal("app-selector-modal",`
Choose an App
@@ -333,12 +333,12 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
-
`);const h="custom-apps";let j=null,v=null;const D=document.getElementById("app-selector-modal"),M=document.getElementById("app-selector-grid");async function $(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return j=c.templates,v=c.categories,!0}catch(o){b.logError("[AppSelector] Fetch Templates",o,{function:"fetchApiTemplates"})}return!1}async function R(o){try{return await(await fetch(`/api/v1/apps/ports/${o}/check`)).json()}catch(c){return b.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function y(o){try{const d=await(await fetch(`/api/v1/apps/ports/${o}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){b.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return o}async function L(){if(M.innerHTML='
Loading app templates...
',!j&&!await $()){M.innerHTML='
Failed to load app templates. Please try again.
';return}M.innerHTML="";const o={};for(const[d,g]of Object.entries(j)){const p=g.category||"Other";o[p]||(o[p]=[]),o[p].push({id:d,...g})}const c=v?Object.keys(v):Object.keys(o).sort();for(const d of c){const g=o[d];if(!g||g.length===0)continue;g.sort((i,l)=>(l.popularity||0)-(i.popularity||0));const p=document.createElement("div");p.className="app-category-header";const e=v?.[d]||{};p.innerHTML=`${escapeHtml(e.icon||"")} ${escapeHtml(d)}`,e.color&&(p.style.borderBottomColor=e.color),M.appendChild(p),g.forEach(i=>{const l=document.createElement("div");l.className="app-option";const s=i.isDashboardWidget,a=s&&safeGet("widget-"+i.id+"-enabled")!=="false",t=s?`
${a?"ON":"OFF"}
`:"",n=!s&&i.difficulty?`
${escapeHtml(i.difficulty)}
`:"";l.innerHTML=`
+
`);const h="custom-apps";let j=null,v=null;const D=document.getElementById("app-selector-modal"),H=document.getElementById("app-selector-grid");async function B(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return j=c.templates,v=c.categories,!0}catch(o){x.logError("[AppSelector] Fetch Templates",o,{function:"fetchApiTemplates"})}return!1}async function R(o){try{return await(await fetch(`/api/v1/apps/ports/${o}/check`)).json()}catch(c){return x.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function y(o){try{const d=await(await fetch(`/api/v1/apps/ports/${o}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){x.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return o}async function L(){if(H.innerHTML='
Loading app templates...
',!j&&!await B()){H.innerHTML='
Failed to load app templates. Please try again.
';return}H.innerHTML="";const o={};for(const[d,g]of Object.entries(j)){const p=g.category||"Other";o[p]||(o[p]=[]),o[p].push({id:d,...g})}const c=v?Object.keys(v):Object.keys(o).sort();for(const d of c){const g=o[d];if(!g||g.length===0)continue;g.sort((i,l)=>(l.popularity||0)-(i.popularity||0));const p=document.createElement("div");p.className="app-category-header";const e=v?.[d]||{};p.innerHTML=`${escapeHtml(e.icon||"")} ${escapeHtml(d)}`,e.color&&(p.style.borderBottomColor=e.color),H.appendChild(p),g.forEach(i=>{const l=document.createElement("div");l.className="app-option";const s=i.isDashboardWidget,a=s&&safeGet("widget-"+i.id+"-enabled")!=="false",t=s?`
${a?"ON":"OFF"}
`:"",n=!s&&i.difficulty?`
${escapeHtml(i.difficulty)}
`:"";l.innerHTML=`
${escapeHtml(i.icon||"\u{1F4E6}")}
${escapeHtml(i.name)}
${escapeHtml(i.description||"")}
${t}${n}
- `,s?l.onclick=()=>w(i,l):l.onclick=()=>z(i),M.appendChild(l)})}window.renderRecipeCards&&await window.renderRecipeCards(M)}function w(o,c){const d="widget-"+o.id+"-enabled",p=!(safeGet(d)!=="false");safeSet(d,String(p));const e=o.widgetSelector;if(e){const l=document.querySelector(e);l&&(l.style.display=p?"":"none")}const i=c.querySelector('div[style*="border-radius: 4px"]');i&&(i.textContent=p?"ON":"OFF",i.style.background=p?"#2ecc7130":"#e74c3c30",i.style.color=p?"#2ecc71":"#e74c3c"),showNotification(`${o.name} widget ${p?"enabled":"disabled"}`,"success",2e3)}async function z(o){const c=document.getElementById("app-deploy-modal"),d=document.getElementById("app-deploy-title"),g=document.getElementById("deploy-subdomain"),p=document.getElementById("deploy-url-preview"),e=document.getElementById("deploy-ip"),i=document.getElementById("deploy-port"),l=document.getElementById("deploy-tailscale-only"),s=document.getElementById("tailscale-status");try{const V=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:o.id})})).json();if(V.success&&V.exists){const Y=V.container;confirm(`Found existing ${o.name} container:
+ `,s?l.onclick=()=>k(i,l):l.onclick=()=>M(i),H.appendChild(l)})}window.renderRecipeCards&&await window.renderRecipeCards(H)}function k(o,c){const d="widget-"+o.id+"-enabled",p=!(safeGet(d)!=="false");safeSet(d,String(p));const e=o.widgetSelector;if(e){const l=document.querySelector(e);l&&(l.style.display=p?"":"none")}const i=c.querySelector('div[style*="border-radius: 4px"]');i&&(i.textContent=p?"ON":"OFF",i.style.background=p?"#2ecc7130":"#e74c3c30",i.style.color=p?"#2ecc71":"#e74c3c"),showNotification(`${o.name} widget ${p?"enabled":"disabled"}`,"success",2e3)}async function M(o){const c=document.getElementById("app-deploy-modal"),d=document.getElementById("app-deploy-title"),g=document.getElementById("deploy-subdomain"),p=document.getElementById("deploy-url-preview"),e=document.getElementById("deploy-ip"),i=document.getElementById("deploy-port"),l=document.getElementById("deploy-tailscale-only"),s=document.getElementById("tailscale-status");try{const V=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:o.id})})).json();if(V.success&&V.exists){const Y=V.container;confirm(`Found existing ${o.name} container:
Container: ${Y.name}
Status: ${Y.status}
@@ -358,27 +358,27 @@ Click Cancel to deploy a new container.`)&&(o._useExisting=!0,o._existingContain
Connected${V.self?.hostname} (${V.self?.ip})| ${V.deviceCount} devices
- `:V.installed?s.innerHTML='Not connected':(s.innerHTML='Not available',l.disabled=!0)}catch{s.innerHTML='Could not check status'}function se(){const W=g.value||"subdomain",V=document.querySelector('input[name="dns-type"]:checked').value,Y=document.querySelector('input[name="ssl-type"]:checked').value;let X="";if(SITE.routingMode==="subdirectory"&&SITE.domain)X=`https://${SITE.domain}/${W}`;else if(V==="private")X=`${Y==="none"?"http":"https"}://${buildDomain(W)}`;else if(V==="public"){const ae=Y==="none"?"http":"https",te=SITE.domain||W;X=SITE.domain?`${ae}://${W}.${SITE.domain}`:`${ae}://${W}`}else{const ae=i.value||o.defaultPort||DC.DEFAULTS.SERVICE_PORT;X=`http://${e.value}:${ae}`}p.textContent=X}g.oninput=se,e.oninput=se,i.oninput=se,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=se}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=se}),se(),D.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(o)}async function x(o){const c=o.appTemplate,d=safeGetJSON(h,[]),g=c._useExisting&&c._existingContainer,p=d.find(e=>e.id===o.subdomain);if(!(p&&!g&&!confirm(`An app with subdomain "${o.subdomain}" already exists. Redeploy?`))){if(p){const e=d.indexOf(p);d.splice(e,1),safeSet(h,JSON.stringify(d))}if(g)o.port=c._existingContainer.primaryPort;else{const e=o.port||c.defaultPort||8080;showNotification(`Checking port ${e} availability...`,"info",0);const i=await R(e);if(!i.available){const l=await y(c.defaultPort||8080);if(confirm(`Port ${e} is already in use by ${i.conflict?.usedBy||"another container"}.
+ `:V.installed?s.innerHTML='Not connected':(s.innerHTML='Not available',l.disabled=!0)}catch{s.innerHTML='Could not check status'}function se(){const W=g.value||"subdomain",V=document.querySelector('input[name="dns-type"]:checked').value,Y=document.querySelector('input[name="ssl-type"]:checked').value;let X="";if(SITE.routingMode==="subdirectory"&&SITE.domain)X=`https://${SITE.domain}/${W}`;else if(V==="private")X=`${Y==="none"?"http":"https"}://${buildDomain(W)}`;else if(V==="public"){const ae=Y==="none"?"http":"https",te=SITE.domain||W;X=SITE.domain?`${ae}://${W}.${SITE.domain}`:`${ae}://${W}`}else{const ae=i.value||o.defaultPort||DC.DEFAULTS.SERVICE_PORT;X=`http://${e.value}:${ae}`}p.textContent=X}g.oninput=se,e.oninput=se,i.oninput=se,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=se}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=se}),se(),D.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(o)}async function w(o){const c=o.appTemplate,d=safeGetJSON(h,[]),g=c._useExisting&&c._existingContainer,p=d.find(e=>e.id===o.subdomain);if(!(p&&!g&&!confirm(`An app with subdomain "${o.subdomain}" already exists. Redeploy?`))){if(p){const e=d.indexOf(p);d.splice(e,1),safeSet(h,JSON.stringify(d))}if(g)o.port=c._existingContainer.primaryPort;else{const e=o.port||c.defaultPort||8080;showNotification(`Checking port ${e} availability...`,"info",0);const i=await R(e);if(!i.available){const l=await y(c.defaultPort||8080);if(confirm(`Port ${e} is already in use by ${i.conflict?.usedBy||"another container"}.
Would you like to use port ${l} instead?`))o.port=l;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(g?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const e={appId:c.id,config:{subdomain:o.subdomain,ip:o.ip,createDns:o.dnsType==="private",port:o.port||c.defaultPort||null,sslType:o.sslType,dnsType:o.dnsType,tailscaleOnly:o.tailscaleOnly||!1,mediaPath:o.mediaPath||null,plexClaimToken:o.plexClaimToken||null,customVolumes:o.customVolumes||null}};g&&(e.config.useExisting=!0,e.config.existingContainerId=c._existingContainer.id,e.config.existingPort=c._existingContainer.primaryPort,!o.port&&c._existingContainer.primaryPort&&(e.config.port=c._existingContainer.primaryPort));const i={app:c.id,port:o.port||c.defaultPort||null,subdomain:o.subdomain||"",media_path:o.mediaPath||"",env:o.plexClaimToken?{PLEX_CLAIM:o.plexClaimToken}:{}},s=await(await secureFetch("/api/v1/deploys/catalog/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).json();if(s.success){const a={id:o.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:null,url:s.url||`http://127.0.0.1:${i.port}`,ip:o.ip,appTemplate:c.id,tailscaleOnly:o.tailscaleOnly||!1};d.push(a),safeSet(h,JSON.stringify(d)),window.APPS&&!window.APPS.some(n=>n.id===c.id)&&(window.APPS.push(a),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let t=s.usedExisting?`${c.name} configured with existing container!
URL: ${s.url}`:`${c.name} deployed successfully!
URL: ${s.url}`;s.warning&&(t+=`
-\u26A0 Warning: ${s.warning}`),showNotification(t,"success",8e3),delete c._useExisting,delete c._existingContainer,s.url&&s.url.startsWith("https://")&&C(s.url,c.name),s.setupInstructions&&s.setupInstructions.length>0&&setTimeout(()=>{const n=s.setupInstructions.join(`
-`);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(s.error||"Deployment failed")}catch(e){b.logError("[AppSelector] Deployment",e,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${e.message}`,"error",8e3)}}}async function C(o,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const g=12,p=async()=>{d++;try{const e=await fetch(o,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return d{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{L(),D.classList.add("show")}),window.openDeployConfigFor=async function(o){if(!j&&!await $())return!1;const c=String(o||"").toLowerCase(),d=Object.entries(j).find(([p])=>p.toLowerCase()===c);if(!d)return!1;const g={id:d[0],...d[1]};return g.isDashboardWidget?(await L(),D.classList.add("show"),"selector"):(await z(g),!0)},wireModal(D,document.getElementById("app-selector-cancel"));const T=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const o=JSON.parse(T.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(p=>{d.push({hostPath:p.value.trim(),containerPath:p.dataset.containerPath})});const g={appTemplate:o,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(!g.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(o.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}T.classList.remove("show"),x(g)}),wireModal(T);const N=document.getElementById("folder-browser-modal"),f=document.getElementById("folder-browser-path"),B=document.getElementById("folder-browser-list"),P=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let S="",I=[],H=null;window.openFolderBrowser=function(o){H=o,I=o.value.split(",").map(c=>c.trim()).filter(c=>c),S="",u(),E(""),N.classList.add("show")};async function E(o){f.textContent=o||"Select a drive...",B.innerHTML='
`;return}S=d.path||"",f.textContent=S||"Select a drive...";let g="";d.parent&&d.parent!==d.path&&(g+=`
+\u26A0 Warning: ${s.warning}`),showNotification(t,"success",8e3),delete c._useExisting,delete c._existingContainer,s.url&&s.url.startsWith("https://")&&z(s.url,c.name),s.setupInstructions&&s.setupInstructions.length>0&&setTimeout(()=>{const n=s.setupInstructions.join(`
+`);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(s.error||"Deployment failed")}catch(e){x.logError("[AppSelector] Deployment",e,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${e.message}`,"error",8e3)}}}async function z(o,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const g=12,p=async()=>{d++;try{const e=await fetch(o,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return d{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{L(),D.classList.add("show")}),window.openDeployConfigFor=async function(o){if(!j&&!await B())return!1;const c=String(o||"").toLowerCase(),d=Object.entries(j).find(([p])=>p.toLowerCase()===c);if(!d)return!1;const g={id:d[0],...d[1]};return g.isDashboardWidget?(await L(),D.classList.add("show"),"selector"):(await M(g),!0)},wireModal(D,document.getElementById("app-selector-cancel"));const C=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{C.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const o=JSON.parse(C.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(p=>{d.push({hostPath:p.value.trim(),containerPath:p.dataset.containerPath})});const g={appTemplate:o,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(!g.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(o.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}C.classList.remove("show"),w(g)}),wireModal(C);const N=document.getElementById("folder-browser-modal"),f=document.getElementById("folder-browser-path"),T=document.getElementById("folder-browser-list"),P=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let S="",I=[],$=null;window.openFolderBrowser=function(o){$=o,I=o.value.split(",").map(c=>c.trim()).filter(c=>c),S="",u(),E(""),N.classList.add("show")};async function E(o){f.textContent=o||"Select a drive...",T.innerHTML='
@@ -492,11 +492,11 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
${j.network?`
Docker network: ${escapeHtml(j.network.name)}
`:""}
- `}function f(){const S=document.querySelectorAll("#recipe-component-list input[data-component-id]"),I=new Set;S.forEach(E=>{E.checked&&I.add(E.dataset.componentId)});const H=j.components||[];return H.filter(E=>E.required).forEach(E=>I.add(E.id)),H.filter(E=>I.has(E.id))}async function B(){const S=document.getElementById("recipe-progress-list"),I=document.getElementById("recipe-deploy-result");I.style.display="none",S.innerHTML="";const H=f();for(const c of H){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=`
+ `}function f(){const S=document.querySelectorAll("#recipe-component-list input[data-component-id]"),I=new Set;S.forEach(E=>{E.checked&&I.add(E.dataset.componentId)});const $=j.components||[];return $.filter(E=>E.required).forEach(E=>I.add(E.id)),$.filter(E=>I.has(E.id))}async function T(){const S=document.getElementById("recipe-progress-list"),I=document.getElementById("recipe-deploy-result");I.style.display="none",S.innerHTML="";const $=f();for(const c of $){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=`
\u23F3${escapeHtml(c.role||c.id)}Queued
- `,S.appendChild(d)}const E=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),u={};E.forEach(c=>{u[c.dataset.volumeKey]=c.value});const o={selectedComponents:H.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:u},componentOverrides:{}};for(const c of H)P(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:j.id,config:o})})).json();if(d.success){for(const g of d.deployed||[])P(g.id,"success",g.url?`Running \u2192 ${g.url}`:"Running");for(const g of d.errors||[])P(g.componentId,"error",g.error);I.style.display="",I.innerHTML=`
+ `,S.appendChild(d)}const E=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),u={};E.forEach(c=>{u[c.dataset.volumeKey]=c.value});const o={selectedComponents:$.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:u},componentOverrides:{}};for(const c of $)P(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:j.id,config:o})})).json();if(d.success){for(const g of d.deployed||[])P(g.id,"success",g.url?`Running \u2192 ${g.url}`:"Running");for(const g of d.errors||[])P(g.componentId,"error",g.error);I.style.display="",I.innerHTML=`
${escapeHtml(d.message||"Deployed!")}
${d.setupInstructions?`
@@ -508,7 +508,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
Deployment failed: ${escapeHtml(d.error||"Unknown error")}
`,z.style.display="none",x.textContent="";return}if(!u&&o!==N)return;const p=Array.isArray(g.logs)?g.logs:[];if(p.length===0&&!u){const i=g.filters&&(g.filters.level||g.filters.context||g.filters.search||g.filters.since||g.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";w.innerHTML=`
");for(const i of p){const l=(i.level||"?").toUpperCase(),s=l==="ERR"?"var(--bad-fg)":l==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",a=i.timestamp?new Date(i.timestamp).toLocaleString():"\u2014",t=i.context||"\u2014",n=(i.error||"").split(`
-`)[0],r=i.request&&i.request.ip||"";e+='
`,M.style.display="none",w.textContent="";return}if(!u&&o!==N)return;const p=Array.isArray(g.logs)?g.logs:[];if(p.length===0&&!u){const i=g.filters&&(g.filters.level||g.filters.context||g.filters.search||g.filters.since||g.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";k.innerHTML=`
");for(const i of p){const l=(i.level||"?").toUpperCase(),s=l==="ERR"?"var(--bad-fg)":l==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",a=i.timestamp?new Date(i.timestamp).toLocaleString():"\u2014",t=i.context||"\u2014",n=(i.error||"").split(`
+`)[0],r=i.request&&i.request.ip||"";e+='
'})}})(),(function(){"use strict";const b=[{unit:"caddy",label:"Caddy (reverse proxy)"},{unit:"dashcaddy-api",label:"DashCaddy API (host systemd unit, not this container)"},{unit:"docker",label:"Docker daemon"},{unit:"ssh",label:"SSH server"},{unit:"systemd-journald",label:"systemd-journald"},{unit:"tailscaled",label:"Tailscale"},{unit:"networkd-dispatcher",label:"Networkd dispatcher"}];injectModal("journald-modal",`
+ `}function d(n,r=""){if(!n||n.length===0){j.innerHTML='
No logs available
',b.textContent="0 lines",C.textContent="0 filtered";return}if(O=n,S=r?n.filter(m=>m.text&&m.text.toLowerCase().includes(r.toLowerCase())):n,b.textContent=`${n.length} lines`,C.textContent=r?`${S.length} of ${n.length} shown`:`${n.length} shown`,S.length===0){j.innerHTML=`
No logs match "${o(r)}"
`;return}j.innerHTML=S.map((m,A)=>c(m,A)).join(""),j.scrollTop=j.scrollHeight}async function g(){try{const r=(await getJSON("/api/v1/logs/containers")).containers||[],m=h.value;h.innerHTML='',r.forEach(A=>{const F=document.createElement("option");F.value=A.id,F.textContent=`${A.name} (${A.image.split(":")[0]}) - ${A.status}`,F.dataset.name=A.name,F.dataset.image=A.image,F.dataset.status=A.status,F.dataset.created=A.created,h.appendChild(F)}),m&&h.querySelector(`option[value="${m}"]`)&&(h.value=m,p(m))}catch(n){console.error("Failed to load containers:",n)}}function p(n){const r=h.querySelector(`option[value="${n}"]`);r&&(N.textContent=r.dataset.image||"-",f.textContent=r.dataset.status||"-",f.style.color=r.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",T.textContent=u(r.dataset.created))}async function e(){const n=h.value;if(!n){j.innerHTML='
'})}})(),(function(){"use strict";const x=[{unit:"caddy",label:"Caddy (reverse proxy)"},{unit:"dashcaddy-api",label:"DashCaddy API (host systemd unit, not this container)"},{unit:"docker",label:"Docker daemon"},{unit:"ssh",label:"SSH server"},{unit:"systemd-journald",label:"systemd-journald"},{unit:"tailscaled",label:"Tailscale"},{unit:"networkd-dispatcher",label:"Networkd dispatcher"}];injectModal("journald-modal",`
@@ -698,7 +698,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
`}).join("");w.innerHTML=i,w.scrollHeight-w.scrollTop-w.clientHeight<80&&(w.scrollTop=w.scrollHeight)}z.textContent=`${f.length} entries`,x.textContent=p?`${e.length} of ${f.length} shown`:`${f.length} shown`}async function u(){if(!N)return;c();const p=j.value;if(!p)return;const e=Math.max(1,Math.min(5e3,Number(D.value)||200)),i=(v.value||"").trim();w.innerHTML='
`}).join("");k.innerHTML=i,k.scrollHeight-k.scrollTop-k.clientHeight<80&&(k.scrollTop=k.scrollHeight)}M.textContent=`${f.length} entries`,w.textContent=p?`${e.length} of ${f.length} shown`:`${f.length} shown`}async function u(){if(!N)return;c();const p=j.value;if(!p)return;const e=Math.max(1,Math.min(5e3,Number(D.value)||200)),i=(v.value||"").trim();k.innerHTML='
@@ -752,7 +752,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const b=document.getElementById("snapshot-modal"),h=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),v=document.getElementById("snapshot-container-select"),D=document.getElementById("snapshot-details"),M=document.getElementById("snapshot-create-btn"),$=document.getElementById("snapshot-create-status");let R=null;async function y(){try{const k=await(await fetch("/api/v1/containers")).json();if(!k.success||!k.containers)return;v.innerHTML='';for(const T of k.containers){const N=document.createElement("option");N.value=T.id,N.textContent=`${T.name||T.id} (${T.image||"unknown"})`,N.dataset.name=T.name,N.dataset.image=T.image,N.dataset.status=T.status,N.dataset.created=T.created,v.appendChild(N)}}catch(C){console.error("Failed to load containers:",C)}}function L(C){if(!C||!C.value){D.style.display="none",R=null;return}R=C.value,document.getElementById("snapshot-image").textContent=C.dataset.image||"-",document.getElementById("snapshot-status").textContent=C.dataset.status||"-",document.getElementById("snapshot-created").textContent=C.dataset.created?new Date(C.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=C.value.substring(0,12),D.style.display=""}async function w(){if(!R){$.textContent="Please select a container first",$.style.color="var(--bad-fg)";return}const C=document.getElementById("snapshot-name").value.trim();if(!C){$.textContent="Please enter a snapshot name",$.style.color="var(--bad-fg)";return}const k=document.getElementById("snapshot-leave-running").checked;M.disabled=!0,M.textContent="Creating...",$.textContent="";try{const N=await(await fetch(`/api/v1/containers/${encodeURIComponent(R)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:C,leaveRunning:k})})).json();N.success?($.textContent=`\u2713 Snapshot "${C}" created successfully`,$.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):($.textContent=`\u2717 Failed: ${N.error||"Unknown error"}`,$.style.color="var(--bad-fg)")}catch(T){$.textContent=`\u2717 Error: ${T.message}`,$.style.color="var(--bad-fg)"}finally{M.disabled=!1,M.textContent="\u{1F4BE} Create Snapshot"}}function z(){b.classList.add("show"),y()}function x(){b.classList.remove("show"),D.style.display="none",R=null,v.selectedIndex=0}h?.addEventListener("click",z),j?.addEventListener("click",x),wireModal(b,j),v?.addEventListener("change",C=>{const k=v.options[v.selectedIndex];L(k)}),M?.addEventListener("click",w),b?.querySelectorAll(".panel-tab").forEach(C=>{C.addEventListener("click",()=>{b.querySelectorAll(".panel-tab").forEach(k=>k.classList.remove("active")),b.querySelectorAll(".panel-section").forEach(k=>k.classList.remove("active")),C.classList.add("active"),b.querySelector(`#${C.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
+
`);const x=document.getElementById("snapshot-modal"),h=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),v=document.getElementById("snapshot-container-select"),D=document.getElementById("snapshot-details"),H=document.getElementById("snapshot-create-btn"),B=document.getElementById("snapshot-create-status");let R=null;async function y(){try{const b=await(await fetch("/api/v1/containers")).json();if(!b.success||!b.containers)return;v.innerHTML='';for(const C of b.containers){const N=document.createElement("option");N.value=C.id,N.textContent=`${C.name||C.id} (${C.image||"unknown"})`,N.dataset.name=C.name,N.dataset.image=C.image,N.dataset.status=C.status,N.dataset.created=C.created,v.appendChild(N)}}catch(z){console.error("Failed to load containers:",z)}}function L(z){if(!z||!z.value){D.style.display="none",R=null;return}R=z.value,document.getElementById("snapshot-image").textContent=z.dataset.image||"-",document.getElementById("snapshot-status").textContent=z.dataset.status||"-",document.getElementById("snapshot-created").textContent=z.dataset.created?new Date(z.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=z.value.substring(0,12),D.style.display=""}async function k(){if(!R){B.textContent="Please select a container first",B.style.color="var(--bad-fg)";return}const z=document.getElementById("snapshot-name").value.trim();if(!z){B.textContent="Please enter a snapshot name",B.style.color="var(--bad-fg)";return}const b=document.getElementById("snapshot-leave-running").checked;H.disabled=!0,H.textContent="Creating...",B.textContent="";try{const N=await(await fetch(`/api/v1/containers/${encodeURIComponent(R)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:z,leaveRunning:b})})).json();N.success?(B.textContent=`\u2713 Snapshot "${z}" created successfully`,B.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(B.textContent=`\u2717 Failed: ${N.error||"Unknown error"}`,B.style.color="var(--bad-fg)")}catch(C){B.textContent=`\u2717 Error: ${C.message}`,B.style.color="var(--bad-fg)"}finally{H.disabled=!1,H.textContent="\u{1F4BE} Create Snapshot"}}function M(){x.classList.add("show"),y()}function w(){x.classList.remove("show"),D.style.display="none",R=null,v.selectedIndex=0}h?.addEventListener("click",M),j?.addEventListener("click",w),wireModal(x,j),v?.addEventListener("change",z=>{const b=v.options[v.selectedIndex];L(b)}),H?.addEventListener("click",k),x?.querySelectorAll(".panel-tab").forEach(z=>{z.addEventListener("click",()=>{x.querySelectorAll(".panel-tab").forEach(b=>b.classList.remove("active")),x.querySelectorAll(".panel-section").forEach(b=>b.classList.remove("active")),z.classList.add("active"),x.querySelector(`#${z.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
\u{1F3AC} Smart Arr Connect
@@ -831,7 +831,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
- `);const b=document.getElementById("arr-setup-modal"),h=document.getElementById("arr-setup-btn"),j=document.getElementById("arr-setup-cancel"),v=document.getElementById("smart-connect-btn"),D=document.getElementById("smart-phase-detect"),M=document.getElementById("smart-phase-credentials"),$=document.getElementById("smart-phase-progress"),R=document.getElementById("smart-phase-results"),y=document.getElementById("smart-detect-results"),L=document.getElementById("smart-credential-inputs"),w=document.getElementById("smart-progress-steps"),z=document.getElementById("smart-results-content"),x=document.getElementById("smart-plex-libraries"),C=document.getElementById("smart-retry-btn");let k=null;const T={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},N={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function f(E){D.style.display=E==="detect"?"block":"none",M.style.display=E==="credentials"?"block":"none",$.style.display=E==="progress"?"block":"none",R.style.display=E==="results"?"block":"none"}function B(E){const u={connected:{bg:"var(--ok-fg)",icon:"✓",text:"Connected"},needs_key:{bg:"#f39c12",icon:"🔑",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"—",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"✗",text:"Error"}},o=u[E]||u.not_found;return`${o.icon} ${o.text}`}async function P(){f("detect"),y.style.display="none";try{if(k=await(await fetch("/api/v1/arr/smart-detect")).json(),!k.success){y.innerHTML=`
`,y.style.display="block"}}function O(E){let u="";const o=E.services,c=["radarr","sonarr","prowlarr"];for(const p of c){const e=o[p];if(!e||e.status==="not_found"&&!e.url)continue;const i=T[p],l=N[p],s=e.status==="connected";u+=`
`,y.style.display="block"}}function O(E){let u="";const o=E.services,c=["radarr","sonarr","prowlarr"];for(const p of c){const e=o[p];if(!e||e.status==="not_found"&&!e.url)continue;const i=C[p],l=N[p],s=e.status==="connected";u+=`
${i}${l}
@@ -868,7 +868,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
@@ -879,25 +879,25 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
\u{1F4CB}Seerr
- ${B(g.status)}
+ ${T(g.status)}
${e}
-
`}L.innerHTML=u,L.querySelectorAll("[data-smart-test]").forEach(p=>{p.addEventListener("click",()=>window.smartTestConnection(p.dataset.smartTest))})}window.smartTestConnection=async function(E){const u=document.getElementById(`smart-${E}-url`),o=document.getElementById(`smart-${E}-key`),c=document.getElementById(`smart-${E}-status`),d=u?.value.trim(),g=o?.value.trim();if(!d||!g){c.innerHTML='Enter URL and API key';return}c.innerHTML='';try{const e=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:E,url:d,apiKey:g})})).json();e.success?c.innerHTML=`✓ ${escapeHtml(e.appName||"Connected")} v${escapeHtml(e.version||"")}`:c.innerHTML=`✗ ${escapeHtml(e.error)}`}catch(p){c.innerHTML=`✗ ${escapeHtml(p.message)}`}};async function S(){f("progress"),w.innerHTML='
Connecting services...
';const E={};for(const o of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${o}-url`)?.value.trim(),d=document.getElementById(`smart-${o}-key`)?.value.trim();d&&c?E[o]={apiKey:d,url:c}:d&&(E[o]={apiKey:d})}const u={services:Object.keys(E).length>0?E: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(u)})).json();let d="";for(const g of c.steps||[]){const p=g.status==="success"?'✓':'✗',e=g.status==="success"?"var(--muted)":"var(--bad-fg)";d+=`
+
`}L.innerHTML=u,L.querySelectorAll("[data-smart-test]").forEach(p=>{p.addEventListener("click",()=>window.smartTestConnection(p.dataset.smartTest))})}window.smartTestConnection=async function(E){const u=document.getElementById(`smart-${E}-url`),o=document.getElementById(`smart-${E}-key`),c=document.getElementById(`smart-${E}-status`),d=u?.value.trim(),g=o?.value.trim();if(!d||!g){c.innerHTML='Enter URL and API key';return}c.innerHTML='';try{const e=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:E,url:d,apiKey:g})})).json();e.success?c.innerHTML=`✓ ${escapeHtml(e.appName||"Connected")} v${escapeHtml(e.version||"")}`:c.innerHTML=`✗ ${escapeHtml(e.error)}`}catch(p){c.innerHTML=`✗ ${escapeHtml(p.message)}`}};async function S(){f("progress"),k.innerHTML='
Connecting services...
';const E={};for(const o of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${o}-url`)?.value.trim(),d=document.getElementById(`smart-${o}-key`)?.value.trim();d&&c?E[o]={apiKey:d,url:c}:d&&(E[o]={apiKey:d})}const u={services:Object.keys(E).length>0?E: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(u)})).json();let d="";for(const g of c.steps||[]){const p=g.status==="success"?'✓':'✗',e=g.status==="success"?"var(--muted)":"var(--bad-fg)";d+=`
"}}}async function H(l,s){try{var a=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,...s})}),t=await a.json();t.success?showNotification("Schedule updated for "+l,"success"):(showNotification("Update failed: "+(t.error||"Unknown"),"error"),I())}catch(n){showNotification("Error: "+n.message,"error")}}async function E(l){try{var s=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(l),{method:"POST",headers:{"Content-Type":"application/json"}}),a=await s.json();a.success?showNotification("Backup started for "+l+"!","success"):showNotification("Backup failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function u(l){if(confirm("Remove backup schedule for "+l+"?"))try{var s=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(l),{method:"DELETE"}),a=await s.json();a.success?(showNotification("Schedule removed for "+l,"success"),I()):showNotification("Delete failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function o(){var l=document.getElementById("new-schedule-appid")?.value?.trim(),s=document.getElementById("new-schedule-interval")?.value||"daily",a=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!l){showNotification("Please enter an App ID","warning");return}try{var t=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,schedule:s,retention:{keep:a},enabled:!0})}),n=await t.json();if(n.success){showNotification("Schedule created for "+l,"success"),I();var r=document.getElementById("new-schedule-appid");r&&(r.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(m){showNotification("Error: "+m.message,"error")}}async function c(){if(P){P.innerHTML='
Loading...
';try{var l=await fetch("/api/v1/backups/files"),s=await l.json();if(!s.success)throw new Error(s.error||"Failed to load");var a=s.files||[];if(a.length===0){P.innerHTML='
"}}}window.__restoreServerBackup=async function(l){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var s=await secureFetch("/api/v1/backups/restore/"+l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),a=await s.json();a.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(a.error||"Unknown error"),"error")}catch(t){showNotification("Restore error: "+t.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",I),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",c),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",g),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",d);async function g(){if(O){try{var l=await fetch("/api/v1/license/status"),s=await l.json();if(s.tier!=="premium"){O.innerHTML='
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
"}}}async function $(l,s){try{var a=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,...s})}),t=await a.json();t.success?showNotification("Schedule updated for "+l,"success"):(showNotification("Update failed: "+(t.error||"Unknown"),"error"),I())}catch(n){showNotification("Error: "+n.message,"error")}}async function E(l){try{var s=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(l),{method:"POST",headers:{"Content-Type":"application/json"}}),a=await s.json();a.success?showNotification("Backup started for "+l+"!","success"):showNotification("Backup failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function u(l){if(confirm("Remove backup schedule for "+l+"?"))try{var s=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(l),{method:"DELETE"}),a=await s.json();a.success?(showNotification("Schedule removed for "+l,"success"),I()):showNotification("Delete failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function o(){var l=document.getElementById("new-schedule-appid")?.value?.trim(),s=document.getElementById("new-schedule-interval")?.value||"daily",a=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!l){showNotification("Please enter an App ID","warning");return}try{var t=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,schedule:s,retention:{keep:a},enabled:!0})}),n=await t.json();if(n.success){showNotification("Schedule created for "+l,"success"),I();var r=document.getElementById("new-schedule-appid");r&&(r.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(m){showNotification("Error: "+m.message,"error")}}async function c(){if(P){P.innerHTML='
Loading...
';try{var l=await fetch("/api/v1/backups/files"),s=await l.json();if(!s.success)throw new Error(s.error||"Failed to load");var a=s.files||[];if(a.length===0){P.innerHTML='
"}}}window.__restoreServerBackup=async function(l){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var s=await secureFetch("/api/v1/backups/restore/"+l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),a=await s.json();a.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(a.error||"Unknown error"),"error")}catch(t){showNotification("Restore error: "+t.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",I),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",c),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",g),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",d);async function g(){if(O){try{var l=await fetch("/api/v1/license/status"),s=await l.json();if(s.tier!=="premium"){O.innerHTML='
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
Configuration differs \u2014 restoring will replace current settings
':r+='
No changes
',r+="
"}r+='
',document.body.insertAdjacentHTML("beforeend",r),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function(F){F.target===this&&this.remove()})}catch(F){showNotification("Compare error: "+F.message,"error")}}async function i(l,s){if(confirm("Restore "+s+" for "+l+`?
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var a=await secureFetch("/api/v1/apps/"+encodeURIComponent(l)+"/revert/"+encodeURIComponent(s),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),t=await a.json();t.success?(showNotification(l+" restored to "+s,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(t.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`
@@ -1305,7 +1305,7 @@ This will replace current configuration, credentials, and data. Containers will
- `);const b=document.getElementById("stats-modal"),h=document.getElementById("container-stats-btn"),j=document.getElementById("stats-cancel"),v=document.getElementById("stats-refresh-btn"),D=document.getElementById("stats-auto-refresh"),M=document.getElementById("stats-container"),$=document.getElementById("stats-aggregated-container"),R=document.getElementById("stats-alerts-container"),y=document.getElementById("stats-last-update");let L=null,w=null;function z(d){if(d===0||!d)return"0 B";const g=1024,p=["B","KB","MB","GB"],e=Math.floor(Math.log(d)/Math.log(g));return parseFloat((d/Math.pow(g,e)).toFixed(1))+" "+p[e]}function x(d){return d<30?"#2ecc71":d<70?"#f39c12":"#e74c3c"}function C(d){return d<50?"#2ecc71":d<80?"#f39c12":"#e74c3c"}async function k(){try{let d=null,g=!1;try{const i=await(await fetch("/api/v1/monitoring/stats")).json();i.success&&i.stats&&(d=i.stats,g=!0,w=i.stats)}catch{}if(!g){const i=await(await fetch("/api/v1/stats/containers")).json();if(i.success&&i.stats){d={};for(const l of i.stats)d[l.name]={name:l.name,current:{cpu:l.cpu,memory:{percent:l.memory.percent,usage:l.memory.used,limit:l.memory.limit,usageMB:Math.round(l.memory.used/1048576),limitMB:Math.round(l.memory.limit/1048576)},network:{rxBytes:l.network.rx,txBytes:l.network.tx,rxMB:(l.network.rx/1048576).toFixed(1),txMB:(l.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:l.status};w=d}}if(!d||Object.keys(d).length===0){M.innerHTML='
';try{const i=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${p}&endTime=${g}`)).json();if(!i.success)throw new Error(i.error||"Failed to load history");const l=i.samples||[],s=i.tier||"raw";if(l.length===0){O.innerHTML=`
\u{1F4CA}No data for the last ${I}. Tier: ${E(s)}.
`;return}const a=s==="raw",t=a?F=>F.cpu?.percent:F=>F.cpu?.avg,n=a?F=>F.memory?.percent:F=>F.memory?.avgPercent,r=a?F=>F.network?.rxMB||0:F=>F.network?.rxMB||0,m=a?F=>F.network?.txMB||0:F=>F.network?.txMB||0;let A=`
+ `}function o(){if(!P)return;const d=k||{},g=P.value,p=Object.entries(d);if(p.length===0){P.innerHTML='';return}P.innerHTML=p.map(([e,i])=>``).join(""),g&&d[g]&&(P.value=g)}async function c(){if(!O||!P)return;const d=P.value;if(!d){O.innerHTML='
';try{const i=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${p}&endTime=${g}`)).json();if(!i.success)throw new Error(i.error||"Failed to load history");const l=i.samples||[],s=i.tier||"raw";if(l.length===0){O.innerHTML=`
\u{1F4CA}No data for the last ${I}. Tier: ${E(s)}.
@@ -1561,7 +1561,7 @@ This will replace current configuration, credentials, and data. Containers will
- `);const b=document.getElementById("health-modal"),h=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),v=document.getElementById("health-refresh-btn"),D=document.getElementById("health-status-container"),M=document.getElementById("health-incidents-container"),$=document.getElementById("health-config-container"),R=document.getElementById("health-last-update"),y=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),z=document.getElementById("health-form-cancel"),x=document.getElementById("health-form-save"),C="dashcaddy-health-settings",k={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},T=document.getElementById("health-global-save"),N=document.getElementById("health-global-reset"),f=document.getElementById("health-global-status"),B=document.getElementById("health-setting-retention"),P=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),S=document.getElementById("health-setting-max-entries"),I=document.getElementById("health-setting-disk-threshold");function H(){try{const a=safeGet(C),t=a?JSON.parse(a):{};return Object.assign({},k,t)}catch{return Object.assign({},k)}}function E(){const a=H();B&&(B.value=a.retentionDays),P&&(P.value=a.pollingInterval),O&&(O.value=a.statsPollingInterval),S&&(S.value=a.maxEntriesPerService),I&&(I.value=a.diskUsageThreshold)}function u(){const a={retentionDays:Math.max(1,Math.min(3650,parseInt(B?.value)||k.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(P?.value)||k.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||k.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(S?.value)||k.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(I?.value)||k.diskUsageThreshold))};try{safeSet(C,JSON.stringify(a)),E(),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(t){f&&(f.textContent="Save failed",f.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+t.message,"error")}}function o(){try{safeSet(C,JSON.stringify(k))}catch{}E(),f&&(f.textContent="Reset to defaults \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500))}E(),T?.addEventListener("click",u),N?.addEventListener("click",o);let c=null;function d(a){return a>=99.9?"var(--ok-fg)":a>=95?"#f39c12":"var(--bad-fg)"}function g(a){const t={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${a}`}async function p(){try{const t=await(await fetch("/api/v1/health-checks/status")).json();if(!t.success||!t.status||Object.keys(t.status).length===0){D.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const n=Object.values(t.status);let r='
';r+='
',r+='
Service
Status
',r+='
Uptime 24h
Uptime 7d
',r+='
Avg Response
Last Check
';for(const m of n){const A=m.status==="up",F=A?"var(--dot-ok)":"var(--dot-bad)",_=m.uptime?.["24h"]??"-",U=m.uptime?.["7d"]??"-",q=m.avgResponseTime!=null?Math.round(m.avgResponseTime)+"ms":"-",J=m.timestamp?timeAgo(m.timestamp):"-";r+=`
`,r+=`
${escapeHtml(m.name||m.serviceId)}
`,r+=`
${A?"Up":"Down"}
`,r+=`
${typeof _=="number"?_.toFixed(1)+"%":_}
`,r+=`
${typeof U=="number"?U.toFixed(1)+"%":U}
`,r+=`
${q}
`,r+=`
${J}
`,r+="
",r+=`
Loading details...
`}r+="
",D.innerHTML=r,R.textContent="Updated "+new Date().toLocaleTimeString(),D.querySelectorAll("tr[data-health-id]").forEach(m=>{m.addEventListener("click",async()=>{const A=m.dataset.healthId,F=document.getElementById("health-detail-"+A);if(F){if(F.style.display!=="none"){F.style.display="none";return}F.style.display="";try{const U=await(await fetch(`/api/v1/health-checks/${A}/stats?hours=24`)).json();if(U.success&&U.stats){const q=U.stats,J=q.responseTime||{};F.querySelector("td").innerHTML=`
+ `);const x=document.getElementById("health-modal"),h=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),v=document.getElementById("health-refresh-btn"),D=document.getElementById("health-status-container"),H=document.getElementById("health-incidents-container"),B=document.getElementById("health-config-container"),R=document.getElementById("health-last-update"),y=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),k=document.getElementById("health-form-title"),M=document.getElementById("health-form-cancel"),w=document.getElementById("health-form-save"),z="dashcaddy-health-settings",b={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},C=document.getElementById("health-global-save"),N=document.getElementById("health-global-reset"),f=document.getElementById("health-global-status"),T=document.getElementById("health-setting-retention"),P=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),S=document.getElementById("health-setting-max-entries"),I=document.getElementById("health-setting-disk-threshold");function $(){try{const a=safeGet(z),t=a?JSON.parse(a):{};return Object.assign({},b,t)}catch{return Object.assign({},b)}}function E(){const a=$();T&&(T.value=a.retentionDays),P&&(P.value=a.pollingInterval),O&&(O.value=a.statsPollingInterval),S&&(S.value=a.maxEntriesPerService),I&&(I.value=a.diskUsageThreshold)}function u(){const a={retentionDays:Math.max(1,Math.min(3650,parseInt(T?.value)||b.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(P?.value)||b.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||b.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(S?.value)||b.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(I?.value)||b.diskUsageThreshold))};try{safeSet(z,JSON.stringify(a)),E(),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(t){f&&(f.textContent="Save failed",f.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+t.message,"error")}}function o(){try{safeSet(z,JSON.stringify(b))}catch{}E(),f&&(f.textContent="Reset to defaults \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500))}E(),C?.addEventListener("click",u),N?.addEventListener("click",o);let c=null;function d(a){return a>=99.9?"var(--ok-fg)":a>=95?"#f39c12":"var(--bad-fg)"}function g(a){const t={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${a}`}async function p(){try{const t=await(await fetch("/api/v1/health-checks/status")).json();if(!t.success||!t.status||Object.keys(t.status).length===0){D.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const n=Object.values(t.status);let r='
';r+='
',r+='
Service
Status
',r+='
Uptime 24h
Uptime 7d
',r+='
Avg Response
Last Check
';for(const m of n){const A=m.status==="up",F=A?"var(--dot-ok)":"var(--dot-bad)",_=m.uptime?.["24h"]??"-",U=m.uptime?.["7d"]??"-",q=m.avgResponseTime!=null?Math.round(m.avgResponseTime)+"ms":"-",J=m.timestamp?timeAgo(m.timestamp):"-";r+=`
';for(const _ of F){const U=_.status==="resolved",q=U&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";m+='
',m+=`
${escapeHtml(_.serviceId)}
`,m+=`
${escapeHtml(_.type)}
`,m+=`
${g(_.severity)}
`,m+=`
${_.status}
`,m+=`
${q}
`,m+=`
${timeAgo(_.createdAt)}
`,m+="
"}m+="
"}M.innerHTML=m||'
\u{1F6A8}No incidents recorded yet.
'}catch(a){M.innerHTML=`
Failed: ${escapeHtml(a.message)}
`}}async function i(){try{const t=await(await fetch("/api/v1/health-checks/status")).json(),n=t.success&&t.status?Object.values(t.status):[];if(n.length===0){$.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
`}}function l(a,t,n,r,m,A,F){c=a||null,w.textContent=a?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=a||"",document.getElementById("health-form-id").disabled=!!a,document.getElementById("health-form-name").value=t||"",document.getElementById("health-form-url").value=n||"",document.getElementById("health-form-timeout").value=r||1e4,document.getElementById("health-form-codes").value=m||"200",document.getElementById("health-form-sla").value=A||99.9,document.getElementById("health-form-slow").value=F||5e3,L.style.display="",y.style.display="none"}function s(){L.style.display="none",y.style.display="",c=null}y?.addEventListener("click",()=>l("","","",1e4,"200",99.9,5e3)),z?.addEventListener("click",s),x?.addEventListener("click",async()=>{const a=c||document.getElementById("health-form-id").value.trim();if(!a)return showNotification("Service ID is required","warning");const t=document.getElementById("health-form-url").value.trim();if(!t)return showNotification("URL is required","warning");const n=document.getElementById("health-form-codes").value.split(",").map(m=>parseInt(m.trim())).filter(Boolean),r={name:document.getElementById("health-form-name").value.trim()||a,url:t,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:n.length?n:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{x.textContent="Saving...",x.disabled=!0;const A=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(a)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).json();if(!A.success)throw new Error(A.error||"Save failed");s(),i(),p()}catch(m){showNotification("Error: "+m.message,"error")}finally{x.textContent="Save",x.disabled=!1}}),document.addEventListener("health-edit",async a=>{const t=a.detail;l(t,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async a=>{const t=a.detail;if(confirm(`Delete health check for "${t}"?`))try{const r=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(t)}/configure`,{method:"DELETE"})).json();if(!r.success)throw new Error(r.error);i(),p()}catch(n){showNotification("Error: "+n.message,"error")}}),h?.addEventListener("click",()=>{b?.classList.add("show"),p()}),wireModal(b,j),v?.addEventListener("click",p),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",e),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",i)})(),(function(){injectModal("updates-modal",`
';for(const _ of F){const U=_.status==="resolved",q=U&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";m+='
',m+=`
${escapeHtml(_.serviceId)}
`,m+=`
${escapeHtml(_.type)}
`,m+=`
${g(_.severity)}
`,m+=`
${_.status}
`,m+=`
${q}
`,m+=`
${timeAgo(_.createdAt)}
`,m+="
"}m+="
"}H.innerHTML=m||'
\u{1F6A8}No incidents recorded yet.
'}catch(a){H.innerHTML=`
Failed: ${escapeHtml(a.message)}
`}}async function i(){try{const t=await(await fetch("/api/v1/health-checks/status")).json(),n=t.success&&t.status?Object.values(t.status):[];if(n.length===0){B.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
`}}function l(a,t,n,r,m,A,F){c=a||null,k.textContent=a?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=a||"",document.getElementById("health-form-id").disabled=!!a,document.getElementById("health-form-name").value=t||"",document.getElementById("health-form-url").value=n||"",document.getElementById("health-form-timeout").value=r||1e4,document.getElementById("health-form-codes").value=m||"200",document.getElementById("health-form-sla").value=A||99.9,document.getElementById("health-form-slow").value=F||5e3,L.style.display="",y.style.display="none"}function s(){L.style.display="none",y.style.display="",c=null}y?.addEventListener("click",()=>l("","","",1e4,"200",99.9,5e3)),M?.addEventListener("click",s),w?.addEventListener("click",async()=>{const a=c||document.getElementById("health-form-id").value.trim();if(!a)return showNotification("Service ID is required","warning");const t=document.getElementById("health-form-url").value.trim();if(!t)return showNotification("URL is required","warning");const n=document.getElementById("health-form-codes").value.split(",").map(m=>parseInt(m.trim())).filter(Boolean),r={name:document.getElementById("health-form-name").value.trim()||a,url:t,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:n.length?n:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{w.textContent="Saving...",w.disabled=!0;const A=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(a)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).json();if(!A.success)throw new Error(A.error||"Save failed");s(),i(),p()}catch(m){showNotification("Error: "+m.message,"error")}finally{w.textContent="Save",w.disabled=!1}}),document.addEventListener("health-edit",async a=>{const t=a.detail;l(t,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async a=>{const t=a.detail;if(confirm(`Delete health check for "${t}"?`))try{const r=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(t)}/configure`,{method:"DELETE"})).json();if(!r.success)throw new Error(r.error);i(),p()}catch(n){showNotification("Error: "+n.message,"error")}}),h?.addEventListener("click",()=>{x?.classList.add("show"),p()}),wireModal(x,j),v?.addEventListener("click",p),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",e),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",i)})(),(function(){injectModal("updates-modal",`
\u2B06\uFE0F Update Management
@@ -1652,17 +1652,17 @@ This will replace current configuration, credentials, and data. Containers will
- `);const b=document.getElementById("updates-modal"),h=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),v=document.getElementById("updates-check-btn"),D=document.getElementById("updates-available-container"),M=document.getElementById("updates-history-container"),$=document.getElementById("updates-auto-container"),R=document.getElementById("updates-last-check");async function y(){try{const e=await(await fetch("/api/v1/updates/available")).json();if(!e.success)throw new Error(e.error);const i=e.updates||[];if(i.length===0){D.innerHTML='
';for(const t of i){const n=(()=>{const r=window.APPS||[];for(const m of r)if(m.containerId===t.containerId||m.name===t.containerName||m.id===t.containerName)return m.id;return t.containerName})();l+=`
`,l+=`
${escapeHtml(t.containerName)}
`,l+=`
${escapeHtml(t.imageName)}
`,l+=`
${escapeHtml(t.currentDigest)}
`,l+=`
${escapeHtml(t.latestDigest)}
`,l+='
',l+=``,l+=``,l+="
"}l+="
",D.innerHTML=l,R.textContent=i.length+" update(s) available";const s=document.getElementById("updates-count-badge"),a=document.getElementById("updates-update-all-btn");s&&(s.textContent=i.length+" pending",s.style.display=""),a&&i.length>0&&(a.style.display=""),window._pendingUpdates=i,D.querySelectorAll(".update-now-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Update "${r}" to the latest version? The container will restart.`)){t.textContent="Updating...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(A.success)t.textContent="Done!",t.style.background="var(--ok-fg)",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Update failed")}catch(m){t.textContent="Failed",t.style.color="var(--bad-fg)",showNotification("Update error: "+m.message,"error"),setTimeout(()=>{t.textContent="Update",t.disabled=!1,t.style.color="",t.style.background=""},3e3)}}})}),D.querySelectorAll(".rollback-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Rollback "${r}" to its previous version?`)){t.textContent="Rolling back...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(n)}`,{method:"POST"})).json();if(A.success)t.textContent="Rolled back!",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Rollback failed")}catch(m){t.textContent="Failed",showNotification("Rollback error: "+m.message,"error"),setTimeout(()=>{t.textContent="Rollback",t.disabled=!1},3e3)}}})})}catch(p){D.innerHTML=`
Failed: ${escapeHtml(p.message)}
`}}async function L(){const p=window._pendingUpdates||[];if(!p.length)return;const e=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${p.length} containers? Each will restart.`))return;e.textContent="\u23F3 Updating...",e.disabled=!0;let i=0,l=0;for(const s of p)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?i++:l++}catch{l++}e.textContent="\u2705 Done",showNotification(`Update all: ${i} succeeded, ${l} failed.`,i>0&&l===0?"success":"error"),setTimeout(()=>{e.textContent="\u2B06\uFE0F Update All",e.disabled=!1,y()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",L);async function w(){v.textContent="\u{1F50D} Checking...",v.disabled=!0;try{const e=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!e.success)throw new Error(e.error);v.textContent="\u2705 Done!",await y()}catch(p){v.textContent="\u274C Failed",showNotification("Check error: "+p.message,"error")}setTimeout(()=>{v.textContent="\u{1F50D} Check for Updates",v.disabled=!1},3e3)}async function z(){try{M.innerHTML='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';t+='
',t+='
Container
Schedule
Window
Rollback
Last Run
Actions
';for(const n of s){const r=n.name||n.Names?.[0]?.replace(/^\//,"")||n.Id?.substring(0,12),m=n.containerId||n.Id,A=a[m]||{},F=A.enabled?A.schedule||"weekly":"",_=A.autoRollback!==!1,U=A.maintenanceWindow||"",q=A.lastAutoUpdate?timeAgo(A.lastAutoUpdate):"Never";t+=`
`,t+=`
${escapeHtml(r)}
`,t+=`
+ `);const x=document.getElementById("updates-modal"),h=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),v=document.getElementById("updates-check-btn"),D=document.getElementById("updates-available-container"),H=document.getElementById("updates-history-container"),B=document.getElementById("updates-auto-container"),R=document.getElementById("updates-last-check");async function y(){try{const e=await(await fetch("/api/v1/updates/available")).json();if(!e.success)throw new Error(e.error);const i=e.updates||[];if(i.length===0){D.innerHTML='
';for(const t of i){const n=(()=>{const r=window.APPS||[];for(const m of r)if(m.containerId===t.containerId||m.name===t.containerName||m.id===t.containerName)return m.id;return t.containerName})();l+=`
`,l+=`
${escapeHtml(t.containerName)}
`,l+=`
${escapeHtml(t.imageName)}
`,l+=`
${escapeHtml(t.currentDigest)}
`,l+=`
${escapeHtml(t.latestDigest)}
`,l+='
',l+=``,l+=``,l+="
"}l+="
",D.innerHTML=l,R.textContent=i.length+" update(s) available";const s=document.getElementById("updates-count-badge"),a=document.getElementById("updates-update-all-btn");s&&(s.textContent=i.length+" pending",s.style.display=""),a&&i.length>0&&(a.style.display=""),window._pendingUpdates=i,D.querySelectorAll(".update-now-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Update "${r}" to the latest version? The container will restart.`)){t.textContent="Updating...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(A.success)t.textContent="Done!",t.style.background="var(--ok-fg)",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Update failed")}catch(m){t.textContent="Failed",t.style.color="var(--bad-fg)",showNotification("Update error: "+m.message,"error"),setTimeout(()=>{t.textContent="Update",t.disabled=!1,t.style.color="",t.style.background=""},3e3)}}})}),D.querySelectorAll(".rollback-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Rollback "${r}" to its previous version?`)){t.textContent="Rolling back...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(n)}`,{method:"POST"})).json();if(A.success)t.textContent="Rolled back!",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Rollback failed")}catch(m){t.textContent="Failed",showNotification("Rollback error: "+m.message,"error"),setTimeout(()=>{t.textContent="Rollback",t.disabled=!1},3e3)}}})})}catch(p){D.innerHTML=`
Failed: ${escapeHtml(p.message)}
`}}async function L(){const p=window._pendingUpdates||[];if(!p.length)return;const e=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${p.length} containers? Each will restart.`))return;e.textContent="\u23F3 Updating...",e.disabled=!0;let i=0,l=0;for(const s of p)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?i++:l++}catch{l++}e.textContent="\u2705 Done",showNotification(`Update all: ${i} succeeded, ${l} failed.`,i>0&&l===0?"success":"error"),setTimeout(()=>{e.textContent="\u2B06\uFE0F Update All",e.disabled=!1,y()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",L);async function k(){v.textContent="\u{1F50D} Checking...",v.disabled=!0;try{const e=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!e.success)throw new Error(e.error);v.textContent="\u2705 Done!",await y()}catch(p){v.textContent="\u274C Failed",showNotification("Check error: "+p.message,"error")}setTimeout(()=>{v.textContent="\u{1F50D} Check for Updates",v.disabled=!1},3e3)}async function M(){try{H.innerHTML='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';t+='
',t+='
Container
Schedule
Window
Rollback
Last Run
Actions
';for(const n of s){const r=n.name||n.Names?.[0]?.replace(/^\//,"")||n.Id?.substring(0,12),m=n.containerId||n.Id,A=a[m]||{},F=A.enabled?A.schedule||"weekly":"",_=A.autoRollback!==!1,U=A.maintenanceWindow||"",q=A.lastAutoUpdate?timeAgo(A.lastAutoUpdate):"Never";t+=`
`}}const C=document.getElementById("dashcaddy-current-version"),k=document.getElementById("dashcaddy-update-badge"),T=document.getElementById("dashcaddy-update-details"),N=document.getElementById("dashcaddy-new-version"),f=document.getElementById("dashcaddy-changelog"),B=document.getElementById("dashcaddy-apply-btn"),P=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),S=document.getElementById("dashcaddy-status-bar"),I=document.getElementById("dashcaddy-history-container");let H=null;function E(p,e){S&&(S.style.display="block",S.style.background=e==="error"?"var(--bad-bg)":e==="success"?"var(--ok-bg)":"var(--bg)",S.style.color=e==="error"?"var(--bad-fg)":e==="success"?"var(--ok-fg)":"var(--fg)",S.textContent=p)}async function u(){try{const e=await(await fetch("/api/v1/system/version")).json();if(e.success){const i=e.commit&&e.commit!=="unknown"?e.commit:null;C.textContent="v"+e.version+(i?" ("+i.substring(0,7)+")":"")}}catch{C.textContent="Unable to fetch version"}}async function o(p){p||(P.textContent="Checking...",P.disabled=!0);try{const i=await(await fetch("/api/v1/system/update-check")).json();if(H=i,i.success&&i.available&&i.remote){k.style.display="",T.style.display="",N.textContent="v"+i.remote.version,f.textContent=i.remote.changelog||"No changelog available.";const l=document.getElementById("updates-btn");if(l&&!l.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",l.style.position="relative",l.appendChild(a)}const s=document.getElementById("updates-dashcaddy-tab");if(s&&!s.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",s.appendChild(a)}}else k.style.display="none",T.style.display="none",await u(),p||E("You are running the latest version.","success");p||(P.textContent="Check for Updates",P.disabled=!1)}catch(e){p||(E("Failed to check: "+e.message,"error"),P.textContent="Check for Updates",P.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;B.textContent="Updating...",B.disabled=!0,E("Downloading and applying update...","info");try{const e=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(e.success)return E("Update initiated: v"+(e.fromVersion||"?")+" \u2192 v"+(e.toVersion||"?")+". The container will restart shortly.","success"),B.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(i=>i.remove()),!0;throw new Error(e.error||"Update failed")}catch(p){throw E("Update failed: "+p.message,"error"),B.textContent="Update Now",B.disabled=!1,p}}async function d(){try{const e=await(await fetch("/api/v1/system/update-history")).json(),i=e.success&&e.history?e.history:[];if(i.length===0){I.innerHTML='
\u{1F4E6}No self-update history.
';return}let l='
';l+='
When
Version
From
Status
';for(const s of i){const a=s.status==="success"?"\u2713 success":s.status==="pending"?"\u23F3 pending":s.status==="partial"?"\u26A0 partial":"\u2717 "+s.status,t=s.status==="success"?"var(--ok-fg)":s.status==="pending"?"var(--muted)":"var(--bad-fg)";l+='
`}}const z=document.getElementById("dashcaddy-current-version"),b=document.getElementById("dashcaddy-update-badge"),C=document.getElementById("dashcaddy-update-details"),N=document.getElementById("dashcaddy-new-version"),f=document.getElementById("dashcaddy-changelog"),T=document.getElementById("dashcaddy-apply-btn"),P=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),S=document.getElementById("dashcaddy-status-bar"),I=document.getElementById("dashcaddy-history-container");let $=null;function E(p,e){S&&(S.style.display="block",S.style.background=e==="error"?"var(--bad-bg)":e==="success"?"var(--ok-bg)":"var(--bg)",S.style.color=e==="error"?"var(--bad-fg)":e==="success"?"var(--ok-fg)":"var(--fg)",S.textContent=p)}async function u(){try{const e=await(await fetch("/api/v1/system/version")).json();if(e.success){const i=e.commit&&e.commit!=="unknown"?e.commit:null;z.textContent="v"+e.version+(i?" ("+i.substring(0,7)+")":"")}}catch{z.textContent="Unable to fetch version"}}async function o(p){p||(P.textContent="Checking...",P.disabled=!0);try{const i=await(await fetch("/api/v1/system/update-check")).json();if($=i,i.success&&i.available&&i.remote){b.style.display="",C.style.display="",N.textContent="v"+i.remote.version,f.textContent=i.remote.changelog||"No changelog available.";const l=document.getElementById("updates-btn");if(l&&!l.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",l.style.position="relative",l.appendChild(a)}const s=document.getElementById("updates-dashcaddy-tab");if(s&&!s.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",s.appendChild(a)}}else b.style.display="none",C.style.display="none",await u(),p||E("You are running the latest version.","success");p||(P.textContent="Check for Updates",P.disabled=!1)}catch(e){p||(E("Failed to check: "+e.message,"error"),P.textContent="Check for Updates",P.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;T.textContent="Updating...",T.disabled=!0,E("Downloading and applying update...","info");try{const e=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(e.success)return E("Update initiated: v"+(e.fromVersion||"?")+" \u2192 v"+(e.toVersion||"?")+". The container will restart shortly.","success"),T.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(i=>i.remove()),!0;throw new Error(e.error||"Update failed")}catch(p){throw E("Update failed: "+p.message,"error"),T.textContent="Update Now",T.disabled=!1,p}}async function d(){try{const e=await(await fetch("/api/v1/system/update-history")).json(),i=e.success&&e.history?e.history:[];if(i.length===0){I.innerHTML='
\u{1F4E6}No self-update history.
';return}let l='
';l+='
When
Version
From
Status
';for(const s of i){const a=s.status==="success"?"\u2713 success":s.status==="pending"?"\u23F3 pending":s.status==="partial"?"\u26A0 partial":"\u2717 "+s.status,t=s.status==="success"?"var(--ok-fg)":s.status==="pending"?"var(--muted)":"var(--bad-fg)";l+='
"}}async function g(){try{const e=await(await fetch("/api/v1/system/rollback-versions")).json(),i=e.success&&e.versions?e.versions:[];if(i.length===0){showNotification("No rollback versions available.","info");return}const l=prompt(`Available rollback versions:
`+i.join(`
`)+`
-Enter version to rollback to:`);if(!l)return;if(!i.includes(l)){showNotification("Invalid version: "+l,"error");return}if(!confirm("Rollback DashCaddy to v"+l+"? The container will restart."))return;E("Rolling back to v"+l+"...","info");const a=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:l})})).json();if(a.success)E("Rollback to v"+l+" initiated. Container will restart.","success");else throw new Error(a.error||"Rollback failed")}catch(p){E("Rollback failed: "+p.message,"error")}}P?.addEventListener("click",()=>o(!1)),B?.addEventListener("click",()=>c().catch(()=>{})),O?.addEventListener("click",g),v?.addEventListener("click",w),h?.addEventListener("click",()=>{b?.classList.add("show"),y()}),wireModal(b,j),window.openUpdateModal=function(p){b?.classList.add("show"),y().then(()=>{if(!p)return;const e=D.querySelector(`[data-app-id="${p}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{e.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",z),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",x),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{u(),d(),H||o(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=o,setTimeout(()=>o(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
+Enter version to rollback to:`);if(!l)return;if(!i.includes(l)){showNotification("Invalid version: "+l,"error");return}if(!confirm("Rollback DashCaddy to v"+l+"? The container will restart."))return;E("Rolling back to v"+l+"...","info");const a=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:l})})).json();if(a.success)E("Rollback to v"+l+" initiated. Container will restart.","success");else throw new Error(a.error||"Rollback failed")}catch(p){E("Rollback failed: "+p.message,"error")}}P?.addEventListener("click",()=>o(!1)),T?.addEventListener("click",()=>c().catch(()=>{})),O?.addEventListener("click",g),v?.addEventListener("click",k),h?.addEventListener("click",()=>{x?.classList.add("show"),y()}),wireModal(x,j),window.openUpdateModal=function(p){x?.classList.add("show"),y().then(()=>{if(!p)return;const e=D.querySelector(`[data-app-id="${p}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{e.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",M),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",w),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{u(),d(),$||o(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=o,setTimeout(()=>o(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
\u{1F433} Docker Resources
Manage volumes, networks, and view disk usage.
@@ -1711,7 +1711,7 @@ Enter version to rollback to:`);if(!l)return;if(!i.includes(l)){showNotification
",R.innerHTML=w,R.querySelectorAll(".dr-vol-del").forEach(z=>{z.addEventListener("click",async()=>{if(confirm(`Delete volume "${z.dataset.name}"? Data will be lost.`)){z.textContent="...",z.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(z.dataset.name)}?force=true`),D()}catch(x){showNotification("Delete failed: "+x.message,"error"),z.textContent="Delete",z.disabled=!1}}})})}catch(y){R.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-vol-name"),y=R.value.trim();if(!y){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:y}),R.value="",showNotification(`Volume "${y}" created`,"success"),D()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function M(){const R=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){R.innerHTML='
\u{1F310}No networks found.
';return}let w='
';w+='
Name
Driver
Scope
Containers
Actions
';for(const z of L){const x=["bridge","host","none"].includes(z.name);w+='
",R.innerHTML=k,R.querySelectorAll(".dr-vol-del").forEach(M=>{M.addEventListener("click",async()=>{if(confirm(`Delete volume "${M.dataset.name}"? Data will be lost.`)){M.textContent="...",M.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(M.dataset.name)}?force=true`),D()}catch(w){showNotification("Delete failed: "+w.message,"error"),M.textContent="Delete",M.disabled=!1}}})})}catch(y){R.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-vol-name"),y=R.value.trim();if(!y){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:y}),R.value="",showNotification(`Volume "${y}" created`,"success"),D()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function H(){const R=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){R.innerHTML='
\u{1F310}No networks found.
';return}let k='
';k+='
Name
Driver
Scope
Containers
Actions
';for(const M of L){const w=["bridge","host","none"].includes(M.name);k+='
';for(const w of y.results){const z=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";L+='
';for(const k of y.results){const M=k.status==="deployed"||k.status==="created"?"\u2705":k.status==="exists"?"\u26A1":k.status==="skipped"?"\u23ED":"\u274C";L+='
`,w.style.display="none";return}if(!P&&O!==C)return;const d=Array.isArray(c.entries)?c.entries:[];if(d.length===0&&!P){const p=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";L.innerHTML=`
\u{1F4DC}${escapeHtml(p)}
`,w.style.display="none";return}let g="";P||(g='
',g+='
',g+='
When
',g+='
Actor
',g+='
IP
',g+='
Action
',g+='
Resource
',g+='
Result
',g+="
");for(const p of d){const e=p.outcome==="success",i=f(p);g+='
`,k.style.display="none";return}if(!P&&O!==z)return;const d=Array.isArray(c.entries)?c.entries:[];if(d.length===0&&!P){const p=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";L.innerHTML=`
\u{1F4DC}${escapeHtml(p)}
`,k.style.display="none";return}let g="";P||(g='
',g+='
',g+='
When
',g+='
Actor
',g+='
IP
',g+='
Action
',g+='
Resource
',g+='
Result
',g+="
");for(const p of d){const e=p.outcome==="success",i=f(p);g+='
`}async function S(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],d=T.value;T.innerHTML=''+c.map(g=>``).join(""),d&&(T.value=d)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",H),document.getElementById("sec-hosts-refresh").addEventListener("click",I);async function I(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];$=c;const d=document.getElementById("sec-hosts-container");if(!c.length){d.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
`}async function S(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],d=C.value;C.innerHTML=''+c.map(g=>``).join(""),d&&(C.value=d)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",$),document.getElementById("sec-hosts-refresh").addEventListener("click",I);async function I(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];B=c;const d=document.getElementById("sec-hosts-container");if(!c.length){d.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
${E(g.label||g.id)}${E(g.type)}
@@ -1911,7 +1911,7 @@ Enter version to rollback to:`);if(!l)return;if(!i.includes(l)){showNotification
${p}
${g.id==="self"?"":``}
-
`}).join(""),d.querySelectorAll(".sec-host-del").forEach(g=>{g.addEventListener("click",async()=>{confirm(`Remove host ${g.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(g.dataset.id)}`,{method:"DELETE"}),I())})})}catch(o){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+E(o.message)+"
"}}async function H(){const o=prompt("Host id (lowercase, no spaces):");if(!o)return;const c=prompt("Display label:",o)||o,d=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const g=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,label:c,type:d})}),p=await g.json();if(!g.ok){alert("Failed: "+(p?.error?.message||g.statusText));return}alert(`\u2705 Host registered!
+ `}).join(""),d.querySelectorAll(".sec-host-del").forEach(g=>{g.addEventListener("click",async()=>{confirm(`Remove host ${g.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(g.dataset.id)}`,{method:"DELETE"}),I())})})}catch(o){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+E(o.message)+"
"}}async function $(){const o=prompt("Host id (lowercase, no spaces):");if(!o)return;const c=prompt("Display label:",o)||o,d=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const g=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,label:c,type:d})}),p=await g.json();if(!g.ok){alert("Failed: "+(p?.error?.message||g.statusText));return}alert(`\u2705 Host registered!
id: ${p.data.host.id}
label: ${p.data.host.label}
@@ -1922,7 +1922,7 @@ type: ${p.data.host.type}
${p.data.api_key}
Send this key as: Authorization: Bearer
-To endpoint: POST /api/v1/security/events/ingest or /events/batch`),I()}catch(g){alert("Failed: "+g.message)}}function E(o){return String(o).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function u(o,c){let d;return function(){clearTimeout(d),d=setTimeout(()=>o.apply(this,arguments),c)}}})(),window.__dc133_buildRepoOptions=function(b,h){var j=h||function(v){return String(v).replace(/[&<>"']/g,function(D){return{"&":"&","<":"<",">":">",'"':""","'":"'"}[D]})};return''+(b||[]).map(function(v){return'"}).join("")},window.__dc133_requestToken=function(b,h){if(b)return"";var j=String(h||"").trim();return j||void 0},(function(){injectModal("deploys-modal",`
+To endpoint: POST /api/v1/security/events/ingest or /events/batch`),I()}catch(g){alert("Failed: "+g.message)}}function E(o){return String(o).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function u(o,c){let d;return function(){clearTimeout(d),d=setTimeout(()=>o.apply(this,arguments),c)}}})(),window.__dc133_buildRepoOptions=function(x,h){var j=h||function(v){return String(v).replace(/[&<>"']/g,function(D){return{"&":"&","<":"<",">":">",'"':""","'":"'"}[D]})};return''+(x||[]).map(function(v){return'"}).join("")},window.__dc133_requestToken=function(x,h){if(x)return"";var j=String(h||"").trim();return j||void 0},(function(){injectModal("deploys-modal",`
\u{1F69A} Deploys
@@ -2006,16 +2006,16 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),I()}catch(g)
-
`);const b=N=>document.getElementById(N);let h=null,j=!1;function v(N){return window.escapeHtml?window.escapeHtml(String(N)):String(N).replace(/[&<>"']/g,f=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[f])}async function D(N,f){const B=await fetch("/dashcaddy-api/api/v1/deploys"+N,Object.assign({credentials:"include"},f||{}));let P=null;try{P=await B.json()}catch{P={success:!1,error:"non-JSON response"}}return{status:B.status,body:P}}function M(N){const f=b("dep-output");f.style.display="block",f.textContent=N||"(no output)",f.scrollTop=f.scrollHeight}async function $(){const N=b("dep-services"),{body:f}=await D("/services");if(!f.success){N.innerHTML=""+v(f.error||"unavailable")+"";return}const B=f.services||[];if(!B.length){N.innerHTML="No shipdeck deployments on record yet.";return}N.innerHTML='
Service
Last action
When
Release
'+B.map(P=>"
"+v(P.name)+"
"+v(P.last_action)+"
"+v(P.last_time)+"
"+v(P.last_epoch)+'
').join("")+"
"}async function R(){const N=b("dep-repo-select"),{body:f}=await D("/repos");if(!f.success){N.innerHTML="";return}const B=f.repos||[];N.innerHTML=B.length?B.map(P=>'").join(""):''}async function y(N){const f=b("dep-journal"),B=N?"?service="+encodeURIComponent(N):"",{body:P}=await D("/journal"+B),O=P.rows||[];if(!O.length){f.innerHTML="No journal rows.";return}f.innerHTML='
Time
Service
Action
Release
Duration
'+O.map(S=>"
"+v(S.time)+"
"+v(S.service)+"
"+v(S.action)+"
"+v(S.epoch)+"
"+v(S.duration||"\u2014")+"
").join("")+"
"}async function L(){const N=document.getElementById("dep-gh-gitea"),f=document.getElementById("dep-gh-gitea-host"),B=document.getElementById("dep-gh-gitea-token"),P=document.getElementById("dep-gh-anonymous"),O={};if(f&&f.value.trim()&&(O.gitea_url="https://"+f.value.trim().replace(/^https?:\/*/,"")),P&&P.checked)O.token="";else{const S=window.__dc133_requestToken(!1,B&&B.value);S!==void 0&&(O.token=S)}try{const{status:S,body:I}=await D("/gitea-repos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!I.success||!(I.repos||[]).length){N.innerHTML='";return}N.innerHTML=window.__dc133_buildRepoOptions(I.repos,v)}catch{N.innerHTML=''}}async function w(){const N=document.getElementById("dep-gh-btn"),f=document.getElementById("dep-gh-url").value.trim(),B=(document.getElementById("dep-gh-service").value.trim()||"").toLowerCase(),P=document.getElementById("dep-gh-args").value.trim();if(!f||!B){M("Repo URL and name are required.");return}const O=P?P.split(/\s+/):[];z(!0,N,"Install"),M("Installing "+f+`
-Cloning, building, gating and DNS-ing... (~30-60s)`);try{const S=!!(document.getElementById("dep-gh-anonymous")||{}).checked,I=(document.getElementById("dep-gh-gitea-token")||{value:""}).value,H=window.__dc133_requestToken(S,I),{status:E,body:u}=await D("/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo_url:f,service:B,args:O,token:H})});if(!u.success){M((u.output?u.output+`
-`:"")+"FAIL "+(u.error||"HTTP "+E)),z(!1,N,"Install");return}const o=u.service||{};if(!(window.APPS||[]).some(d=>d.id===o.id)){const d={id:o.id,name:o.name||o.id,url:o.url,logo:o.logo,tailscaleOnly:!0,isCustom:!0};try{await fetch("/dashcaddy-api/api/v1/services",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),window.APPS.push(d),typeof window.renderApps=="function"&&window.renderApps(),typeof window.renderGrid=="function"&&window.renderGrid()}catch{}}M("INSTALLED "+(o.name||o.id)+" in "+(o.deploy_seconds||"?")+`s
+ `);const x=N=>document.getElementById(N);let h=null,j=!1;function v(N){return window.escapeHtml?window.escapeHtml(String(N)):String(N).replace(/[&<>"']/g,f=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[f])}async function D(N,f){const T=await fetch("/dashcaddy-api/api/v1/deploys"+N,Object.assign({credentials:"include"},f||{}));let P=null;try{P=await T.json()}catch{P={success:!1,error:"non-JSON response"}}return{status:T.status,body:P}}function H(N){const f=x("dep-output");f.style.display="block",f.textContent=N||"(no output)",f.scrollTop=f.scrollHeight}async function B(){const N=x("dep-services"),{body:f}=await D("/services");if(!f.success){N.innerHTML=""+v(f.error||"unavailable")+"";return}const T=f.services||[];if(!T.length){N.innerHTML="No shipdeck deployments on record yet.";return}N.innerHTML='
Service
Last action
When
Release
'+T.map(P=>"
"+v(P.name)+"
"+v(P.last_action)+"
"+v(P.last_time)+"
"+v(P.last_epoch)+'
').join("")+"
"}async function R(){const N=x("dep-repo-select"),{body:f}=await D("/repos");if(!f.success){N.innerHTML="";return}const T=f.repos||[];N.innerHTML=T.length?T.map(P=>'").join(""):''}async function y(N){const f=x("dep-journal"),T=N?"?service="+encodeURIComponent(N):"",{body:P}=await D("/journal"+T),O=P.rows||[];if(!O.length){f.innerHTML="No journal rows.";return}f.innerHTML='
Time
Service
Action
Release
Duration
'+O.map(S=>"
"+v(S.time)+"
"+v(S.service)+"
"+v(S.action)+"
"+v(S.epoch)+"
"+v(S.duration||"\u2014")+"
").join("")+"
"}async function L(){const N=document.getElementById("dep-gh-gitea"),f=document.getElementById("dep-gh-gitea-host"),T=document.getElementById("dep-gh-gitea-token"),P=document.getElementById("dep-gh-anonymous"),O={};if(f&&f.value.trim()&&(O.gitea_url="https://"+f.value.trim().replace(/^https?:\/*/,"")),P&&P.checked)O.token="";else{const S=window.__dc133_requestToken(!1,T&&T.value);S!==void 0&&(O.token=S)}try{const{status:S,body:I}=await D("/gitea-repos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!I.success||!(I.repos||[]).length){N.innerHTML='";return}N.innerHTML=window.__dc133_buildRepoOptions(I.repos,v)}catch{N.innerHTML=''}}async function k(){const N=document.getElementById("dep-gh-btn"),f=document.getElementById("dep-gh-url").value.trim(),T=(document.getElementById("dep-gh-service").value.trim()||"").toLowerCase(),P=document.getElementById("dep-gh-args").value.trim();if(!f||!T){H("Repo URL and name are required.");return}const O=P?P.split(/\s+/):[];M(!0,N,"Install"),H("Installing "+f+`
+Cloning, building, gating and DNS-ing... (~30-60s)`);try{const S=!!(document.getElementById("dep-gh-anonymous")||{}).checked,I=(document.getElementById("dep-gh-gitea-token")||{value:""}).value,$=window.__dc133_requestToken(S,I),{status:E,body:u}=await D("/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo_url:f,service:T,args:O,token:$})});if(!u.success){H((u.output?u.output+`
+`:"")+"FAIL "+(u.error||"HTTP "+E)),M(!1,N,"Install");return}const o=u.service||{};if(!(window.APPS||[]).some(d=>d.id===o.id)){const d={id:o.id,name:o.name||o.id,url:o.url,logo:o.logo,tailscaleOnly:!0,isCustom:!0};try{await fetch("/dashcaddy-api/api/v1/services",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),window.APPS.push(d),typeof window.renderApps=="function"&&window.renderApps(),typeof window.renderGrid=="function"&&window.renderGrid()}catch{}}H("INSTALLED "+(o.name||o.id)+" in "+(o.deploy_seconds||"?")+`s
Card: `+(o.url||"")+`
-`+(u.output||"").slice(-800)),$()}catch(S){M("install error: "+S.message)}z(!1,N,"Install")}function z(N,f,B){f&&(f.disabled=N,B&&(f.textContent=N?"Working\u2026":B))}async function x(){const N=b("dep-deploy-btn"),f=b("dep-repo-select").value;if(f){z(!0,N,"Deploy"),M("Deploying "+f+`
-This can take ~30-60s\u2026`);try{const{body:B}=await D("/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:f})});M((B.output||B.error||"")+(B.success?`
+`+(u.output||"").slice(-800)),B()}catch(S){H("install error: "+S.message)}M(!1,N,"Install")}function M(N,f,T){f&&(f.disabled=N,T&&(f.textContent=N?"Working\u2026":T))}async function w(){const N=x("dep-deploy-btn"),f=x("dep-repo-select").value;if(f){M(!0,N,"Deploy"),H("Deploying "+f+`
+This can take ~30-60s\u2026`);try{const{body:T}=await D("/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:f})});H((T.output||T.error||"")+(T.success?`
\u2705 SUCCESS`:`
-\u274C FAILED`)),$()}catch(B){M("deploy error: "+B.message)}z(!1,N,"Deploy")}}async function C(N,f){if(confirm("Roll back "+N+" to the previous release?")){z(!0,f,"Rollback"),M("Rolling back "+N+"\u2026");try{const{body:B}=await D("/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:N})});M((B.output||B.error||"")+(B.success?`
+\u274C FAILED`)),B()}catch(T){H("deploy error: "+T.message)}M(!1,N,"Deploy")}}async function z(N,f){if(confirm("Roll back "+N+" to the previous release?")){M(!0,f,"Rollback"),H("Rolling back "+N+"\u2026");try{const{body:T}=await D("/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:N})});H((T.output||T.error||"")+(T.success?`
\u2705 ROLLED BACK`:`
-\u274C FAILED`)),$()}catch(B){M("rollback error: "+B.message)}z(!1,f,"Rollback")}}async function k(N,f){z(!0,f,"Status");try{const{body:B}=await D("/status?service="+encodeURIComponent(N));M(B.output||B.error||"(no output)")}catch(B){M("status error: "+B.message)}z(!1,f,"Status")}function T(){h=document.getElementById("deploys-btn"),h&&(h.addEventListener("click",async()=>{b("deploys-modal").classList.add("open"),j||(j=!0,$(),R(),y(""),L())}),b("dep-close").addEventListener("click",()=>{b("deploys-modal").classList.remove("open")}),document.querySelectorAll(".dep-tab").forEach(N=>{N.addEventListener("click",()=>{document.querySelectorAll(".dep-tab").forEach(f=>f.classList.remove("active")),N.classList.add("active"),document.querySelectorAll("#deploys-modal .dep-panel").forEach(f=>{f.style.display=f.dataset.panel===N.dataset.tab?"block":"none"})})}),b("dep-deploy-btn").addEventListener("click",x),b("dep-gh-btn").addEventListener("click",w),["dep-gh-gitea-host","dep-gh-gitea-token"].forEach(N=>{const f=document.getElementById(N);f&&f.addEventListener("change",()=>L())}),document.getElementById("dep-gh-gitea").addEventListener("change",N=>{const f=N.target.value;if(f){document.getElementById("dep-gh-url").value=f;const B=N.target.selectedOptions[0],P=B&&B.dataset?B.dataset.id:"",O=document.getElementById("dep-gh-service");P&&!O.value&&(O.value=P)}}),b("dep-journal-btn").addEventListener("click",()=>y(b("dep-journal-name").value.trim())),b("dep-status-btn").addEventListener("click",()=>{const N=b("dep-status-name").value.trim();N&&k(N)}),b("dep-services").addEventListener("click",N=>{const f=N.target.closest(".dep-rollback");if(f)return C(f.dataset.service,f);const B=N.target.closest(".dep-status");if(B)return k(B.dataset.service,B)}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",T):T()})(),(function(){const b=new ErrorHandler;injectModal("weather-modal",`