@stacksjs/ts-cloud 0.9.3 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/aws/index.js +1 -269
  2. package/dist/bin/chunk-00kg80qg.js +1 -0
  3. package/dist/bin/{chunk-hzqw8xm5.js → chunk-1k5kszjp.js} +1 -1
  4. package/dist/bin/{chunk-9v39615t.js → chunk-21e0mavm.js} +1 -1
  5. package/dist/bin/{chunk-waayf9ay.js → chunk-2empps47.js} +1 -1
  6. package/dist/bin/{chunk-14cwr6eh.js → chunk-3vqfexc4.js} +1 -1
  7. package/dist/bin/chunk-5ectjq0b.js +1 -0
  8. package/dist/bin/{chunk-b5gd39s8.js → chunk-5erkxpt7.js} +4 -4
  9. package/dist/bin/{chunk-41x17hw1.js → chunk-5mrtzemj.js} +1 -1
  10. package/dist/bin/{chunk-p8q9bq9g.js → chunk-5n9fmabb.js} +1 -1
  11. package/dist/bin/{chunk-gqf6jsmy.js → chunk-9knpg30y.js} +1 -1
  12. package/dist/bin/{chunk-r3kv0vm9.js → chunk-ddk4rt4j.js} +1 -1
  13. package/dist/bin/{chunk-avm7tnwe.js → chunk-e0rkrq70.js} +1 -1
  14. package/dist/bin/{chunk-ry030a6b.js → chunk-etrb03mt.js} +1 -1
  15. package/dist/bin/{chunk-8v7ddyvf.js → chunk-k9t9wvms.js} +1 -1
  16. package/dist/bin/{chunk-92mea34a.js → chunk-m7dgskt1.js} +1 -1
  17. package/dist/bin/{chunk-3r4fb59r.js → chunk-mz0wbbsj.js} +1 -1
  18. package/dist/bin/{chunk-b9qbp8j1.js → chunk-qk9qgepa.js} +1 -1
  19. package/dist/bin/chunk-rxcvf10f.js +7364 -0
  20. package/dist/bin/{chunk-r9hjwcj9.js → chunk-tga3hhwk.js} +1 -1
  21. package/dist/bin/{chunk-ynjvbphf.js → chunk-tx0tqq2k.js} +1 -1
  22. package/dist/bin/{chunk-57y1zxbf.js → chunk-vm3q5gf2.js} +1 -1
  23. package/dist/bin/{chunk-bz828v8q.js → chunk-y7s5r8y6.js} +1 -1
  24. package/dist/bin/{chunk-sgyffpgm.js → chunk-zmegvjp8.js} +1 -1
  25. package/dist/bin/cli.js +14 -14
  26. package/dist/bin/dashboard-server.js +1 -1
  27. package/dist/chunk-0ccta6z6.js +6 -0
  28. package/dist/chunk-0k1cs6pp.js +1 -0
  29. package/dist/chunk-1egjn203.js +704 -0
  30. package/dist/chunk-2wx29qga.js +5 -0
  31. package/dist/chunk-5m5rqmv7.js +1 -0
  32. package/dist/chunk-8ea5022g.js +114 -0
  33. package/dist/chunk-8xqn3c0w.js +2 -0
  34. package/dist/chunk-b4esxhmw.js +2 -0
  35. package/dist/chunk-b8e5wzwn.js +44 -0
  36. package/dist/chunk-bggt4n6e.js +2 -0
  37. package/dist/chunk-cwkg37rs.js +37 -0
  38. package/dist/chunk-dskvqt67.js +7355 -0
  39. package/dist/chunk-gahsdmxf.js +1617 -0
  40. package/dist/chunk-gnv3r2jg.js +1 -0
  41. package/dist/chunk-hg3c48cp.js +34 -0
  42. package/dist/chunk-m5azeva3.js +2 -0
  43. package/dist/chunk-r3qf56b3.js +92 -0
  44. package/dist/chunk-sdqa9ghv.js +141 -0
  45. package/dist/chunk-svrvvcm7.js +1 -0
  46. package/dist/chunk-v0p3hpc3.js +60 -0
  47. package/dist/chunk-wdzjbecg.js +50 -0
  48. package/dist/chunk-ww8k3g7j.js +1 -0
  49. package/dist/chunk-xmqfc62w.js +1 -0
  50. package/dist/chunk-xrebj679.js +435 -0
  51. package/dist/chunk-xt3s24vr.js +2 -0
  52. package/dist/chunk-y21zk0pn.js +4 -0
  53. package/dist/deploy/index.js +1 -168
  54. package/dist/dns/index.js +1 -41
  55. package/dist/drivers/index.js +1 -154
  56. package/dist/index.js +100 -6129
  57. package/dist/protection/index.js +1 -89
  58. package/dist/push/index.js +1 -509
  59. package/dist/spend/index.js +1 -173
  60. package/dist/ui/404.html +1 -1
  61. package/dist/ui/accept-invitation.html +1 -1
  62. package/dist/ui/access-denied.html +1 -1
  63. package/dist/ui/account/automation.html +6 -6
  64. package/dist/ui/account/security.html +2 -2
  65. package/dist/ui/applications/compose.html +6 -6
  66. package/dist/ui/applications/new.html +2 -2
  67. package/dist/ui/data/backups.html +5 -5
  68. package/dist/ui/data/services.html +5 -5
  69. package/dist/ui/data/volumes.html +6 -6
  70. package/dist/ui/index.html +6 -6
  71. package/dist/ui/infrastructure/topology.html +5 -5
  72. package/dist/ui/integrations.html +1 -1
  73. package/dist/ui/operations/alerts.html +5 -5
  74. package/dist/ui/operations/configuration.html +5 -5
  75. package/dist/ui/operations/jobs.html +5 -5
  76. package/dist/ui/operations/maintenance.html +5 -5
  77. package/dist/ui/operations/observability.html +6 -6
  78. package/dist/ui/operations/previews.html +6 -6
  79. package/dist/ui/operations/queue.html +6 -6
  80. package/dist/ui/operations/regions.html +6 -6
  81. package/dist/ui/operations/releases.html +6 -6
  82. package/dist/ui/operations/spend.html +6 -6
  83. package/dist/ui/operations/workloads.html +6 -6
  84. package/dist/ui/security.html +1 -1
  85. package/dist/ui/server/actions.html +5 -5
  86. package/dist/ui/server/activity.html +1 -1
  87. package/dist/ui/server/capacity.html +6 -6
  88. package/dist/ui/server/database.html +6 -6
  89. package/dist/ui/server/deployments.html +6 -6
  90. package/dist/ui/server/diagnostics.html +2 -2
  91. package/dist/ui/server/firewall.html +6 -6
  92. package/dist/ui/server/fleet.html +6 -6
  93. package/dist/ui/server/logs.html +6 -6
  94. package/dist/ui/server/metrics.html +6 -6
  95. package/dist/ui/server/security.html +2 -2
  96. package/dist/ui/server/services.html +1 -1
  97. package/dist/ui/server/sites.html +6 -6
  98. package/dist/ui/server/ssh-keys.html +6 -6
  99. package/dist/ui/server/team.html +6 -6
  100. package/dist/ui/server/terminal.html +1 -1
  101. package/dist/ui/serverless/alarms.html +5 -5
  102. package/dist/ui/serverless/assets.html +2 -2
  103. package/dist/ui/serverless/cost.html +1 -1
  104. package/dist/ui/serverless/data.html +6 -6
  105. package/dist/ui/serverless/deployments.html +2 -2
  106. package/dist/ui/serverless/firewall.html +1 -1
  107. package/dist/ui/serverless/functions.html +6 -6
  108. package/dist/ui/serverless/logs.html +6 -6
  109. package/dist/ui/serverless/metrics.html +2 -2
  110. package/dist/ui/serverless/queues.html +6 -6
  111. package/dist/ui/serverless/secrets.html +6 -6
  112. package/dist/ui/serverless/traces.html +6 -6
  113. package/dist/ui/serverless.html +5 -5
  114. package/package.json +3 -3
  115. package/dist/bin/chunk-jpjamjey.js +0 -6935
  116. package/dist/bin/chunk-m2zwtapr.js +0 -1
  117. package/dist/bin/chunk-rtczra13.js +0 -1
  118. package/dist/chunk-01d86gt1.js +0 -1324
  119. package/dist/chunk-050r7ycy.js +0 -46516
  120. package/dist/chunk-1c8dbv57.js +0 -7278
  121. package/dist/chunk-29rse4p1.js +0 -12203
  122. package/dist/chunk-32e7ya18.js +0 -642
  123. package/dist/chunk-4cjrg98a.js +0 -597
  124. package/dist/chunk-50jpda9q.js +0 -371
  125. package/dist/chunk-6a1t7fnq.js +0 -12121
  126. package/dist/chunk-728jvrr0.js +0 -1701
  127. package/dist/chunk-7m60qnc8.js +0 -1762
  128. package/dist/chunk-aa2dkn7b.js +0 -205
  129. package/dist/chunk-d48vtdj4.js +0 -433
  130. package/dist/chunk-f55nkpvb.js +0 -8
  131. package/dist/chunk-fgk8cqew.js +0 -152
  132. package/dist/chunk-he9a874b.js +0 -769
  133. package/dist/chunk-k2yyatfw.js +0 -10
  134. package/dist/chunk-k4px0bnv.js +0 -23
  135. package/dist/chunk-nsgqsmrh.js +0 -1779
  136. package/dist/chunk-q0st3se8.js +0 -42033
  137. package/dist/chunk-qr803fye.js +0 -2122
  138. package/dist/chunk-rds0sy87.js +0 -1771
  139. package/dist/chunk-ttz2ra5j.js +0 -12
  140. package/dist/chunk-v0bahtg2.js +0 -4
  141. package/dist/chunk-va2yd85b.js +0 -200
  142. package/dist/chunk-x9s0cqfx.js +0 -13
  143. package/dist/chunk-zqtpg06c.js +0 -1752
@@ -1,4 +1,4 @@
1
- import{Ua as eE}from"./chunk-38pq971s.js";import{$a as kc,$b as tu,$c as Yo,Gc as eu,Va as Lc,Wa as Ot,Xa as UR,_c as p,ad as nu,bd as qg,db as jR,eb as HR,fb as LR,gb as FR,hb as VR,ib as NR,jb as xR,lb as Cc,mb as Gg,nb as Oc,ob as MR,pb as QR,qb as GR,rb as yi,sb as ac,tb as ZR,ub as YR,vb as sR,wb as XR,xb as uo,yb as KR}from"./chunk-hzqw8xm5.js";import{dd as Er}from"./chunk-fhc6ntvd.js";import{nd as Jl}from"./chunk-gavvf0pg.js";import{od as f_,rd as __}from"./chunk-bz828v8q.js";import{sd as gf,td as Ai,xd as ho}from"./chunk-57y1zxbf.js";import{yd as dc}from"./chunk-4vrqm9h0.js";import{Gd as b_,Hd as W_,Id as kl,Jd as Ol,Od as le,Pd as U_,zd as cc}from"./chunk-3r4fb59r.js";import{Rd as Fd}from"./chunk-p66ptpmr.js";import{Ie as So,Sd as kR,re as Jn,se as co,ve as qR,we as tE,xe as gc,ye as $l}from"./chunk-sgyffpgm.js";import{cf as pR}from"./chunk-r3kv0vm9.js";import{gf as u_,jf as h_,pf as S_,qf as Xf,uf as Kf,vf as ul,zf as Al}from"./chunk-r9hjwcj9.js";import{Sf as mR}from"./chunk-axhnkn5g.js";import{Uf as T_}from"./chunk-h5pa5men.js";import{$f as _n}from"./chunk-fy8j3y8p.js";import{ag as CR,dg as OR,eg as JR,fg as BR,gg as zR,hg as bR,ig as WR}from"./chunk-ynjvbphf.js";import{jg as Uc,kg as Jf,lg as Ne,mg as lc,ng as bt,og as Bf,pg as TR}from"./chunk-ry030a6b.js";import{Og as ut}from"./chunk-fpm59y25.js";import{Gh as B_,Un as z_,hh as yS,jh as bc,kh as de,nh as On,ph as re,qh as ps}from"./chunk-jpjamjey.js";import{Vo as oe}from"./chunk-mh0kdzqp.js";import{createHash as EP}from"node:crypto";import{existsSync as Tn,mkdtempSync as Nl,readdirSync as _R,rmSync as Wr,statSync as nE}from"node:fs";import{readFile as ln,writeFile as Tr}from"node:fs/promises";import{tmpdir as Ro}from"node:os";import{dirname as IP,extname as uc,join as At,normalize as wP,relative as AP,resolve as DP,sep as yP}from"node:path";import{fileURLToPath as PP}from"node:url";class vo extends Error{status;code;requestId;constructor(t,e,n,r){super(n);this.status=t;this.code=e;this.requestId=r}}class lg{options;baseUrl;fetchFn;constructor(t){this.options=t;this.baseUrl=t.baseUrl.replace(/\/$/,""),this.fetchFn=t.fetch??fetch}async request(t,e={}){let n=await this.fetchFn(`${this.baseUrl}${t}`,{...e,headers:{accept:"application/json",authorization:`Bearer ${this.options.token}`,...e.headers}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new vo(n.status,r.error?.code??"api_error",r.error?.message??"API request failed.",r.error?.requestId??n.headers.get("x-request-id")??void 0);return r}listProjects(t={}){return this.request(`/api/v1/projects?${new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).map(([e,n])=>[e,String(n)])))}`)}listEnvironments(t,e={}){return this.request(`/api/v1/projects/${encodeURIComponent(t)}/environments?${new URLSearchParams(Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0).map(([n,r])=>[n,String(r)])))}`)}listServices(t,e){return this.request(`/api/v1/services?${new URLSearchParams({projectId:t,...e?{environmentId:e}:{}})}`)}listOperations(t){return this.request(`/api/v1/operations${t?`?projectId=${encodeURIComponent(t)}`:""}`)}listComposeTemplates(){return this.request("/api/v1/compose-templates")}listComposeApplications(t,e){return this.request(`/api/v1/compose-applications?${new URLSearchParams({projectId:t,...e?{environmentId:e}:{}})}`)}previewCompose(t){return this.request("/api/v1/compose-applications/preview",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createComposeApplication(t){return this.request("/api/v1/compose-applications",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}composeServices(t){return this.request(`/api/v1/compose-applications/${encodeURIComponent(t)}/services`)}composeAction(t,e,n={}){return this.request(`/api/v1/compose-applications/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}releaseCapabilities(t,e={}){return this.request(`/api/v1/releases/capabilities?${new URLSearchParams({kind:t,health:String(!!e.health),replicas:String(e.replicas??1)})}`)}listReleases(t,e={}){return this.request(`/api/v1/releases?${new URLSearchParams({projectId:t,...e})}`)}createReleaseArtifact(t){return this.request("/api/v1/release-artifacts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createRelease(t){return this.request("/api/v1/releases",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}releaseAction(t,e,n={}){return this.request(`/api/v1/releases/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}createDeployment(t,e){return this.request("/api/v1/deployments",{method:"POST",headers:{"content-type":"application/json","idempotency-key":e},body:JSON.stringify(t)})}detectApplication(t){return this.request("/api/v1/application-detections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}planApplication(t){return this.request("/api/v1/application-plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}listApplicationDrafts(t){return this.request(`/api/v1/application-drafts?projectId=${encodeURIComponent(t)}`)}createApplicationDraft(t){return this.request("/api/v1/application-drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}updateApplicationDraft(t){return this.request("/api/v1/application-drafts",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createApplication(t,e){return this.request("/api/v1/applications",{method:"POST",headers:{"content-type":"application/json","idempotency-key":e},body:JSON.stringify(t)})}uploadApplicationArtifact(t,e,n){return this.request("/api/v1/application-artifacts",{method:"POST",headers:{"content-type":"application/octet-stream","x-project-id":t,"x-artifact-filename":e},body:n})}listRegistryConnections(){return this.request("/api/v1/registry-connections")}createRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}updateRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}disconnectRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({id:t})})}listQueue(t={}){let e=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==void 0).map(([n,r])=>[n,String(r)]));return this.request(`/api/v1/queue?${e}`)}operationLogs(t,e={}){let n=new URLSearchParams(Object.entries(e).filter(([,r])=>r!==void 0).map(([r,i])=>[r,String(i)]));return this.request(`/api/v1/operations/${encodeURIComponent(t)}/logs?${n}`)}streamOperationLogs(t,e=0){return this.fetchFn(`${this.baseUrl}/api/v1/operations/${encodeURIComponent(t)}/logs/stream`,{headers:{accept:"text/event-stream",authorization:`Bearer ${this.options.token}`,"last-event-id":String(e)}})}cancelOperation(t){return this.request(`/api/v1/operations/${encodeURIComponent(t)}/cancel`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}retryOperation(t,e,n=0){return this.request(`/api/v1/operations/${encodeURIComponent(t)}/retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({errorClass:e,delayMs:n})})}queueSettings(){return this.request("/api/v1/queue/settings")}updateQueueSettings(t){return this.request("/api/v1/queue/settings",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"update queue limits",concurrency:t})})}listPreviews(t){return this.request(`/api/v1/previews${t?`?projectId=${encodeURIComponent(t)}`:""}`)}listPreviewDefinitions(t){return this.request(`/api/v1/preview-definitions?projectId=${encodeURIComponent(t)}`)}createPreviewDefinition(t){return this.request("/api/v1/preview-definitions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createPreview(t){return this.request("/api/v1/previews",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}destroyPreview(t,e){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/destroy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:e})})}extendPreview(t,e){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/extend`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hours:e})})}rebuildPreview(t){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/rebuild`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}usage(t={}){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))if(r)e.set(n,String(r));return this.request(`/api/v1/usage${e.size>0?`?${e}`:""}`)}usageRollups(t){let e=new URLSearchParams({from:t.from,to:t.to});if(t.projectId)e.set("projectId",t.projectId);if(t.environmentId)e.set("environmentId",t.environmentId);if(t.limit)e.set("limit",String(t.limit));for(let n of t.meters??[])e.append("meter",n);return this.request(`/api/v1/usage/rollups?${e}`)}allowance(t="deploy",e={}){let n=new URLSearchParams({operation:t});if(e.projectId)n.set("projectId",e.projectId);if(e.environmentId)n.set("environmentId",e.environmentId);return this.request(`/api/v1/spend/allowance?${n}`)}budgets(t={}){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))if(r)e.set(n,String(r));return this.request(`/api/v1/spend/budgets${e.size>0?`?${e}`:""}`)}anomalies(t={}){let e=new URLSearchParams;if(t.projectId)e.set("projectId",t.projectId);if(t.since)e.set("since",t.since);if(t.unacknowledged)e.set("unacknowledged","true");return this.request(`/api/v1/spend/anomalies${e.size>0?`?${e}`:""}`)}}import{createHash as aI}from"node:crypto";import{lstatSync as RE,readdirSync as EE,readFileSync as IE}from"node:fs";import{relative as wE,resolve as gg,sep as AE}from"node:path";function DE(t){return new Map(t.map((e)=>[e.path.replace(/^\.\//,"").replace(/\\/g,"/"),e]))}function ar(t,e,n){return{path:t,reason:e,weight:n}}function ug(t){try{return t?.content?JSON.parse(t.content):{}}catch{return{}}}function Vr(t,e,n,r,i,c){return{framework:t,strategy:e,confidence:n,evidence:r,defaults:{build:i,runtime:{target:e==="static"?"serverless":e==="serverless"?"serverless":e==="dockerfile"||e==="prebuilt_image"?"container":"server",architecture:"x86_64",port:e==="static"||e==="serverless"?void 0:3000,healthCheck:e==="static"?void 0:{protocol:"http",path:"/health"}}},description:c}}function Nr(t){let e=DE(t.slice(0,1e4)),n=[];if(e.has("Dockerfile"))n.push(Vr("dockerfile","dockerfile",0.99,[ar("Dockerfile","A root Dockerfile defines an explicit reproducible build.",1)],{kind:"dockerfile",context:".",dockerfile:"Dockerfile"},"Build the repository with its Dockerfile and run the resulting OCI image."));let r=ug(e.get("composer.json"));if(e.has("artisan")&&r.require?.["laravel/framework"])n.push(Vr("laravel","server",0.98,[ar("artisan","Laravel Artisan entrypoint is present.",0.45),ar("composer.json","Requires laravel/framework.",0.55)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",buildCommand:"php artisan config:cache && php artisan route:cache && php artisan view:cache",startCommand:"php artisan serve --host=0.0.0.0 --port=$PORT"},"Install a production Composer tree, warm Laravel caches, and run the HTTP application."));else if(e.has("composer.json"))n.push(Vr("php","server",0.82,[ar("composer.json","Composer metadata identifies a PHP application.",0.8)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",startCommand:"php -S 0.0.0.0:$PORT -t public"},"Install Composer dependencies and run the configured PHP document root."));let i=ug(e.get("package.json"));if(e.has("package.json")){let c=e.has("bun.lock")||e.has("bun.lockb")||i.engines?.bun,d=c?"bun":"node",a=c?"bun":"node",l=[ar("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(c)l.push(ar(e.has("bun.lock")?"bun.lock":e.has("bun.lockb")?"bun.lockb":"package.json","Pins the Bun package manager/runtime.",0.35));let o=!!(i.dependencies?.vite||i.devDependencies?.vite||i.dependencies?.["@stacksjs/bunpress"]||i.devDependencies?.["@stacksjs/bunpress"])&&!i.scripts?.start,u=o?{kind:"static",installCommand:`${d} install --frozen-lockfile`,buildCommand:`${d} run build`,publishDirectory:"dist"}:{kind:"server",runtime:d,installCommand:`${d} install --frozen-lockfile`,buildCommand:i.scripts?.build?`${d} run build`:void 0,startCommand:i.scripts?.start?`${d} run start`:d==="bun"?"bun run index.ts":"node index.js"};n.push(Vr(a,u.kind,Math.min(0.94,l.reduce((f,R)=>f+R.weight,0)),l,u,o?"Install dependencies, build static assets, and publish the output directory.":`Install dependencies, build if configured, and start the ${d} server.`))}if(!n.length&&(e.has("index.html")||e.has("public/index.html")))n.push(Vr("static","static",0.78,[ar(e.has("index.html")?"index.html":"public/index.html","A static HTML entrypoint is present.",0.78)],{kind:"static",publishDirectory:e.has("index.html")?".":"public"},"Publish the static directory without a runtime process."));if(!n.length)n.push(Vr("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return n.sort((c,d)=>d.confidence-c.confidence||c.framework.localeCompare(d.framework))}function ko(t,e={}){let n=gg(t),r=e.maxFiles??1e4,i=e.maxContentBytes??262144,c=[],d=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),a=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),l=(o)=>{for(let u of EE(o).sort()){if(a.has(u))continue;let f=gg(o,u),R=wE(n,f).split(AE).join("/");if(!R||R.startsWith("../"))throw Error("Detection path escaped the application root");let E=RE(f);if(E.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${R}`);if(E.isDirectory())l(f);else if(E.isFile()){if(c.length>=r)throw Error("Application file-count limit exceeded");let y={path:R,size:E.size};if(d.has(R)&&E.size<=i)y.content=IE(f,"utf8");c.push(y)}}};return l(n),c}function Oo(t){if(Array.isArray(t))return`[${t.map(Oo).join(",")}]`;if(t&&typeof t==="object")return`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Oo(n)}`).join(",")}}`;return JSON.stringify(t)??"null"}function Ci(t){return!!t&&!t.startsWith("/")&&!t.split("/").includes("..")&&!/[\0\r\n]/.test(t)}function Ae(t,e,n,r){return{path:t,code:e,message:n,alternatives:r}}function Co(t){return JSON.parse(JSON.stringify(t))}function yE(t){let e=Object.fromEntries(Object.entries(t.environment??{}).map(([n,r])=>[n,typeof r==="string"?r:`\${${r.secretRef}}`]));if(t.build.kind==="prebuilt_image"||t.build.kind==="dockerfile")return Co({infrastructure:{containers:{[t.slug]:{source:t.source,build:t.build,port:t.runtime.port,cpu:t.runtime.cpu,memory:t.runtime.memoryMb,architecture:t.runtime.architecture,healthCheck:t.runtime.healthCheck,environment:e}}}});if(t.runtime.target==="serverless"||t.build.kind==="serverless")return Co({serverless:{apps:{[t.slug]:{source:t.source,build:t.build,architecture:t.runtime.architecture,environment:e,domain:t.domain}}}});return Co({sites:{[t.slug]:{source:t.source,build:t.build,port:t.runtime.port,architecture:t.runtime.architecture,healthCheck:t.runtime.healthCheck,env:e,domain:t.domain?.hostname}}})}function Fe(t,e=[]){let n=[],r=(y)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(y),i=Object.fromEntries(Object.entries(t.environment??{}).map(([y,$])=>{if(typeof $==="string"&&r(y))return n.push(Ae(`environment.${y}`,"write_only_secret_required",`${y} must be supplied through the write-only secrets boundary.`)),[y,{secretRef:y}];return[y,$]})),c=t.build;if(t.build.kind==="dockerfile"&&t.build.buildArgs){let y=Object.fromEntries(Object.entries(t.build.buildArgs).map(([$,C])=>{if(r($))return n.push(Ae(`build.buildArgs.${$}`,"write_only_build_secret_required",`${$} must be declared in secretNames instead of buildArgs.`)),[$,"[REDACTED]"];return[$,C]}));c={...t.build,buildArgs:y}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(t.slug))n.push(Ae("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!Ci((t.source.kind==="git"?t.source.monorepoRoot:t.source.kind==="local"?t.source.root:".")??"."))n.push(Ae("source","unsafe_source_root","Source root must stay inside the source tree."));if(t.source.kind==="git"&&t.source.sparsePaths?.some((y)=>!Ci(y)))n.push(Ae("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(t.build.kind==="dockerfile"&&(!Ci(t.build.context)||!Ci(t.build.dockerfile)))n.push(Ae("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(t.build.kind==="static"&&!Ci(t.build.publishDirectory))n.push(Ae("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(t.build.kind==="server"&&!t.build.startCommand.trim())n.push(Ae("build.startCommand","missing_start_command","A server start command is required.",["Use static output","Use a Dockerfile"]));if(t.source.kind==="image"&&t.build.kind!=="prebuilt_image")n.push(Ae("build.kind","image_requires_prebuilt","An OCI image source must use the prebuilt-image strategy.",["Select prebuilt image"]));if(t.build.kind==="prebuilt_image"&&t.runtime.target!=="container")n.push(Ae("runtime.target","image_requires_container","Prebuilt images require the container runtime target.",["Select container target"]));if(t.runtime.target==="serverless"&&t.build.kind==="dockerfile")n.push(Ae("runtime.target","unsupported_serverless_dockerfile","Dockerfile builds currently target the container service path.",["Select container target","Select serverless package"]));if(t.runtime.port!==void 0&&(!Number.isInteger(t.runtime.port)||t.runtime.port<1||t.runtime.port>65535))n.push(Ae("runtime.port","invalid_port","Port must be an integer from 1 to 65535."));let d=t.runtime.healthCheck;if(d&&d.protocol!=="tcp"&&(!d.path||!d.path.startsWith("/")||/[\r\n]/.test(d.path)))n.push(Ae("runtime.healthCheck.path","invalid_health_path","HTTP health checks require a path beginning with /."));if(t.domain?.hostname&&(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(t.domain.hostname)||t.domain.hostname.includes("..")))n.push(Ae("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let a=Object.values(i).flatMap((y)=>typeof y==="object"?[y.secretRef]:[]),l=[...new Set([...t.requiredSecretNames??[],...t.build.kind==="dockerfile"?t.build.secretNames??[]:[],...a])].sort(),o=new Set(e),u=l.filter((y)=>!o.has(y)),f={apiVersion:"ts-cloud.dev/v1",kind:"Application",metadata:{name:t.name,slug:t.slug,projectId:t.projectId,environmentId:t.environmentId},spec:{source:t.source,build:c,runtime:t.runtime,environment:i,domain:t.domain}},R=[...new Set([t.source.kind==="git"?"git:read":t.source.kind==="image"?"registry:pull":t.source.kind==="artifact"?"artifact:inspect":"filesystem:read",t.runtime.target==="container"?"containers":t.runtime.target==="serverless"?"serverless":"servers",t.domain?"dns":""])].filter(Boolean).sort(),E=[...new Set([t.runtime.target,t.runtime.cpu?`${t.runtime.cpu} vCPU`:"",t.runtime.memoryMb?`${t.runtime.memoryMb} MB memory`:"",(t.runtime.minInstances??0)>0?`${t.runtime.minInstances} minimum instances`:"scales from zero where supported",t.domain?"managed DNS/TLS":""])].filter(Boolean);return{valid:n.length===0&&u.length===0,issues:n,missingSecrets:u,manifest:f,configPatch:yE({...t,build:c,environment:i}),capabilityRequirements:R,costDrivers:E,serializedManifest:`${Oo(f)}
1
+ import{Ua as eE}from"./chunk-38pq971s.js";import{$a as kc,$b as tu,$c as Yo,Gc as eu,Va as Lc,Wa as Ot,Xa as UR,_c as p,ad as nu,bd as qg,db as jR,eb as HR,fb as LR,gb as FR,hb as VR,ib as NR,jb as xR,lb as Cc,mb as Gg,nb as Oc,ob as MR,pb as QR,qb as GR,rb as yi,sb as ac,tb as ZR,ub as YR,vb as sR,wb as XR,xb as uo,yb as KR}from"./chunk-1k5kszjp.js";import{dd as Er}from"./chunk-fhc6ntvd.js";import{nd as Jl}from"./chunk-gavvf0pg.js";import{od as f_,rd as __}from"./chunk-y7s5r8y6.js";import{sd as gf,td as Ai,xd as ho}from"./chunk-vm3q5gf2.js";import{yd as dc}from"./chunk-4vrqm9h0.js";import{Gd as b_,Hd as W_,Id as kl,Jd as Ol,Od as le,Pd as U_,zd as cc}from"./chunk-mz0wbbsj.js";import{Rd as Fd}from"./chunk-p66ptpmr.js";import{Ie as So,Sd as kR,re as Jn,se as co,ve as qR,we as tE,xe as gc,ye as $l}from"./chunk-zmegvjp8.js";import{cf as pR}from"./chunk-ddk4rt4j.js";import{gf as u_,jf as h_,pf as S_,qf as Xf,uf as Kf,vf as ul,zf as Al}from"./chunk-tga3hhwk.js";import{Sf as mR}from"./chunk-axhnkn5g.js";import{Uf as T_}from"./chunk-h5pa5men.js";import{$f as _n}from"./chunk-fy8j3y8p.js";import{ag as CR,dg as OR,eg as JR,fg as BR,gg as zR,hg as bR,ig as WR}from"./chunk-tx0tqq2k.js";import{jg as Uc,kg as Jf,lg as Ne,mg as lc,ng as bt,og as Bf,pg as TR}from"./chunk-etrb03mt.js";import{Og as ut}from"./chunk-fpm59y25.js";import{Gh as B_,Un as z_,hh as yS,jh as bc,kh as de,nh as On,ph as re,qh as ps}from"./chunk-rxcvf10f.js";import{Vo as oe}from"./chunk-mh0kdzqp.js";import{createHash as EP}from"node:crypto";import{existsSync as Tn,mkdtempSync as Nl,readdirSync as _R,rmSync as Wr,statSync as nE}from"node:fs";import{readFile as ln,writeFile as Tr}from"node:fs/promises";import{tmpdir as Ro}from"node:os";import{dirname as IP,extname as uc,join as At,normalize as wP,relative as AP,resolve as DP,sep as yP}from"node:path";import{fileURLToPath as PP}from"node:url";class vo extends Error{status;code;requestId;constructor(t,e,n,r){super(n);this.status=t;this.code=e;this.requestId=r}}class lg{options;baseUrl;fetchFn;constructor(t){this.options=t;this.baseUrl=t.baseUrl.replace(/\/$/,""),this.fetchFn=t.fetch??fetch}async request(t,e={}){let n=await this.fetchFn(`${this.baseUrl}${t}`,{...e,headers:{accept:"application/json",authorization:`Bearer ${this.options.token}`,...e.headers}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new vo(n.status,r.error?.code??"api_error",r.error?.message??"API request failed.",r.error?.requestId??n.headers.get("x-request-id")??void 0);return r}listProjects(t={}){return this.request(`/api/v1/projects?${new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).map(([e,n])=>[e,String(n)])))}`)}listEnvironments(t,e={}){return this.request(`/api/v1/projects/${encodeURIComponent(t)}/environments?${new URLSearchParams(Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0).map(([n,r])=>[n,String(r)])))}`)}listServices(t,e){return this.request(`/api/v1/services?${new URLSearchParams({projectId:t,...e?{environmentId:e}:{}})}`)}listOperations(t){return this.request(`/api/v1/operations${t?`?projectId=${encodeURIComponent(t)}`:""}`)}listComposeTemplates(){return this.request("/api/v1/compose-templates")}listComposeApplications(t,e){return this.request(`/api/v1/compose-applications?${new URLSearchParams({projectId:t,...e?{environmentId:e}:{}})}`)}previewCompose(t){return this.request("/api/v1/compose-applications/preview",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createComposeApplication(t){return this.request("/api/v1/compose-applications",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}composeServices(t){return this.request(`/api/v1/compose-applications/${encodeURIComponent(t)}/services`)}composeAction(t,e,n={}){return this.request(`/api/v1/compose-applications/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}releaseCapabilities(t,e={}){return this.request(`/api/v1/releases/capabilities?${new URLSearchParams({kind:t,health:String(!!e.health),replicas:String(e.replicas??1)})}`)}listReleases(t,e={}){return this.request(`/api/v1/releases?${new URLSearchParams({projectId:t,...e})}`)}createReleaseArtifact(t){return this.request("/api/v1/release-artifacts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createRelease(t){return this.request("/api/v1/releases",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}releaseAction(t,e,n={}){return this.request(`/api/v1/releases/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}createDeployment(t,e){return this.request("/api/v1/deployments",{method:"POST",headers:{"content-type":"application/json","idempotency-key":e},body:JSON.stringify(t)})}detectApplication(t){return this.request("/api/v1/application-detections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}planApplication(t){return this.request("/api/v1/application-plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}listApplicationDrafts(t){return this.request(`/api/v1/application-drafts?projectId=${encodeURIComponent(t)}`)}createApplicationDraft(t){return this.request("/api/v1/application-drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}updateApplicationDraft(t){return this.request("/api/v1/application-drafts",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createApplication(t,e){return this.request("/api/v1/applications",{method:"POST",headers:{"content-type":"application/json","idempotency-key":e},body:JSON.stringify(t)})}uploadApplicationArtifact(t,e,n){return this.request("/api/v1/application-artifacts",{method:"POST",headers:{"content-type":"application/octet-stream","x-project-id":t,"x-artifact-filename":e},body:n})}listRegistryConnections(){return this.request("/api/v1/registry-connections")}createRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}updateRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}disconnectRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({id:t})})}listQueue(t={}){let e=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==void 0).map(([n,r])=>[n,String(r)]));return this.request(`/api/v1/queue?${e}`)}operationLogs(t,e={}){let n=new URLSearchParams(Object.entries(e).filter(([,r])=>r!==void 0).map(([r,i])=>[r,String(i)]));return this.request(`/api/v1/operations/${encodeURIComponent(t)}/logs?${n}`)}streamOperationLogs(t,e=0){return this.fetchFn(`${this.baseUrl}/api/v1/operations/${encodeURIComponent(t)}/logs/stream`,{headers:{accept:"text/event-stream",authorization:`Bearer ${this.options.token}`,"last-event-id":String(e)}})}cancelOperation(t){return this.request(`/api/v1/operations/${encodeURIComponent(t)}/cancel`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}retryOperation(t,e,n=0){return this.request(`/api/v1/operations/${encodeURIComponent(t)}/retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({errorClass:e,delayMs:n})})}queueSettings(){return this.request("/api/v1/queue/settings")}updateQueueSettings(t){return this.request("/api/v1/queue/settings",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"update queue limits",concurrency:t})})}listPreviews(t){return this.request(`/api/v1/previews${t?`?projectId=${encodeURIComponent(t)}`:""}`)}listPreviewDefinitions(t){return this.request(`/api/v1/preview-definitions?projectId=${encodeURIComponent(t)}`)}createPreviewDefinition(t){return this.request("/api/v1/preview-definitions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createPreview(t){return this.request("/api/v1/previews",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}destroyPreview(t,e){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/destroy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:e})})}extendPreview(t,e){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/extend`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hours:e})})}rebuildPreview(t){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/rebuild`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}usage(t={}){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))if(r)e.set(n,String(r));return this.request(`/api/v1/usage${e.size>0?`?${e}`:""}`)}usageRollups(t){let e=new URLSearchParams({from:t.from,to:t.to});if(t.projectId)e.set("projectId",t.projectId);if(t.environmentId)e.set("environmentId",t.environmentId);if(t.limit)e.set("limit",String(t.limit));for(let n of t.meters??[])e.append("meter",n);return this.request(`/api/v1/usage/rollups?${e}`)}allowance(t="deploy",e={}){let n=new URLSearchParams({operation:t});if(e.projectId)n.set("projectId",e.projectId);if(e.environmentId)n.set("environmentId",e.environmentId);return this.request(`/api/v1/spend/allowance?${n}`)}budgets(t={}){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))if(r)e.set(n,String(r));return this.request(`/api/v1/spend/budgets${e.size>0?`?${e}`:""}`)}anomalies(t={}){let e=new URLSearchParams;if(t.projectId)e.set("projectId",t.projectId);if(t.since)e.set("since",t.since);if(t.unacknowledged)e.set("unacknowledged","true");return this.request(`/api/v1/spend/anomalies${e.size>0?`?${e}`:""}`)}}import{createHash as aI}from"node:crypto";import{lstatSync as RE,readdirSync as EE,readFileSync as IE}from"node:fs";import{relative as wE,resolve as gg,sep as AE}from"node:path";function DE(t){return new Map(t.map((e)=>[e.path.replace(/^\.\//,"").replace(/\\/g,"/"),e]))}function ar(t,e,n){return{path:t,reason:e,weight:n}}function ug(t){try{return t?.content?JSON.parse(t.content):{}}catch{return{}}}function Vr(t,e,n,r,i,c){return{framework:t,strategy:e,confidence:n,evidence:r,defaults:{build:i,runtime:{target:e==="static"?"serverless":e==="serverless"?"serverless":e==="dockerfile"||e==="prebuilt_image"?"container":"server",architecture:"x86_64",port:e==="static"||e==="serverless"?void 0:3000,healthCheck:e==="static"?void 0:{protocol:"http",path:"/health"}}},description:c}}function Nr(t){let e=DE(t.slice(0,1e4)),n=[];if(e.has("Dockerfile"))n.push(Vr("dockerfile","dockerfile",0.99,[ar("Dockerfile","A root Dockerfile defines an explicit reproducible build.",1)],{kind:"dockerfile",context:".",dockerfile:"Dockerfile"},"Build the repository with its Dockerfile and run the resulting OCI image."));let r=ug(e.get("composer.json"));if(e.has("artisan")&&r.require?.["laravel/framework"])n.push(Vr("laravel","server",0.98,[ar("artisan","Laravel Artisan entrypoint is present.",0.45),ar("composer.json","Requires laravel/framework.",0.55)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",buildCommand:"php artisan config:cache && php artisan route:cache && php artisan view:cache",startCommand:"php artisan serve --host=0.0.0.0 --port=$PORT"},"Install a production Composer tree, warm Laravel caches, and run the HTTP application."));else if(e.has("composer.json"))n.push(Vr("php","server",0.82,[ar("composer.json","Composer metadata identifies a PHP application.",0.8)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",startCommand:"php -S 0.0.0.0:$PORT -t public"},"Install Composer dependencies and run the configured PHP document root."));let i=ug(e.get("package.json"));if(e.has("package.json")){let c=e.has("bun.lock")||e.has("bun.lockb")||i.engines?.bun,d=c?"bun":"node",a=c?"bun":"node",l=[ar("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(c)l.push(ar(e.has("bun.lock")?"bun.lock":e.has("bun.lockb")?"bun.lockb":"package.json","Pins the Bun package manager/runtime.",0.35));let o=!!(i.dependencies?.vite||i.devDependencies?.vite||i.dependencies?.["@stacksjs/bunpress"]||i.devDependencies?.["@stacksjs/bunpress"])&&!i.scripts?.start,u=o?{kind:"static",installCommand:`${d} install --frozen-lockfile`,buildCommand:`${d} run build`,publishDirectory:"dist"}:{kind:"server",runtime:d,installCommand:`${d} install --frozen-lockfile`,buildCommand:i.scripts?.build?`${d} run build`:void 0,startCommand:i.scripts?.start?`${d} run start`:d==="bun"?"bun run index.ts":"node index.js"};n.push(Vr(a,u.kind,Math.min(0.94,l.reduce((f,R)=>f+R.weight,0)),l,u,o?"Install dependencies, build static assets, and publish the output directory.":`Install dependencies, build if configured, and start the ${d} server.`))}if(!n.length&&(e.has("index.html")||e.has("public/index.html")))n.push(Vr("static","static",0.78,[ar(e.has("index.html")?"index.html":"public/index.html","A static HTML entrypoint is present.",0.78)],{kind:"static",publishDirectory:e.has("index.html")?".":"public"},"Publish the static directory without a runtime process."));if(!n.length)n.push(Vr("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return n.sort((c,d)=>d.confidence-c.confidence||c.framework.localeCompare(d.framework))}function ko(t,e={}){let n=gg(t),r=e.maxFiles??1e4,i=e.maxContentBytes??262144,c=[],d=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),a=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),l=(o)=>{for(let u of EE(o).sort()){if(a.has(u))continue;let f=gg(o,u),R=wE(n,f).split(AE).join("/");if(!R||R.startsWith("../"))throw Error("Detection path escaped the application root");let E=RE(f);if(E.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${R}`);if(E.isDirectory())l(f);else if(E.isFile()){if(c.length>=r)throw Error("Application file-count limit exceeded");let y={path:R,size:E.size};if(d.has(R)&&E.size<=i)y.content=IE(f,"utf8");c.push(y)}}};return l(n),c}function Oo(t){if(Array.isArray(t))return`[${t.map(Oo).join(",")}]`;if(t&&typeof t==="object")return`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Oo(n)}`).join(",")}}`;return JSON.stringify(t)??"null"}function Ci(t){return!!t&&!t.startsWith("/")&&!t.split("/").includes("..")&&!/[\0\r\n]/.test(t)}function Ae(t,e,n,r){return{path:t,code:e,message:n,alternatives:r}}function Co(t){return JSON.parse(JSON.stringify(t))}function yE(t){let e=Object.fromEntries(Object.entries(t.environment??{}).map(([n,r])=>[n,typeof r==="string"?r:`\${${r.secretRef}}`]));if(t.build.kind==="prebuilt_image"||t.build.kind==="dockerfile")return Co({infrastructure:{containers:{[t.slug]:{source:t.source,build:t.build,port:t.runtime.port,cpu:t.runtime.cpu,memory:t.runtime.memoryMb,architecture:t.runtime.architecture,healthCheck:t.runtime.healthCheck,environment:e}}}});if(t.runtime.target==="serverless"||t.build.kind==="serverless")return Co({serverless:{apps:{[t.slug]:{source:t.source,build:t.build,architecture:t.runtime.architecture,environment:e,domain:t.domain}}}});return Co({sites:{[t.slug]:{source:t.source,build:t.build,port:t.runtime.port,architecture:t.runtime.architecture,healthCheck:t.runtime.healthCheck,env:e,domain:t.domain?.hostname}}})}function Fe(t,e=[]){let n=[],r=(y)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(y),i=Object.fromEntries(Object.entries(t.environment??{}).map(([y,$])=>{if(typeof $==="string"&&r(y))return n.push(Ae(`environment.${y}`,"write_only_secret_required",`${y} must be supplied through the write-only secrets boundary.`)),[y,{secretRef:y}];return[y,$]})),c=t.build;if(t.build.kind==="dockerfile"&&t.build.buildArgs){let y=Object.fromEntries(Object.entries(t.build.buildArgs).map(([$,C])=>{if(r($))return n.push(Ae(`build.buildArgs.${$}`,"write_only_build_secret_required",`${$} must be declared in secretNames instead of buildArgs.`)),[$,"[REDACTED]"];return[$,C]}));c={...t.build,buildArgs:y}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(t.slug))n.push(Ae("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!Ci((t.source.kind==="git"?t.source.monorepoRoot:t.source.kind==="local"?t.source.root:".")??"."))n.push(Ae("source","unsafe_source_root","Source root must stay inside the source tree."));if(t.source.kind==="git"&&t.source.sparsePaths?.some((y)=>!Ci(y)))n.push(Ae("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(t.build.kind==="dockerfile"&&(!Ci(t.build.context)||!Ci(t.build.dockerfile)))n.push(Ae("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(t.build.kind==="static"&&!Ci(t.build.publishDirectory))n.push(Ae("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(t.build.kind==="server"&&!t.build.startCommand.trim())n.push(Ae("build.startCommand","missing_start_command","A server start command is required.",["Use static output","Use a Dockerfile"]));if(t.source.kind==="image"&&t.build.kind!=="prebuilt_image")n.push(Ae("build.kind","image_requires_prebuilt","An OCI image source must use the prebuilt-image strategy.",["Select prebuilt image"]));if(t.build.kind==="prebuilt_image"&&t.runtime.target!=="container")n.push(Ae("runtime.target","image_requires_container","Prebuilt images require the container runtime target.",["Select container target"]));if(t.runtime.target==="serverless"&&t.build.kind==="dockerfile")n.push(Ae("runtime.target","unsupported_serverless_dockerfile","Dockerfile builds currently target the container service path.",["Select container target","Select serverless package"]));if(t.runtime.port!==void 0&&(!Number.isInteger(t.runtime.port)||t.runtime.port<1||t.runtime.port>65535))n.push(Ae("runtime.port","invalid_port","Port must be an integer from 1 to 65535."));let d=t.runtime.healthCheck;if(d&&d.protocol!=="tcp"&&(!d.path||!d.path.startsWith("/")||/[\r\n]/.test(d.path)))n.push(Ae("runtime.healthCheck.path","invalid_health_path","HTTP health checks require a path beginning with /."));if(t.domain?.hostname&&(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(t.domain.hostname)||t.domain.hostname.includes("..")))n.push(Ae("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let a=Object.values(i).flatMap((y)=>typeof y==="object"?[y.secretRef]:[]),l=[...new Set([...t.requiredSecretNames??[],...t.build.kind==="dockerfile"?t.build.secretNames??[]:[],...a])].sort(),o=new Set(e),u=l.filter((y)=>!o.has(y)),f={apiVersion:"ts-cloud.dev/v1",kind:"Application",metadata:{name:t.name,slug:t.slug,projectId:t.projectId,environmentId:t.environmentId},spec:{source:t.source,build:c,runtime:t.runtime,environment:i,domain:t.domain}},R=[...new Set([t.source.kind==="git"?"git:read":t.source.kind==="image"?"registry:pull":t.source.kind==="artifact"?"artifact:inspect":"filesystem:read",t.runtime.target==="container"?"containers":t.runtime.target==="serverless"?"serverless":"servers",t.domain?"dns":""])].filter(Boolean).sort(),E=[...new Set([t.runtime.target,t.runtime.cpu?`${t.runtime.cpu} vCPU`:"",t.runtime.memoryMb?`${t.runtime.memoryMb} MB memory`:"",(t.runtime.minInstances??0)>0?`${t.runtime.minInstances} minimum instances`:"scales from zero where supported",t.domain?"managed DNS/TLS":""])].filter(Boolean);return{valid:n.length===0&&u.length===0,issues:n,missingSecrets:u,manifest:f,configPatch:yE({...t,build:c,environment:i}),capabilityRequirements:R,costDrivers:E,serializedManifest:`${Oo(f)}
2
2
  `}}function hg(t){let e=t.replace(/\\/g,"/");return!!e&&!e.startsWith("/")&&!/^[A-Za-z]:\//.test(e)&&!e.split("/").includes("..")&&!/[\0\r\n]/.test(e)}function Sg(t,e,n={}){let r=n.maxBytes??104857600,i=n.maxEntries??1e4,c=n.maxExpandedBytes??524288000;if(t.byteLength>r)throw Error("Archive exceeds the compressed size limit");let d=new DataView(t.buffer,t.byteOffset,t.byteLength),a=[],l=0;if(e.toLowerCase().endsWith(".zip")||t[0]===80&&t[1]===75){let u=0;while(u+30<=t.length){let f=d.getUint32(u,!0);if(f===33639248||f===101010256)break;if(f!==67324752)throw Error("Malformed ZIP local header");let R=d.getUint16(u+6,!0),E=d.getUint32(u+18,!0),y=d.getUint32(u+22,!0),$=d.getUint16(u+26,!0),C=d.getUint16(u+28,!0);if(R&8)throw Error("ZIP data descriptors are not accepted for uploaded artifacts");let J=new TextDecoder().decode(t.subarray(u+30,u+30+$));if(!hg(J))throw Error(`Unsafe archive path: ${J}`);if(a.push(J),l+=y,a.length>i||l>c)throw Error("Archive expansion limit exceeded");u+=30+$+C+E}return{format:"zip",entries:a.length,expandedBytes:l,paths:a}}if(!e.toLowerCase().match(/\.(?:tar|tar\.gz|tgz)$/))throw Error("Only ZIP and uncompressed TAR artifacts are supported");let o=0;while(o+512<=t.length){let u=t.subarray(o,o+512);if(u.every(($)=>$===0))break;let f=($,C)=>new TextDecoder().decode(u.subarray($,$+C)).replace(/\0.*$/,""),R=`${f(345,155)}${f(345,155)?"/":""}${f(0,100)}`,E=Number.parseInt(f(124,12).trim()||"0",8),y=String.fromCharCode(u[156]??0);if(!hg(R))throw Error(`Unsafe archive path: ${R}`);if(y==="1"||y==="2")throw Error(`Archive links are not accepted: ${R}`);if(!Number.isFinite(E)||E<0)throw Error("Malformed TAR entry size");if(a.push(R),l+=E,a.length>i||l>c)throw Error("Archive expansion limit exceeded");o+=512+Math.ceil(E/512)*512}return{format:"tar",entries:a.length,expandedBytes:l,paths:a}}var fg=new Set(["source","build","runtime","environment","domain","review"]);function _g(t,e){try{return typeof t==="string"?JSON.parse(t):e}catch{return e}}function Rg(t){return/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(t)}function Eg(t){for(let[n,r]of Object.entries(t.environment??{}))if(typeof r==="string"&&Rg(n)&&r)throw Error(`${n} must be stored through the write-only secrets boundary`);if(t.build.kind==="dockerfile"){for(let[n,r]of Object.entries(t.build.buildArgs??{}))if(Rg(n)&&r)throw Error(`${n} must be declared as a build secret name`)}let e=JSON.stringify(t);if(/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(e))throw Error("Drafts cannot contain credential-bearing URLs")}function Ig(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),schemaVersion:Number(t.schema_version),name:String(t.name),step:String(t.step),input:_g(t.input,{}),suppliedSecretNames:_g(t.supplied_secret_names,[]),status:String(t.status),version:Number(t.version),createdByActorId:t.created_by_actor_id?String(t.created_by_actor_id):void 0,createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}class Jo{controlPlane;nowFn;idFn;constructor(t,e={}){this.controlPlane=t;this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}create(t){if(Eg(t.draft),t.draft.projectId!==t.projectId)throw Error("Draft project does not match its storage scope");let e=this.controlPlane.getProject(t.projectId);if(!e||e.organizationId!==t.organizationId)throw Error("Draft project was not found");let n=this.idFn(),r=this.now(),i=t.step??"source";if(!fg.has(i))throw Error("Invalid draft step");let c=[...new Set(t.suppliedSecretNames??[])].sort(),d=Fe(t.draft,c).valid?"ready":"draft";return this.controlPlane.database.run("INSERT INTO application_drafts (id, organization_id, project_id, schema_version, name, step, input, supplied_secret_names, status, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.organizationId,t.projectId,t.name.trim().slice(0,100),i,JSON.stringify(t.draft),JSON.stringify(c),d,t.actorId??null,r,r]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,actorId:t.actorId,type:"application.draft.created",payload:{draftId:n,step:i,status:d,requiredSecretNames:t.draft.requiredSecretNames??[]}}),this.get(n)}get(t){let e=this.controlPlane.database.query("SELECT * FROM application_drafts WHERE id=?").get(t);return e?Ig(e):void 0}list(t){return this.controlPlane.database.query("SELECT * FROM application_drafts WHERE project_id=? ORDER BY updated_at DESC").all(t).map(Ig)}update(t,e,n){let r=this.get(t);if(!r||r.version!==e)throw Error(`Application draft ${t} changed since version ${e}`);if(!fg.has(n.step))throw Error("Invalid draft step");if(n.draft.projectId!==r.projectId)throw Error("Draft project cannot be changed");Eg(n.draft);let i=[...new Set(n.suppliedSecretNames??r.suppliedSecretNames)].sort(),c=Fe(n.draft,i).valid?"ready":"draft",d=this.now();if(this.controlPlane.database.run("UPDATE application_drafts SET name=?, step=?, input=?, supplied_secret_names=?, status=?, version=version+1, updated_at=? WHERE id=? AND version=?",[n.draft.name.slice(0,100),n.step,JSON.stringify(n.draft),JSON.stringify(i),c,d,t,e]).changes!==1)throw Error(`Application draft ${t} changed since version ${e}`);return this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,actorId:n.actorId,type:"application.draft.updated",payload:{draftId:t,fromVersion:e,toVersion:e+1,step:n.step,status:c}}),this.get(t)}markApplied(t,e,n){let r=this.get(t);if(!r||r.version!==e)throw Error(`Application draft ${t} changed since version ${e}`);let i=Fe(r.input,r.suppliedSecretNames);if(!i.valid)throw Error(`Draft is not deployable: ${[...i.issues.map((d)=>d.message),...i.missingSecrets.map((d)=>`Missing secret ${d}`)].join("; ")}`);let c=this.now();return this.controlPlane.database.run("UPDATE application_drafts SET status='applied', step='review', version=version+1, updated_at=? WHERE id=? AND version=?",[c,t,e]),this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,actorId:n,type:"application.draft.applied",payload:bt({draftId:t,manifest:i.manifest})}),this.get(t)}}import{createCipheriv as PE,createDecipheriv as $E,createHash as Dg,randomBytes as vE}from"node:crypto";function Oi(t){return typeof t==="string"&&t?t:void 0}function Bo(t){return Dg("sha256").update(t).digest("hex").slice(0,16)}function wg(t){let e=new URL(t.includes("://")?t:`https://${t}`);if(e.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(e.hostname))throw Error("Registry host must use HTTPS");if(e.username||e.password||e.search||e.hash)throw Error("Registry host cannot contain credentials");return`${e.protocol}//${e.host}`}function kE(t){return{id:String(t.id),organizationId:String(t.organization_id),provider:String(t.provider),name:String(t.name),host:String(t.host),credentialConfigured:!!t.credential_ciphertext,credentialFingerprint:Oi(t.credential_fingerprint),credentialExpiresAt:Oi(t.credential_expires_at),status:String(t.status),healthMessage:Oi(t.health_message),lastTestedAt:Oi(t.last_tested_at),version:Number(t.version),createdByActorId:Oi(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}class zo{controlPlane;key;nowFn;idFn;constructor(t,e){this.controlPlane=t;if(!e.encryptionKey)throw Error("Registry encryption key is required");this.key=Dg("sha256").update(`ts-cloud:registry:${e.encryptionKey}`).digest(),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}encrypt(t){let e=vE(12),n=PE("aes-256-gcm",this.key,e),r=Buffer.concat([n.update(t,"utf8"),n.final()]);return`v1.${e.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${r.toString("base64url")}`}decrypt(t){let[e,n,r,i]=t.split(".");if(e!=="v1"||!n||!r||!i)throw Error("Registry credential envelope is invalid");let c=$E("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return c.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([c.update(Buffer.from(i,"base64url")),c.final()]).toString("utf8")}current(t){let e=kE(t);return e.status!=="disconnected"&&e.credentialExpiresAt&&new Date(e.credentialExpiresAt).getTime()<=this.nowFn().getTime()?{...e,status:"expired",healthMessage:"Registry credential expired; rotate it before pulling images."}:e}create(t){if(!["docker_hub","ghcr","ecr","gcr","generic"].includes(t.provider))throw Error("A supported registry provider is required");let e=t.credential?JSON.stringify(t.credential):void 0,n=this.idFn(),r=this.now();return this.controlPlane.database.run("INSERT INTO registry_connections (id, organization_id, provider, name, host, credential_ciphertext, credential_fingerprint, credential_expires_at, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.organizationId,t.provider,t.name.trim().slice(0,80),wg(t.host),e?this.encrypt(e):null,e?Bo(e):null,t.credentialExpiresAt??null,t.actorId??null,r,r]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.actorId,type:"registry.connection.created",payload:{connectionId:n,provider:t.provider,host:wg(t.host),credentialConfigured:!!e}}),this.get(n)}get(t){let e=this.controlPlane.database.query("SELECT * FROM registry_connections WHERE id=?").get(t);return e?this.current(e):void 0}list(t){return this.controlPlane.database.query("SELECT * FROM registry_connections WHERE organization_id=? ORDER BY name").all(t).map((e)=>this.current(e))}credential(t){let e=this.controlPlane.database.query("SELECT credential_ciphertext FROM registry_connections WHERE id=?").get(t);return e?.credential_ciphertext?JSON.parse(this.decrypt(String(e.credential_ciphertext))):void 0}rotate(t,e,n={}){let r=this.get(t);if(!r||r.status==="disconnected")throw Error("Registry connection was not found");let i=JSON.stringify(e);return this.controlPlane.database.run("UPDATE registry_connections SET credential_ciphertext=?, credential_fingerprint=?, credential_expires_at=?, status='pending', health_message=NULL, version=version+1, updated_at=? WHERE id=?",[this.encrypt(i),Bo(i),n.expiresAt??null,this.now(),t]),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:n.actorId,type:"registry.credential.rotated",payload:{connectionId:t,fingerprint:Bo(i),expiresAt:n.expiresAt??null}}),this.get(t)}disconnect(t,e){let n=this.get(t);if(!n)throw Error("Registry connection was not found");return this.controlPlane.database.run("UPDATE registry_connections SET credential_ciphertext=NULL, credential_fingerprint=NULL, status='disconnected', health_message='Disconnected by an administrator', version=version+1, updated_at=? WHERE id=?",[this.now(),t]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:e,type:"registry.connection.disconnected",level:"warning",payload:{connectionId:t}}),this.get(t)}async test(t,e={}){let n=this.get(t);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active registry connection was not found");let r=this.credential(t),i=e.fetch??fetch,c=new AbortController,d=setTimeout(()=>c.abort(),e.timeoutMs??15000),a=r?.token?`Bearer ${r.token}`:r?.username||r?.password?`Basic ${Buffer.from(`${r.username??""}:${r.password??""}`).toString("base64")}`:void 0;try{let l=await i(`${n.host}/v2/`,{method:"GET",redirect:"error",signal:c.signal,headers:a?{Authorization:a}:void 0}),o=l.headers.get("www-authenticate")??"";if(l.status===401&&o.startsWith("Bearer ")&&r){let R=Object.fromEntries([...o.slice(7).matchAll(/(\w+)="([^"]+)"/g)].map((J)=>[J[1],J[2]])),E=new URL(R.realm??"");if(E.protocol!=="https:")throw Error("Registry authentication realm must use HTTPS");if(R.service)E.searchParams.set("service",R.service);if(e.image)E.searchParams.set("scope",`repository:${yg(e.image).repository}:pull`);let y=await i(E,{signal:c.signal,redirect:"error",headers:a?{Authorization:a}:void 0});if(!y.ok)throw Error(`Registry authentication failed (${y.status})`);let $=await y.json(),C=$.token??$.access_token;if(!C)throw Error("Registry did not return an access token");l=e.image?await Ag(i,n.host,e.image,C,c.signal):await i(`${n.host}/v2/`,{signal:c.signal,redirect:"error",headers:{Authorization:`Bearer ${C}`}})}else if(l.ok&&e.image)l=await Ag(i,n.host,e.image,r?.token,c.signal,a);let u=l.ok?"healthy":"degraded",f=l.ok?e.image?"Registry image is readable.":"Registry connection is healthy.":`Registry request failed (${l.status})`;return this.controlPlane.database.run("UPDATE registry_connections SET status=?, health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[u,f,this.now(),this.now(),t]),this.get(t)}catch(l){let o=c.signal.aborted?"Registry request timed out.":l instanceof Error?l.message:"Registry test failed";return this.controlPlane.database.run("UPDATE registry_connections SET status='degraded', health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[o.slice(0,1000),this.now(),this.now(),t]),this.get(t)}finally{clearTimeout(d)}}}function yg(t){let e=t.replace(/^https?:\/\//,""),n=e.indexOf("/");if(n<1)throw Error("Image must include registry/repository");let r=e.slice(n+1),i=r.lastIndexOf("@"),c=r.lastIndexOf(":"),d=i>=0?i:c>r.lastIndexOf("/")?c:-1,a=d>=0?r.slice(0,d):r,l=d>=0?r.slice(d+1):"latest";if(!/^[A-Za-z0-9_.\/-]+$/.test(a)||!/^[A-Za-z0-9_.:+-]+$/.test(l))throw Error("Image reference is invalid");return{repository:a,reference:l}}async function Ag(t,e,n,r,i,c){let d=yg(n);return t(`${e}/v2/${d.repository}/manifests/${encodeURIComponent(d.reference)}`,{method:"HEAD",redirect:"error",signal:i,headers:{Accept:"application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json",...r?{Authorization:`Bearer ${r}`}:c?{Authorization:c}:{}}})}import{createHash as CE}from"node:crypto";import{chmodSync as Pg,existsSync as $g,mkdirSync as OE,renameSync as JE,unlinkSync as vg,writeFileSync as BE}from"node:fs";import{basename as zE,join as TE}from"node:path";function To(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),filename:String(t.filename),sha256:String(t.sha256),size:Number(t.size),format:String(t.format),entryCount:Number(t.entry_count),expandedBytes:Number(t.expanded_bytes),createdByActorId:t.created_by_actor_id?String(t.created_by_actor_id):void 0,createdAt:String(t.created_at)}}class bo{controlPlane;root;idFn;nowFn;constructor(t,e){this.controlPlane=t;this.root=de(e.cwd,"artifacts"),this.idFn=e.id??(()=>crypto.randomUUID()),this.nowFn=e.now??(()=>new Date)}create(t){let e=this.controlPlane.getProject(t.projectId);if(!e||e.organizationId!==t.organizationId)throw Error("Artifact project was not found");let n=zE(t.filename).slice(0,200);if(!n||n!==t.filename)throw Error("Artifact filename must not contain a path");let r=Sg(t.bytes,n),i=CE("sha256").update(t.bytes).digest("hex"),c=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? AND sha256=?").get(t.projectId,i);if(c)return To(c);let d=this.idFn();OE(this.root,{recursive:!0,mode:448}),Pg(this.root,448);let a=TE(this.root,`${d}.archive`),l=`${a}.partial`;try{BE(l,t.bytes,{mode:384,flag:"wx"}),JE(l,a),Pg(a,384),this.controlPlane.database.run("INSERT INTO application_artifacts (id, organization_id, project_id, filename, storage_path, sha256, size, format, entry_count, expanded_bytes, created_by_actor_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[d,t.organizationId,t.projectId,n,a,i,t.bytes.byteLength,r.format,r.entries,r.expandedBytes,t.actorId??null,this.nowFn().toISOString()])}catch(o){if($g(l))vg(l);if($g(a))vg(a);throw o}return this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,actorId:t.actorId,type:"application.artifact.created",payload:{artifactId:d,filename:n,sha256:i,size:t.bytes.byteLength,entries:r.entries}}),this.get(d)}get(t){let e=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE id=?").get(t);return e?To(e):void 0}list(t){return this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? ORDER BY created_at DESC").all(t).map(To)}}function wc(t){let e=t.drafts.get(t.draftId);if(!e||e.version!==t.expectedVersion)throw Error(`Application draft ${t.draftId} changed since version ${t.expectedVersion}`);if(e.status==="applied")throw Error("Application draft was already applied");let n=t.controlPlane.getProject(e.projectId),r=n?t.controlPlane.listEnvironments(n.id).find((o)=>o.id===e.input.environmentId):void 0;if(!n||!r||r.projectId!==n.id||n.organizationId!==e.organizationId)throw Error("Draft deployment scope was not found");if(t.confirmEnvironment!==r.slug)throw Error(`Type ${r.slug} to confirm this deployment target`);let i=Fe(e.input,e.suppliedSecretNames);if(!i.valid)throw Error(`Application plan is invalid: ${[...i.issues.map((o)=>o.message),...i.missingSecrets.map((o)=>`Missing secret ${o}`)].join("; ")}`);let c=t.controlPlane.listResources(n.id,r.id).find((o)=>o.kind==="application"&&o.slug===e.input.slug),d=JSON.parse(JSON.stringify({manifest:i.manifest,configPatch:i.configPatch})),a=c?t.controlPlane.updateResource(c.id,c.version,{name:e.input.name,desiredState:d}):t.controlPlane.createResource({projectId:n.id,environmentId:r.id,kind:"application",slug:e.input.slug,name:e.input.name,desiredState:d,metadata:{source:"application-onboarding",draftId:e.id}}),l=new Ot(t.controlPlane).enqueue({projectId:n.id,environmentId:r.id,resourceId:a.id,actorId:t.actorId,kind:"application.create",idempotencyKey:`application-draft:${e.id}:v${e.version}`,correlationId:`application-draft:${e.id}`,input:d,lockKey:`resource:${a.id}`,providerKey:a.provider??"default",buildSlot:e.input.build.kind!=="prebuilt_image",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return t.drafts.markApplied(e.id,e.version,t.actorId),t.controlPlane.appendEvent({organizationId:e.organizationId,projectId:n.id,resourceId:a.id,operationId:l.id,actorId:t.actorId,type:"application.create.queued",payload:{draftId:e.id,environment:r.slug,strategy:e.input.build.kind,costDrivers:i.costDrivers}}),{plan:i,resource:a,operation:l}}function Ji(t){let e=["static","compute","serverless_zip","serverless_image"].includes(t.kind),n=["container","compose"].includes(t.kind)&&(t.replicas??1)>1,r=t.kind==="container"||t.kind==="serverless_zip"||t.kind==="serverless_image",i=(c,d)=>d&&(c==="atomic"?t.kind==="static"||t.hasHealthGate:t.hasHealthGate);return[{strategy:"atomic",supported:i("atomic",e),explanation:e?t.hasHealthGate||t.kind==="static"?"Activate an immutable version with an atomic pointer/alias switch.":"Atomic activation needs a readiness gate for this runtime.":"This driver has no atomic pointer or alias primitive.",capacityMultiplier:1,costImpact:"none",rollback:"Switch the pointer/alias back to the previous immutable release."},{strategy:"rolling",supported:i("rolling",n),explanation:n?t.hasHealthGate?"Replace healthy replicas within the configured capacity envelope.":"Rolling activation requires a health/readiness gate.":"Rolling activation requires a capable container/Compose driver and at least two replicas.",capacityMultiplier:1.5,costImpact:"temporary",rollback:"Stop replacement and restore the prior task/service definition."},{strategy:"blue_green",supported:i("blue_green",r),explanation:r?t.hasHealthGate?"Provision a complete green target and switch traffic after health passes.":"Blue-green requires a health gate before traffic can switch.":"The provider does not expose two traffic-addressable revisions.",capacityMultiplier:2,costImpact:"temporary",rollback:"Return all traffic to the preserved blue target."},{strategy:"canary",supported:i("canary",r),explanation:r?t.hasHealthGate?"Shift bounded traffic steps while evaluating health.":"Canary requires a health gate and measurable traffic target.":"The provider does not expose weighted traffic primitives.",capacityMultiplier:1.25,costImpact:"temporary",rollback:"Set canary weight to zero and preserve its diagnostics."}]}function Ac(t,e){let n=Ji(t).find((r)=>r.strategy===e);if(!n.supported)throw Error(`${e} is unavailable: ${n.explanation}`);return n}import{createHash as bE}from"node:crypto";var WE=/^sha256:[a-f0-9]{64}$/,UE=/^[a-f0-9]{40,64}$/i;function nn(t){return typeof t==="string"&&t?t:void 0}function sr(t,e){try{return JSON.parse(String(t))}catch{return e}}function kg(t){return{id:String(t.id),organizationId:String(t.organization_id),digest:String(t.digest),kind:String(t.kind),uri:String(t.uri),size:Number(t.size),mediaType:String(t.media_type),provenance:sr(t.provenance,{}),attestation:sr(t.attestation,{}),verifiedAt:String(t.verified_at),createdAt:String(t.created_at)}}function Cg(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:String(t.environment_id),resourceId:String(t.resource_id),artifactId:String(t.artifact_id),kind:String(t.kind),sourceSha:nn(t.source_sha),configHash:String(t.config_hash),manifest:sr(t.manifest,{}),provenance:sr(t.provenance,{}),strategy:String(t.strategy),status:String(t.status),healthGate:t.health_gate==null?void 0:sr(t.health_gate,void 0),hooks:sr(t.hooks,{migrations:"none",preActivate:[],postActivate:[]}),drainSeconds:Number(t.drain_seconds),graceSeconds:Number(t.grace_seconds),automaticRollback:Number(t.automatic_rollback)===1,rollbackAttempts:Number(t.rollback_attempts),previousReleaseId:nn(t.previous_release_id),promotedFromReleaseId:nn(t.promoted_from_release_id),actorId:nn(t.actor_id),trigger:String(t.trigger),pinned:Number(t.pinned)===1,pinReason:nn(t.pin_reason),activatedAt:nn(t.activated_at),failedAt:nn(t.failed_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function jE(t){return{sequence:Number(t.sequence),id:String(t.id),releaseId:String(t.release_id),fromStatus:nn(t.from_status),toStatus:String(t.to_status),trafficPercent:t.traffic_percent==null?void 0:Number(t.traffic_percent),health:sr(t.health,{}),message:String(t.message),operationId:nn(t.operation_id),createdAt:String(t.created_at)}}function HE(t,e){let n=[],r=(i,c,d)=>{if(JSON.stringify(c)===JSON.stringify(d))return;if(c&&d&&typeof c==="object"&&typeof d==="object"&&!Array.isArray(c)&&!Array.isArray(d)){for(let a of[...new Set([...Object.keys(c),...Object.keys(d)])].sort())r(i?`${i}.${a}`:a,c[a],d[a]);return}n.push({path:i,...c!==void 0?{before:c}:{},...d!==void 0?{after:d}:{}})};return r("",t,e),n}class Wo{controlPlane;now;id;constructor(t,e={}){this.controlPlane=t;this.now=e.now??(()=>new Date),this.id=e.id??(()=>crypto.randomUUID())}registerArtifact(t){if(!WE.test(t.digest)||!/^(?:s3|https|oci|file):/.test(t.uri)||!Number.isInteger(t.size)||t.size<0)throw Error("Artifact requires a SHA-256 digest, supported immutable URI, and non-negative byte size");let e=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE organization_id=? AND digest=?").get(t.organizationId,t.digest);if(e)return kg(e);let n=this.id(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO release_artifacts (id, organization_id, digest, kind, uri, size, media_type, provenance, attestation, verified_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.organizationId,t.digest,t.kind,t.uri,t.size,t.mediaType??"application/octet-stream",JSON.stringify(bt(t.provenance??{})),JSON.stringify(bt(t.attestation??{})),r,r]),this.getArtifact(n)}getArtifact(t){let e=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE id=?").get(t);return e?kg(e):void 0}create(t){let e=this.getArtifact(t.artifactId),n=this.controlPlane.getResource(t.resourceId),r=this.controlPlane.listEnvironments(t.projectId).find((f)=>f.id===t.environmentId);if(!e||e.organizationId!==t.organizationId||e.kind!==t.kind)throw Error("Release artifact does not match the organization and deployable kind");if(!n||n.projectId!==t.projectId||n.environmentId!==t.environmentId||!r)throw Error("Release target scope does not match the resource");if(t.sourceSha&&!UE.test(t.sourceSha))throw Error("Release source must be an immutable commit SHA");Ac({kind:t.kind,provider:n.provider,hasHealthGate:!!t.healthGate,replicas:t.replicas},t.strategy);let i=bt(t.config),c=bE("sha256").update(JSON.stringify(i)).digest("hex"),d=this.active(t.resourceId),a=this.id(),l=this.now().toISOString(),o=t.approvalRequired?"awaiting_approval":"built",u=t.hooks??{migrations:"none",preActivate:[],postActivate:[]};return this.controlPlane.database.run("INSERT INTO releases (id, organization_id, project_id, environment_id, resource_id, artifact_id, kind, source_sha, config_hash, manifest, provenance, strategy, status, health_gate, hooks, drain_seconds, grace_seconds, automatic_rollback, previous_release_id, promoted_from_release_id, actor_id, trigger, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[a,t.organizationId,t.projectId,t.environmentId,t.resourceId,t.artifactId,t.kind,t.sourceSha??null,c,JSON.stringify(bt(t.manifest)),JSON.stringify(bt(t.provenance??{})),t.strategy,o,t.healthGate?JSON.stringify(t.healthGate):null,JSON.stringify(u),Math.max(0,Math.min(3600,Math.floor(t.drainSeconds??30))),Math.max(0,Math.min(3600,Math.floor(t.graceSeconds??30))),t.automaticRollback===!1?0:1,d?.id??null,t.promotedFromReleaseId??null,t.actorId??null,t.trigger??"manual",l,l]),this.recordTransition(a,void 0,o,{message:t.promotedFromReleaseId?"Immutable artifact promoted without rebuild.":"Immutable release record created."}),this.get(a)}get(t){let e=this.controlPlane.database.query("SELECT * FROM releases WHERE id=?").get(t);return e?Cg(e):void 0}list(t={}){return this.controlPlane.database.query("SELECT * FROM releases ORDER BY created_at DESC, rowid DESC").all().map(Cg).filter((e)=>(!t.projectId||e.projectId===t.projectId)&&(!t.environmentId||e.environmentId===t.environmentId)&&(!t.resourceId||e.resourceId===t.resourceId)&&(!t.status||e.status===t.status))}active(t){return this.list({resourceId:t,status:"active"})[0]}transitions(t){return this.controlPlane.database.query("SELECT * FROM release_transitions WHERE release_id=? ORDER BY sequence").all(t).map(jE)}recordTransition(t,e,n,r){this.controlPlane.database.run("INSERT INTO release_transitions (id, release_id, from_status, to_status, traffic_percent, health, message, operation_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",[this.id(),t,e??null,n,r.trafficPercent??null,JSON.stringify(bt(r.health??{})),r.message.slice(0,1000),r.operationId??null,this.now().toISOString()])}progress(t,e){let n=this.get(t);if(!n)throw Error(`Release ${t} was not found`);return this.recordTransition(t,n.status,n.status,e),this.transitions(t).at(-1)}transition(t,e,n){let r=this.get(t);if(!r)throw Error(`Release ${t} was not found`);if(!{built:["awaiting_approval","activating","failed"],awaiting_approval:["built","failed"],activating:["active","failed","rolled_back"],active:["superseded","failed","rolled_back"],failed:["activating","rolled_back"],rolled_back:["activating"],superseded:["activating"]}[r.status].includes(e))throw Error(`Invalid release transition ${r.status} → ${e}`);let c=this.now().toISOString();if(e==="active"){let d=this.active(r.resourceId);if(d&&d.id!==t)this.controlPlane.database.run("UPDATE releases SET status='superseded', updated_at=? WHERE id=?",[c,d.id]),this.recordTransition(d.id,"active","superseded",{message:`Superseded by ${t}.`,operationId:n.operationId})}return this.controlPlane.database.run("UPDATE releases SET status=?, rollback_attempts=rollback_attempts+?, activated_at=CASE WHEN ?='active' THEN ? ELSE activated_at END, failed_at=CASE WHEN ?='failed' THEN ? ELSE failed_at END, updated_at=? WHERE id=?",[e,e==="rolled_back"?1:0,e,c,e,c,c,t]),this.recordTransition(t,r.status,e,n),this.get(t)}approve(t,e){let n=this.get(t);if(!n||n.status!=="awaiting_approval")throw Error("Release is not awaiting approval");let r=this.id(),i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO release_approvals (id, release_id, environment_id, decision, actor_id, comment, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[r,t,n.environmentId,e.decision,e.actorId,e.comment?.slice(0,1000)??null,i]),this.transition(t,e.decision==="approved"?"built":"failed",{message:e.decision==="approved"?"Environment gate approved.":"Environment gate rejected."})}approvals(t){return this.controlPlane.database.query("SELECT * FROM release_approvals WHERE release_id=? ORDER BY created_at").all(t).map((e)=>({id:String(e.id),releaseId:String(e.release_id),environmentId:String(e.environment_id),decision:String(e.decision),actorId:String(e.actor_id),comment:nn(e.comment),createdAt:String(e.created_at)}))}promote(t,e){let n=this.get(t);if(!n||!["active","superseded"].includes(n.status))throw Error("Only a tested active/superseded release can be promoted");return this.create({organizationId:n.organizationId,projectId:n.projectId,environmentId:e.targetEnvironmentId,resourceId:e.targetResourceId,artifactId:n.artifactId,kind:n.kind,sourceSha:n.sourceSha,config:e.config,manifest:n.manifest,provenance:n.provenance,strategy:e.strategy??n.strategy,healthGate:e.healthGate??n.healthGate,hooks:n.hooks,drainSeconds:n.drainSeconds,graceSeconds:n.graceSeconds,automaticRollback:n.automaticRollback,promotedFromReleaseId:n.id,actorId:e.actorId,trigger:"promotion",approvalRequired:e.approvalRequired})}compare(t,e){let n=this.get(t),r=this.get(e);if(!n||!r)throw Error("Both releases are required for comparison");return{artifactChanged:n.artifactId!==r.artifactId,sourceChanged:n.sourceSha!==r.sourceSha,configChanged:n.configHash!==r.configHash,manifestChanges:HE(n.manifest,r.manifest),dataCaveat:r.hooks.migrations==="none"?"No database migration is recorded.":`Database hooks are ${r.hooks.migrations}; release rollback does not roll back data.`}}pin(t,e,n){if(!this.get(t))throw Error("Release was not found");return this.controlPlane.database.run("UPDATE releases SET pinned=?, pin_reason=?, updated_at=? WHERE id=?",[e?1:0,e?n?.slice(0,500)??"operator":null,this.now().toISOString(),t]),this.get(t)}retentionCandidates(t){let e=Math.max(1,Math.min(100,Math.floor(t.keepPerResource??10))),n=new Map;for(let r of this.list()){let i=n.get(r.resourceId)??[];i.push(r),n.set(r.resourceId,i)}return[...n.values()].flatMap((r)=>r.slice(e)).filter((r)=>new Date(r.createdAt)<t.before&&!r.pinned&&!["active","activating","awaiting_approval"].includes(r.status)&&!this.list().some((i)=>i.previousReleaseId===r.id&&["active","activating"].includes(i.status)))}}class lr{controlPlane;releases;queue;constructor(t){this.controlPlane=t;this.releases=new Wo(t),this.queue=new Ot(t)}enqueueActivation(t,e={}){let n=this.releases.get(t.id);if(!n)throw Error("Release was not found");if(!["built","failed","rolled_back","superseded"].includes(n.status))throw Error(`Release ${n.status} cannot be activated`);let r=e.action??"activate",i=this.queue.enqueue({projectId:n.projectId,environmentId:n.environmentId,resourceId:n.resourceId,actorId:e.actorId,kind:`release.${r}`,idempotencyKey:`release:${n.id}:${r}:${n.rollbackAttempts}`,correlationId:`release:${n.id}`,input:{releaseId:n.id,targetReleaseId:e.targetReleaseId??null},lockKey:`resource:${n.resourceId}`,providerKey:this.controlPlane.getResource(n.resourceId)?.provider??"default",maxAttempts:n.automaticRollback?2:1,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return this.releases.transition(n.id,"activating",{message:`${r} queued.`,operationId:i.id,trafficPercent:0}),i}completeHealthGate(t,e){let n=this.releases.get(t);if(!n||n.status!=="activating")throw Error("Release is not activating");if(e.healthy)return{release:this.releases.transition(n.id,"active",{message:e.message??"Health gate passed; activation completed.",operationId:e.operationId,trafficPercent:100,health:e.health})};let r=this.releases.transition(n.id,"failed",{message:e.message??"Health gate failed.",operationId:e.operationId,trafficPercent:0,health:e.health}),i=n.previousReleaseId?this.releases.get(n.previousReleaseId):void 0;if(!n.automaticRollback||n.rollbackAttempts>=1||!i)return{release:r};let c=this.queue.enqueue({projectId:n.projectId,environmentId:n.environmentId,resourceId:n.resourceId,kind:"release.rollback",idempotencyKey:`release:${n.id}:automatic-rollback`,correlationId:`release:${n.id}`,input:{releaseId:n.id,targetReleaseId:i.id,automatic:!0},lockKey:`resource:${n.resourceId}`,providerKey:this.controlPlane.getResource(n.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return{release:r,rollbackOperation:c}}enqueueRollback(t,e={}){let n=this.releases.get(t.id);if(!n||n.status!=="active")throw Error("Only the active release can be rolled back");let r=e.targetReleaseId?this.releases.get(e.targetReleaseId):n.previousReleaseId?this.releases.get(n.previousReleaseId):void 0;if(!r||r.resourceId!==n.resourceId||!["superseded","active"].includes(r.status))throw Error("Rollback requires a preserved prior release for the same resource");return this.queue.enqueue({projectId:n.projectId,environmentId:n.environmentId,resourceId:n.resourceId,actorId:e.actorId,kind:"release.rollback",idempotencyKey:`release:${n.id}:manual-rollback:${r.id}`,correlationId:`release:${n.id}`,input:{releaseId:n.id,targetReleaseId:r.id,automatic:!1},lockKey:`resource:${n.resourceId}`,providerKey:this.controlPlane.getResource(n.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}}function LE(t){if(t.strategy==="canary")return[5,25,50,100].map((e,n)=>({step:`canary-${e}`,trafficPercent:e,waitSeconds:n===3?t.drainSeconds:t.graceSeconds,requiresHealth:!0}));if(t.strategy==="blue_green")return[{step:"green-health",trafficPercent:0,waitSeconds:t.graceSeconds,requiresHealth:!0},{step:"traffic-switch",trafficPercent:100,waitSeconds:t.drainSeconds,requiresHealth:!0}];if(t.strategy==="rolling")return[{step:"rolling-replacement",trafficPercent:50,waitSeconds:t.graceSeconds,requiresHealth:!0},{step:"rolling-complete",trafficPercent:100,waitSeconds:t.drainSeconds,requiresHealth:!0}];return[{step:"immutable-switch",trafficPercent:100,waitSeconds:t.drainSeconds,requiresHealth:!!t.healthGate}]}async function Og(t,e){if(e.release.artifactId!==e.artifact.id)throw Error("Release activation artifact identity changed");Ac({kind:e.release.kind,hasHealthGate:!!e.release.healthGate,replicas:Number(e.release.manifest?.replicas)||void 0},e.release.strategy);let n=t.capability(e);if(!n.supported)throw Error(`${e.release.strategy} is unavailable in ${t.name}: ${n.explanation}`);return t.activate({...e,transitions:LE(e.release)})}async function Jg(t,e){if(!e.previous)throw Error("Rollback requires the preserved previous release");return t.rollback({...e,transitions:[{step:"rollback",trafficPercent:0,waitSeconds:e.release.drainSeconds,requiresHealth:!0}]})}var FE=["release.activate","release.rollback"];function VE(t){return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}function Bg(t){let e=new lr(t.store),n=async(r)=>{let i=VE(r.operation.input),c=typeof i.releaseId==="string"?i.releaseId:"",d=e.releases.get(c);if(!d)throw Error(`Queued release ${c||"(missing)"} was not found`);if(d.projectId!==r.operation.projectId||d.environmentId!==r.operation.environmentId||d.resourceId!==r.operation.resourceId)throw Error("Queued release does not match the operation scope");let a=e.releases.getArtifact(d.artifactId);if(!a||a.digest!==e.releases.getArtifact(d.artifactId)?.digest)throw Error("Immutable release artifact is unavailable");let l=typeof i.targetReleaseId==="string"&&i.targetReleaseId?i.targetReleaseId:d.previousReleaseId,o=l?e.releases.get(l):void 0;if(o&&(o.resourceId!==d.resourceId||o.artifactId===d.artifactId&&o.id===d.id))throw Error("Rollback target does not match the release resource");let u=await t.resolveDriver(d);r.checkpoint("verify",`Verifying ${a.digest} and ${d.configHash} for ${u.name}.`),r.log(`Artifact ${a.digest}; source ${d.sourceSha??"not recorded"}; config ${d.configHash}.`,{stream:"system"}),r.throwIfCancellationRequested();let f;try{f=r.operation.kind==="release.rollback"?await Jg(u,{release:d,artifact:a,previous:o}):await Og(u,{release:d,artifact:a,previous:o})}catch(R){if(r.operation.kind==="release.activate"&&e.releases.get(d.id)?.status==="activating")e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,message:R instanceof Error?R.message:String(R)});throw R}for(let R of f.transitions)e.releases.progress(d.id,{message:`${r.operation.kind==="release.rollback"?"Rollback":"Activation"} traffic at ${R.trafficPercent}%.`,trafficPercent:R.trafficPercent,health:R.observed,operationId:r.operation.id}),r.log(`Traffic ${R.trafficPercent}%: ${R.healthy?"healthy":"unhealthy"}.`,{stream:R.healthy?"step":"stderr",step:"health"});if(r.checkpoint("health","Evaluating the provider health result."),!f.activated||!f.healthy){if(r.operation.kind==="release.activate"&&e.releases.get(d.id)?.status==="activating")e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,health:{resourceVersions:f.resourceVersions},message:f.error??"Provider health gate failed."});throw Error(f.error??`${u.name} reported an unhealthy release`)}if(r.operation.kind==="release.activate"&&d.healthGate?.name){if(!t.resolveHealthGate)throw e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,message:`Named health gate ${d.healthGate.name} is not available to this worker.`}),Error(`Named health gate ${d.healthGate.name} is unavailable`);r.checkpoint("named-health-gate",`Waiting on ${d.healthGate.name}.`);let R=await t.resolveHealthGate(d.healthGate.name,d);if(r.log(`${d.healthGate.name}: ${R.healthy?"healthy":"unhealthy"}${R.message?` — ${R.message}`:""}.`,{stream:R.healthy?"step":"stderr",step:"health"}),!R.healthy)throw e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,health:R.evidence,message:R.message??`Named health gate ${d.healthGate.name} failed.`}),Error(R.message??`Named health gate ${d.healthGate.name} failed`)}if(r.operation.kind==="release.rollback"){let R=e.releases.get(d.id);if(R.status!=="rolled_back")e.releases.transition(R.id,"rolled_back",{message:`Traffic restored through ${u.name}.`,operationId:r.operation.id,trafficPercent:0,health:{resourceVersions:f.resourceVersions}});if(o&&o.status!=="active"){let E=o.status==="activating"?o:e.releases.transition(o.id,"activating",{message:"Rollback target restoring traffic.",operationId:r.operation.id,trafficPercent:0});e.releases.transition(E.id,"active",{message:"Previous immutable release restored.",operationId:r.operation.id,trafficPercent:100,health:{resourceVersions:f.resourceVersions}})}}else e.completeHealthGate(d.id,{healthy:!0,operationId:r.operation.id,health:{providerVersion:f.providerVersion??null,resourceVersions:f.resourceVersions},message:"Provider activation and health gates completed."});return r.checkpoint("finalize","Persisted the terminal release state."),{releaseId:d.id,artifactDigest:a.digest,provider:u.name,providerVersion:f.providerVersion??null,resourceVersions:f.resourceVersions,status:e.releases.get(d.id).status}};return Object.fromEntries(FE.map((r)=>[r,n]))}import{createCipheriv as NE,createDecipheriv as xE,createHash as Ug,randomBytes as Uo}from"node:crypto";var jg={github:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0},gitlab:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0},bitbucket:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0},gitea:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!1,deployKeys:!0},generic_https:{repositories:!1,branches:!0,tags:!0,webhooks:!1,pullRequests:!1,tokenRefresh:!1,deployKeys:!1},generic_ssh:{repositories:!1,branches:!0,tags:!0,webhooks:!1,pullRequests:!1,tokenRefresh:!1,deployKeys:!0}};function Pt(t){return typeof t==="string"&&t?t:void 0}function ur(t,e){try{return typeof t==="string"?JSON.parse(t):e}catch{return e}}function rn(t){return JSON.stringify(bt(t))}function gr(t){return Ug("sha256").update(t).digest("hex")}function zg(t){let e=t.trim().replace(/\/$/,""),n=new URL(e.includes("://")?e:`https://${e}`);if(n.username||n.password||n.search||n.hash)throw Error("Source host cannot contain credentials, a query, or a fragment");if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(n.hostname)))throw Error("Source host must use HTTPS");return`${n.protocol}//${n.host}${n.pathname.replace(/\/$/,"")}`}function Tg(t){let e=t.trim();if(e.length<2||e.length>80)throw Error("Connection name must contain 2-80 characters");return e}function jo(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e))throw Error("Repository must use owner/name format");return e}function bg(t){let e=t.trim()||".";if(e.startsWith("/")||e.split("/").includes("..")||/[\0\r\n]/.test(e))throw Error("Monorepo root must stay inside the repository");return e.replace(/^\.\//,"")||"."}function Dc(t){return[...new Set((t??[]).map((e)=>e.trim()).filter(Boolean))].slice(0,100)}function ME(t){let e=t.trim();if(/\r|\n/.test(e)||/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(e))throw Error("Clone URL cannot contain credentials or control characters");if(!/^(?:https?:\/\/|ssh:\/\/|git@[A-Za-z0-9.-]+:)/.test(e))throw Error("Clone URL must use HTTPS or SSH");return e}function QE(t){return{id:String(t.id),organizationId:String(t.organization_id),provider:String(t.provider),name:String(t.name),host:String(t.host),owner:Pt(t.owner),authKind:String(t.auth_kind),credentialConfigured:!!t.credential_ciphertext,credentialFingerprint:Pt(t.credential_fingerprint),grantedScopes:ur(t.granted_scopes,[]),capabilities:ur(t.capabilities,jg[String(t.provider)]),status:String(t.status),healthMessage:Pt(t.health_message),lastTestedAt:Pt(t.last_tested_at),lastSyncedAt:Pt(t.last_synced_at),credentialExpiresAt:Pt(t.credential_expires_at),version:Number(t.version),createdByActorId:Pt(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Ho(t){return{id:String(t.id),connectionId:String(t.connection_id),providerRepositoryId:String(t.provider_repository_id),fullName:String(t.full_name),cloneUrl:String(t.clone_url),defaultBranch:String(t.default_branch),visibility:String(t.visibility),archived:Number(t.archived)===1,metadata:ur(t.metadata,{}),syncedAt:String(t.synced_at)}}function Wg(t){return{id:String(t.id),projectId:String(t.project_id),environmentId:Pt(t.environment_id),resourceId:Pt(t.resource_id),connectionId:String(t.connection_id),repositoryId:Pt(t.repository_id),repositoryFullName:String(t.repository_full_name),defaultBranch:String(t.default_branch),branchRule:Pt(t.branch_rule),tagRule:Pt(t.tag_rule),monorepoRoot:String(t.monorepo_root),includePaths:ur(t.include_paths,[]),excludePaths:ur(t.exclude_paths,[]),submodules:Number(t.submodules)===1,cloneDepth:t.clone_depth==null?void 0:Number(t.clone_depth),deployKeyId:Pt(t.deploy_key_id),autoDeploy:Number(t.auto_deploy)===1,pullRequestPreviews:Number(t.pull_request_previews)===1,status:String(t.status),disabledReason:Pt(t.disabled_reason),version:Number(t.version),createdByActorId:Pt(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Lo(t){return{id:String(t.id),connectionId:String(t.connection_id),name:String(t.name),publicKey:String(t.public_key),publicKeyFingerprint:String(t.public_key_fingerprint),host:String(t.host),hostKey:String(t.host_key),hostKeyFingerprint:String(t.host_key_fingerprint),createdByActorId:Pt(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Fo(t){return{id:String(t.id),connectionId:String(t.connection_id),repositoryId:Pt(t.repository_id),repositoryFullName:String(t.repository_full_name),providerWebhookId:Pt(t.provider_webhook_id),events:ur(t.events,[]),status:String(t.status),healthMessage:Pt(t.health_message),lastDeliveryAt:Pt(t.last_delivery_at),lastReconciledAt:Pt(t.last_reconciled_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Vo(t){return{id:String(t.id),connectionId:String(t.connection_id),webhookId:String(t.webhook_id),providerDeliveryId:String(t.provider_delivery_id),event:String(t.event),action:Pt(t.action),commitSha:Pt(t.commit_sha),signatureStatus:String(t.signature_status),status:String(t.status),payloadSummary:ur(t.payload_summary,{}),operationId:Pt(t.operation_id),error:Pt(t.error),receivedAt:String(t.received_at),processedAt:Pt(t.processed_at)}}class No{controlPlane;key;nowFn;idFn;constructor(t,e={}){this.controlPlane=t;this.key=e.encryptionKey?Ug("sha256").update(e.encryptionKey).digest():void 0,this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(t,e){this.controlPlane.database.run(t,e)}encrypt(t){if(!this.key)throw Error("Source credential encryption key is not configured");let e=Uo(12),n=NE("aes-256-gcm",this.key,e),r=Buffer.concat([n.update(t,"utf8"),n.final()]);return`v1.${e.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${r.toString("base64url")}`}decrypt(t){if(!this.key)throw Error("Source credential encryption key is not configured");let[e,n,r,i]=t.split(".");if(e!=="v1"||!n||!r||!i)throw Error("Encrypted source credential is unavailable");let c=xE("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return c.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([c.update(Buffer.from(i,"base64url")),c.final()]).toString("utf8")}createConnection(t){if(!this.controlPlane.getOrganization(t.organizationId))throw Error("Source connection organization was not found");let e=this.now(),n=this.idFn(),r=t.credential?JSON.stringify(t.credential):void 0;return this.run(`INSERT INTO source_connections (id, organization_id, provider, name, host, owner, auth_kind, credential_ciphertext, credential_fingerprint, granted_scopes, capabilities, status, credential_expires_at, created_by_actor_id, created_at, updated_at)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,[n,t.organizationId,t.provider,Tg(t.name),zg(t.host),t.owner?.trim()||null,t.authKind??(r?"access_token":"none"),r?this.encrypt(r):null,r?gr(r).slice(0,16):null,rn([...new Set(t.grantedScopes??[])].sort()),rn(jg[t.provider]),t.credentialExpiresAt??null,t.createdByActorId??null,e,e]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.createdByActorId,type:"source.connection.created",payload:{connectionId:n,provider:t.provider,host:zg(t.host),owner:t.owner??null,scopes:t.grantedScopes??[]}}),this.getConnection(n)}getConnection(t){let e=this.controlPlane.database.query("SELECT * FROM source_connections WHERE id = ?").get(t);return e?this.currentConnection(e):void 0}listConnections(t){return this.controlPlane.database.query("SELECT * FROM source_connections WHERE organization_id = ? ORDER BY name").all(t).map((e)=>this.currentConnection(e))}currentConnection(t){let e=QE(t);if(e.status!=="disconnected"&&e.credentialExpiresAt&&new Date(e.credentialExpiresAt).getTime()<=this.nowFn().getTime())return{...e,status:"expired",healthMessage:"Source credential expired; rotate it before deploying."};return e}getCredential(t){let e=this.controlPlane.database.query("SELECT credential_ciphertext FROM source_connections WHERE id = ?").get(t);return e?.credential_ciphertext?JSON.parse(this.decrypt(String(e.credential_ciphertext))):void 0}rotateCredential(t,e,n={}){let r=this.getConnection(t);if(!r||r.status==="disconnected")throw Error("Active source connection was not found");let i=JSON.stringify(e);return this.run("UPDATE source_connections SET credential_ciphertext = ?, credential_fingerprint = ?, credential_expires_at = ?, status = 'pending', health_message = NULL, version = version + 1, updated_at = ? WHERE id = ?",[this.encrypt(i),gr(i).slice(0,16),n.expiresAt??null,this.now(),t]),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:n.actorId,type:"source.credential.rotated",payload:{connectionId:t,fingerprint:gr(i).slice(0,16),expiresAt:n.expiresAt??null}}),this.getConnection(t)}updateHealth(t,e){let n=this.getConnection(t);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active source connection was not found");let r=this.now(),i=e.grantedScopes?[...new Set(e.grantedScopes.map((c)=>c.trim()).filter(Boolean))].sort():void 0;if(this.run("UPDATE source_connections SET status = ?, health_message = ?, granted_scopes = COALESCE(?, granted_scopes), last_tested_at = COALESCE(?, last_tested_at), last_synced_at = COALESCE(?, last_synced_at), version = version + 1, updated_at = ? WHERE id = ?",[e.status,e.message?.slice(0,1000)??null,i?rn(i):null,e.tested?r:null,e.synced?r:null,r,t]),i&&JSON.stringify(i)!==JSON.stringify([...n.grantedScopes].sort()))this.controlPlane.appendEvent({organizationId:n.organizationId,type:"source.connection.scopes_updated",payload:{connectionId:t,grantedScopes:i}});return this.getConnection(t)}upsertRepository(t){let e=this.getConnection(t.connectionId);if(!e||["disconnected","expired"].includes(e.status))throw Error("Active source connection was not found");let n=this.now(),r=this.controlPlane.database.query("SELECT id FROM source_repositories WHERE connection_id = ? AND provider_repository_id = ?").get(t.connectionId,t.providerRepositoryId),i=r?String(r.id):this.idFn();return this.run(`INSERT INTO source_repositories (id, connection_id, provider_repository_id, full_name, clone_url, default_branch, visibility, archived, metadata, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
4
4
  ON CONFLICT(connection_id, provider_repository_id) DO UPDATE SET full_name=excluded.full_name, clone_url=excluded.clone_url, default_branch=excluded.default_branch, visibility=excluded.visibility, archived=excluded.archived, metadata=excluded.metadata, synced_at=excluded.synced_at`,[i,t.connectionId,t.providerRepositoryId,jo(t.fullName),ME(t.cloneUrl),t.defaultBranch.trim()||"main",t.visibility,t.archived?1:0,rn(t.metadata),n]),Ho(this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(i))}listRepositories(t,e,n=100){let r=e?.trim().toLowerCase();return(r?this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? AND lower(full_name) LIKE ? ORDER BY full_name LIMIT ?").all(t,`%${r}%`,Math.min(500,n)):this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? ORDER BY full_name LIMIT ?").all(t,Math.min(500,n))).map(Ho)}getRepository(t){let e=this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(t);return e?Ho(e):void 0}createDeployKey(t){let e=this.getConnection(t.connectionId);if(!e||["disconnected","expired"].includes(e.status)||!e.capabilities.deployKeys)throw Error("An active deploy-key capable source connection is required");if(!/^ssh-(?:ed25519|rsa)\s+[A-Za-z0-9+/=]+/.test(t.publicKey.trim()))throw Error("A valid SSH public key is required");if(!/BEGIN (?:OPENSSH|RSA) PRIVATE KEY/.test(t.privateKey))throw Error("A valid SSH private key is required");if(!/^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp\d+)\s+[A-Za-z0-9+/=]+/.test(t.hostKey.trim()))throw Error("A pinned SSH host key is required");let n=this.idFn(),r=this.now(),i=`sha256:${gr(t.publicKey.trim())}`,c=`sha256:${gr(t.hostKey.trim())}`;return this.run("INSERT INTO source_deploy_keys (id, connection_id, name, public_key, public_key_fingerprint, private_key_ciphertext, host, host_key, host_key_fingerprint, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.connectionId,Tg(t.name),t.publicKey.trim(),i,this.encrypt(t.privateKey),t.host.trim().toLowerCase(),t.hostKey.trim(),c,t.actorId??null,r,r]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:t.actorId,type:"source.deploy_key.created",payload:{connectionId:t.connectionId,deployKeyId:n,publicFingerprint:i,hostFingerprint:c}}),Lo(this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(n))}getDeployKey(t){let e=this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(t);return e?Lo(e):void 0}listDeployKeys(t){return this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE connection_id = ? ORDER BY name, created_at").all(t).map(Lo)}revokeDeployKey(t,e){let n=this.getDeployKey(t),r=n?this.getConnection(n.connectionId):void 0;if(!n||!r)throw Error("Deploy key was not found");let i=this.listBindings({connectionId:r.id}).filter((d)=>d.deployKeyId===t),c=this.now();return this.controlPlane.database.transaction(()=>{this.run("UPDATE source_bindings SET deploy_key_id=NULL, status='disabled', auto_deploy=0, disabled_reason='Source deploy key was revoked', version=version+1, updated_at=? WHERE deploy_key_id=?",[c,t]),this.run("DELETE FROM source_deploy_keys WHERE id=?",[t])})(),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:e,type:"source.deploy_key.revoked",level:"warning",payload:{connectionId:r.id,deployKeyId:t,affectedBindingIds:i.map((d)=>d.id)}}),{affectedBindings:i}}getDeployPrivateKey(t){let e=this.controlPlane.database.query("SELECT private_key_ciphertext FROM source_deploy_keys WHERE id = ?").get(t);if(!e)throw Error("Deploy key was not found");return this.decrypt(String(e.private_key_ciphertext))}createBinding(t){let e=this.getConnection(t.connectionId);if(!e||["disconnected","expired"].includes(e.status))throw Error("Active source connection was not found");if(t.repositoryId&&this.getRepository(t.repositoryId)?.connectionId!==e.id)throw Error("Repository does not belong to this connection");if(t.deployKeyId&&this.getDeployKey(t.deployKeyId)?.connectionId!==e.id)throw Error("Deploy key does not belong to this connection");let n=this.idFn(),r=this.now();return this.run(`INSERT INTO source_bindings (id, project_id, environment_id, resource_id, connection_id, repository_id, repository_full_name, default_branch, branch_rule, tag_rule, monorepo_root, include_paths, exclude_paths, submodules, clone_depth, deploy_key_id, auto_deploy, pull_request_previews, status, created_by_actor_id, created_at, updated_at)
@@ -475,7 +475,7 @@ data: ${JSON.stringify({cursor:c,at:new Date().toISOString()})}
475
475
  ${a}
476
476
  ${l}`);return null}return r}catch(i){if(r)Wr(r,{recursive:!0,force:!0});if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build errored; serving the pre-built UI. ${i.message}`);return null}}function ZP(t){let e=t.infrastructure?.compute?.managedServices?JSON.parse(JSON.stringify(t.infrastructure.compute.managedServices)):void 0;if(e?.vitess?.password)e.vitess.password="";return{project:{name:t.project?.name,slug:t.project?.slug,region:t.project?.region},provider:t.provider,environments:Object.keys(t.environments??{}),compute:t.infrastructure?.compute?{provider:t.infrastructure.compute.provider,runtime:t.infrastructure.compute.runtime,webServer:t.infrastructure.compute.webServer,proxy:t.infrastructure.compute.proxy?{engine:t.infrastructure.compute.proxy.engine,onDemandTls:t.infrastructure.compute.proxy.onDemandTls,cdn:!!t.infrastructure.compute.proxy.cdn}:void 0,managedServices:e,sshKeys:gc($i(t)).map((n)=>({name:n.name,type:n.type,fingerprint:n.fingerprint,added:n.added}))}:void 0,sites:Object.fromEntries(Object.entries(t.sites??{}).map(([n,r])=>[n,{domain:r.domain,path:r.path,type:r.type,deploy:r.deploy,root:r.root,port:r.port,ssl:r.ssl}]))}}function iE(t){return[{id:"status",label:"Refresh Cloud Status",description:"Runs the local ts-cloud status checks against configured providers.",command:["status","--env",t],mutates:!1},{id:"doctor",label:"Run Doctor",description:"Checks local tooling, credentials, and provider access.",command:["doctor"],mutates:!1},{id:"security-scan",label:"Security Scan",description:"Runs the pre-deploy scanner from this checkout.",command:["deploy:security-scan","--source",".","--fail-on","critical"],mutates:!1},{id:"deploy",label:"Deploy Environment",description:"Deploys the selected environment from the local checkout.",command:["deploy","--env",t,"--yes"],mutates:!0,confirm:"deploy"}]}function YP(t,e){return iE(e).find((n)=>n.id===t)}function AR(t){if(t.length<=RR)return t;return`${t.slice(0,RR)}
477
477
 
478
- [output truncated]`}async function DR(t,e,n){let r=t.getReader(),i=new TextDecoder,c="";while(!0){let{done:a,value:l}=await r.read();if(a)break;let o=i.decode(l,{stream:!0});if(c+=o,o)n?.(e,o)}let d=i.decode();if(d)c+=d,n?.(e,d);return c}async function Vl(t,e){let n=Bun.spawn([process.execPath,e.cliEntry,...t.command],{cwd:e.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,...e.env}}),r=()=>{try{n.kill()}catch{}};if(e.signal?.aborted)r();else e.signal?.addEventListener("abort",r,{once:!0});try{let[i,c,d]=await Promise.all([DR(n.stdout,"stdout",e.onOutput),DR(n.stderr,"stderr",e.onOutput),n.exited]);return{action:t.id,command:["cloud",...t.command].join(" "),exitCode:d,ok:d===0,stdout:AR(i),stderr:AR(c)}}finally{e.signal?.removeEventListener("abort",r)}}function XP(){return Object.entries(process.env).filter(([t,e])=>!!e&&e.length>=8&&/(?:secret|token|password|passwd|private|credential|api.?key|access.?key)/i.test(t)).map(([,t])=>t)}var KP=new Set(["/server/sites","/server/deployments","/server/logs","/integrations","/applications/new","/applications/compose","/operations/queue","/operations/previews","/operations/releases","/operations/workloads","/operations/observability","/operations/alerts","/operations/jobs","/data/backups","/account/security","/security","/access-denied"]);function pP(t){let e=uc(t);if(e&&e!==".html")return!1;let n=t.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/")return!1;return!KP.has(n)}var mP={"/":"runtime:read","/server/activity":"audit:read","/server/sites":"project:read","/server/deployments":"deployments:read","/server/logs":"runtime:logs","/server/metrics":"runtime:read","/server/services":"runtime:read","/data/backups":"backups:read","/data/volumes":"data:read","/server/fleet":"fleet:read","/server/capacity":"fleet:read","/server/actions":"runtime:restart","/server/database":"data:read","/server/firewall":"fleet:read","/infrastructure/topology":"fleet:read","/server/security":"security:read","/security":"security:read","/integrations":"sources:read","/applications/new":"applications:read","/applications/compose":"applications:read","/operations/queue":"deployments:read","/operations/previews":"deployments:read","/operations/releases":"deployments:read","/operations/regions":"deployments:read","/operations/maintenance":"deployments:read","/operations/workloads":"runtime:read","/operations/observability":"runtime:logs","/operations/alerts":"runtime:read","/operations/jobs":"automation:read","/operations/configuration":"config:read","/server/ssh-keys":"fleet:read","/server/terminal":"runtime:terminal","/server/team":"users:read","/account/security":"project:read","/account/automation":"users:read","/serverless":"project:read","/serverless/deployments":"deployments:read","/serverless/logs":"runtime:logs","/serverless/metrics":"runtime:read","/serverless/traces":"runtime:read","/serverless/functions":"config:read","/serverless/queues":"data:read","/serverless/data":"data:read","/serverless/assets":"project:read","/serverless/secrets":"secrets:read","/serverless/firewall":"fleet:read","/serverless/alarms":"runtime:read","/serverless/cost":"project:read"};function yR(t,e){if(e.role==="admin")return!0;let n=uc(t);if(n&&n!==".html")return!0;if(e.organizationSource==="legacy")return!pP(t);let r=t.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/access-denied")return!0;let i=mP[r];return!!i&&!!e.capabilities?.includes(i)}function qP(t,e){let n=decodeURIComponent(e).replace(/^\/+/,""),i=wP(n===""?"index.html":n);if(i.startsWith("..")||i.includes("/../"))return null;let c=At(t,i);if(Tn(c)&&!nE(c).isDirectory())return c;if(!uc(c)&&Tn(`${c}.html`))return`${c}.html`;if(!uc(c)&&Tn(At(c,"index.html")))return At(c,"index.html");return null}async function PR(t,e){let n=qP(t,e);if(!n){let c=At(t,"404.html");if(Tn(c))return new Response(await ln(c),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return Eo("Not found",404)}if(nE(n).isDirectory())return Eo("Not found",404);let r=await ln(n),i=OP[uc(n)]??"application/octet-stream";return new Response(r,{headers:{"content-type":i}})}var _o=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],$R=new WeakMap;async function vR(t){let e=$R.get(t);if(e)return e;let n=await import("./chunk-b9qbp8j1.js"),r=new n.SpendStore(t),i={store:r,service:new n.SpendService(r),gate:new n.SpendGate(t)};return $R.set(t,i),i}async function Sj(t={}){CP();let e=t.cwd??process.cwd(),n=t.host??$P,r=t.port??vP,i=t.cliEntry??process.argv[1];if(t.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await jP(e);let c=t.config??await $S(),d=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,a=re(c);if(d&&a&&!a.password)a.password=d;let l=c.infrastructure?.compute?.managedServices?.vitess;if(d&&l&&typeof l==="object"&&!l.password)l.password=d;let o=zf(e,c);if(o.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${o.reconciliation.failed} orphaned operation(s) as failed after restart.`);let u=Object.keys(c.environments??{}),f=WP(c,t.environment),R=HP(e),E=await br(c,f),y=new Map([[f,E]]),$=new Map([[f,Date.now()]]),C=new Map([[f,Date.now()]]),J=new Map,H=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),O=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),Y=On(c)!=="serverless",dt=(S)=>{let x=y.get(S);if(x&&!ER($.get(S),Date.now(),H))return Promise.resolve(x);let Z=J.get(S);if(Z)return Z;let V=!Y||ER(C.get(S),Date.now(),O),tt=br(c,S,{includeSiteHealth:V}).then((_t)=>{let w=y.get(S),ce=V?_t:MP(w,_t);if(y.set(S,ce),$.set(S,Date.now()),V)C.set(S,Date.now());if(w?._serverReachable!==ce._serverReachable||w?._metricsStatus!==ce._metricsStatus||(w?.sitesDetail?.length??0)!==(ce.sitesDetail?.length??0))Le();return ce}).finally(()=>J.delete(S));return J.set(S,tt),tt},m=pR(e),Ut=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(t.box&&Ut!=="0"&&(Ut==="1"||!c.cloud?.attachTo)){let S=!1,x=Date.now()+300000,Z=async()=>{if(S)return;S=!0;try{let tt=Date.now(),_t=tt>=x;if(_t)x=tt+300000;let w=o.environments.get(f);await Ll({controlPlane:o.store,projectId:o.project.id,environmentId:w?.id,config:c,environment:f,force:!0,lightweight:!0,includeSiteHealth:_t})}catch(tt){if(t.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${tt instanceof Error?tt.message:String(tt)}`)}finally{S=!1}};Z(),setInterval(()=>void Z(),60000).unref?.()}let Q=new Map,rt=new Map,Dt=new Set,Ke=0;function bn(S,x){if(S.role==="admin"&&!o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`))return S;let Z=o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`),V=Z?o.store.getMembershipForActor(o.organization.id,Z.id):void 0;if(!V||V.status!=="active")return{...S,role:"member",sites:{},capabilities:[]};let tt=o.store.listGrants(V.id),_t=o.store.resolveAuthorizationTarget(o.organization.id,V.scope)??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id}),w=lc({membership:V,grants:tt,target:_t});if(V.roleTemplate==="owner"||V.roleTemplate==="admin")return{...S,role:"admin",sites:{},organizationRole:V.roleTemplate,organizationSource:V.source,capabilities:w};let ce=o.environments.get(x),Lt={};for(let it of o.store.listResources(o.project.id,ce?.id).filter((at)=>at.kind==="application")){let at=o.store.resolveAuthorizationTarget(o.organization.id,{type:"resource",id:it.id});if(!at||!Ne({membership:V,grants:tt,capability:"project:read",target:at}).allowed)continue;Lt[it.slug]=Ne({membership:V,grants:tt,capability:"config:write",target:at}).allowed?"owner":"collaborator"}return{...S,role:"member",sites:Lt,organizationRole:V.roleTemplate,organizationSource:V.source,capabilities:w}}function Le(){Ke+=1,Q.clear();for(let S of Dt)Wr(S,{recursive:!0,force:!0});Dt.clear()}let pe=(S,x)=>`${x}:${S.role==="admin"?"admin":`member:${Object.entries(S.sites).sort(([Z],[V])=>Z.localeCompare(V)).map(([Z,V])=>`${Z}=${V}`).join(",")}`}:${[...S.capabilities??[]].sort().join(",")}`;async function me(S,x){let Z=bn(S,x),V=pe(Z,x),tt=Q.get(V);if(tt)return tt;let _t=rt.get(V);if(_t)return _t;let w=Ke,ce=(async()=>{let Lt=y.get(x)??await br(c,x);y.set(x,Lt);let it={...yl(Lt,{user:Z,slug:c.project.slug}),viewer:{role:Z.role,organizationRole:Z.organizationRole,organizationSource:Z.organizationSource,capabilities:Z.capabilities??[]}},at=await GP(e,it);if(at&&w!==Ke)return Wr(at,{recursive:!0,force:!0}),m?.uiRoot;if(at)Dt.add(at);let pt=at??m?.uiRoot;if(pt)Q.set(V,pt);return pt})();rt.set(V,ce);try{return await ce}finally{rt.delete(V)}}let qe=await me({username:"",passwordHash:"",role:"admin",sites:{}},f);if(!qe)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let P=new WeakMap,b=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",N=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(N&&t.box)throw Error("TS_CLOUD_DASHBOARD_AUTH=0 is refused in box mode: the dashboard is internet-facing there, and disabling auth would expose a root shell.");let G=!N,vt=mf(e),jt=G?n_(e,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,F=new Tc(o.store,{encryptionKey:Gn(e)}),gt=new jc(o.store),ot=new pi(o.store),q=new No(o.store,{encryptionKey:Gn(e)}),ie=new Jo(o.store),Ur=new bo(o.store,{cwd:e}),tn=new zo(o.store,{encryptionKey:Gn(e)}),yt=new Ot(o.store,{workerId:`dashboard:${process.pid}`}),kt=new Aa(o.store),gn=new Ba(o.store,Gn(e)),Wn=new CR(o.store),hc=new Zc(kt,yt,gn),Un=c.project?.region??"us-east-1",xl=Gn(e),we=new bR(Wn,{encryptionKey:xl,backends:[new OR(o.store,xl),new JR(new cc(Un),Un),new BR(new kR(Un),Un),new zR]});await WR(we,o,c);let Io=new Er(Un),cE={aws_rds:new Da(new Ca(Io)),aws_aurora:new ya(new Oa(Io)),aws_elasticache:new Pa(new Ja(new Hi(Un))),server:new $a(new pr),container:new va(new pr)},Ml=(S)=>cE[S.provider],Ft=new Ra(o.store),ir=new Mc(Ft,yt),Ql=new Ia(gn),dE={managed_database:new wa(kt,Io),logical_database:new Wa(kt,gn),volume:new ja,files:new ba(e),control_plane:new La(o.store,e),infrastructure:new Va(new ji(Un))},oE=(S)=>dE[S.resourceKind],aE=(S)=>S.provider==="aws_backup"?void 0:Ql,wo=new xR(o.store),Ao=[new VR,new NR(de(e,"volumes"))],un=new LR(wo,Ao,yt),vi=new Bs(o.store),en=new zs(vi,[new Zi("aws"),new Zi("hetzner"),new Zi("ssh")],yt),jn=new Ls(o.store),Gl=new Fs(jn,vi),cr=new Ms(o.store),Zl=new Qs(cr,yt),hn=new Ws(o.store),Do=new Us(hn,yt),Yl=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((S)=>new Hs(S,o.store,o.project.id,o.organization.id)),Xt=new ha(o.store),Xl=new ga(Xt,{queue:yt}),Ht=new Oc(o.store),Hn=new Cc(o.store),Oe=new lr(o.store),nt=new QR(o.store,{encryptionKey:Gn(e)}),sE=()=>vR(o.store);for(let S of o.environments.values())la(Xt,c,{organization:o.organization,project:o.project,environment:S,resources:o.store.listResources(o.project.id,S.id)});let Je=new GR(nt,{emailImpl:async(S)=>{let{email:x}=await import("./chunk-c1vcdgvr.js");return x.send(S)}}),Kl=async(S)=>{let x=KR(nt,o.project.id,S),Z=[];for(let V of x.filter((tt)=>tt.notify&&tt.alert))Z.push(...await Je.deliverAll(Je.enqueue(o.organization.id,V.alert,V.transition)));return Z.push(...await Je.deliverAll(Je.enqueueRemindersAndEscalations(o.organization.id,nt.listAlerts(o.project.id,{environmentId:S,states:["firing"]})))),Z.push(...await Je.retryDue()),{evaluations:x,deliveries:Z}},yo=!1,lE=async()=>{if(yo)return;yo=!0;try{for(let S of o.environments.values())for(let x of nt.listHealthChecks(o.project.id,S.id).filter((Z)=>Z.enabled)){let Z=nt.listHealthResults(x.id,1)[0];if(Z&&Date.now()-new Date(Z.checkedAt).getTime()<x.intervalSeconds*1000)continue;let V=await new yi(nt).runAndEvaluate(x);for(let tt of V.evaluations.filter((_t)=>_t.notify&&_t.alert))await Je.deliverAll(Je.enqueue(o.organization.id,tt.alert,tt.transition))}}finally{yo=!1}},pl=setInterval(()=>{for(let S of o.environments.values())Kl(S.id).catch((x)=>console.error("ts-cloud alert evaluation failed:",x))},60000);pl.unref?.();let ml=setInterval(()=>{lE().catch((S)=>console.error("ts-cloud health check evaluation failed:",S))},30000);ml.unref?.();let ql=setInterval(()=>{try{Xl.tick()}catch(S){console.error("ts-cloud scheduled job evaluation failed:",S)}},30000);ql.unref?.();let tg=setInterval(()=>{try{ir.enqueueDue(),ir.enqueueRetention()}catch(S){console.error("ts-cloud backup policy evaluation failed:",S)}},30000);tg.unref?.(),Ht.cleanup();let eg=setInterval(()=>{try{Ht.cleanup()}catch(S){console.error("ts-cloud preview cleanup failed:",S)}},3600000);eg.unref?.();let gE=t.queueWorker??!0,uE=XP(),hE=async(S,x)=>{let V=(S.environmentId?o.store.listEnvironments(S.projectId).find((tt)=>tt.id===S.environmentId):void 0)?.slug??String(f);if(x.kind==="dashboard_operation"&&x.operationId){let tt=y.get(V)??E,_t=Dl(x.operationId,c,tt);if(!_t||_t.danger||!["scheduler","backup","worker"].includes(_t.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let w=await ao(c,V,_t);return{ok:w.ok,stdout:w.stdout,stderr:w.stderr??w.error,retryable:/temporar|unavailable|timeout|network/i.test(w.stderr??w.error??""),output:{command:w.command??null,operation:w.operation}}}if(x.kind==="serverless_scheduler"){let tt=await Wl(c,V,"run");return{ok:tt.ok,stdout:tt.stdout,stderr:tt.error,retryable:/temporar|unavailable|timeout|network/i.test(tt.error??""),output:{command:tt.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${x.kind}.`}},Sc=gE?new UR(yt,{...MR({store:o.store,execute:async(S,x)=>{let Z=x.operation.input&&typeof x.operation.input==="object"&&!Array.isArray(x.operation.input)?x.operation.input:{},V=Z.source&&typeof Z.source==="object"?Z.source:void 0,tt=e,_t,w,ce;try{if(V?.bindingId&&V?.connectionId&&V?.commitSha){let it=q.getBinding(String(V.bindingId)),at=q.getConnection(String(V.connectionId));if(!it||!at||it.connectionId!==at.id)throw Error("Queued source binding is no longer available");let Zt=(it.repositoryId?q.getRepository(it.repositoryId):q.listRepositories(at.id).find((Lr)=>Lr.fullName.toLowerCase()===it.repositoryFullName.toLowerCase()))?.cloneUrl;if(!Zt&&at.provider==="generic_ssh")Zt=`git@${new URL(at.host).hostname}:${it.repositoryFullName}.git`;if(!Zt)Zt=new URL(`/${it.repositoryFullName}.git`,at.host.endsWith("/")?at.host:`${at.host}/`).href;let U=it.deployKeyId?q.getDeployKey(it.deployKeyId):void 0,Ct=U&&it.deployKeyId?{...U,privateKey:q.getDeployPrivateKey(it.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(at.provider)&&S.target.previewId){let Lr=xn(at,q.getCredential(at.id)),z=Ht.previews.getInstance(S.target.previewId);ce=async(Be,Ic)=>{try{await Lr.setCommitStatus(it.repositoryFullName,String(V.commitSha),{state:Be,url:z?.url,description:Ic})}catch(Fr){x.log(`Could not publish source status: ${Fr instanceof Error?Fr.message:String(Fr)}`,{stream:"stderr"})}},await ce("pending",`Preview deployment started for ${String(V.commitSha).slice(0,12)}`)}_t=Nl(At(Ro(),"ts-cloud-queued-source-")),x.log(`Checking out immutable source commit ${V.commitSha}.`,{stream:"system"}),tt=(await Qo({remote:Zt,binding:it,destination:At(_t,"checkout"),ref:String(V.branch??it.defaultBranch),commitSha:String(V.commitSha)},{credential:q.getCredential(at.id),deployKey:Ct})).directory}if(x.operation.kind!=="preview.destroy"){let it=S.target.previewId?Ht.previews.getInstance(S.target.previewId):void 0,at=it?Ht.previews.getDefinition(it.definitionId):void 0,pt=x.operation.resourceId?o.store.getResource(x.operation.resourceId):void 0;if(w=await we.resolve({projectId:o.project.id,environmentId:x.operation.environmentId,resourceId:x.operation.resourceId,functionId:pt?.kind==="function"?pt.id:void 0,previewId:it?.id,trustedPreview:!!it&&!it.fork,allowedPreviewSecrets:at?.inheritedSecrets}),w.warnings.some((Zt)=>Zt.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${w.warnings.filter((Zt)=>Zt.code==="missing_required").map((Zt)=>Zt.key).join(", ")}`);if(x.operation.resourceId)for(let Zt of Object.values(w.entries))Wn.setDependency({entryId:Zt.id,resourceId:x.operation.resourceId,injectionTarget:"environment",required:Zt.required,requiresRedeploy:!0});x.log(`Resolved configuration ${w.configurationHash.slice(0,18)} for ${Object.keys(w.values).length} keys.`,{stream:"system"})}let Lt=await Vl(S,{cwd:tt,cliEntry:i,signal:x.signal,env:w?.values,onOutput:(it,at)=>x.log(at,{stream:it,step:"execute",secrets:[...uE,...Object.entries(w?.entries??{}).filter(([,pt])=>pt.kind==="secret").map(([pt])=>w.values[pt]).filter(Boolean)]})});if(Lt.ok&&x.operation.resourceId&&w)for(let it of Object.values(w.entries))Wn.setDependency({entryId:it.id,resourceId:x.operation.resourceId,injectionTarget:"environment",required:it.required,requiresRedeploy:!1,lastDeployedVersion:it.version});return await ce?.(Lt.ok?"success":"failure",Lt.ok?`Preview is ready at ${String(V?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(V?.commitSha).slice(0,12)}`),Lt}catch(Lt){throw await ce?.("error",`Preview deployment could not complete at ${String(V?.commitSha).slice(0,12)}`),Lt}finally{if(_t)Wr(_t,{recursive:!0,force:!0})}}}),...Cu({store:Xt,executor:hE}),...Fu({store:kt,secrets:gn,resolveAdapter:Ml}),...CS(vi,en.drivers),...XS(cr,[new Gs("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...VS({store:hn,cleanup:Yl}),...FR(wo,Ao),...Uu({store:Ft,queue:yt,resolveSource:oE,resolveDestination:aE,validateHealth:async(S,x)=>{if(!S.healthCheckId)return{healthy:!0,mode:"adapter"};let Z=nt.getHealthCheck(S.healthCheckId);if(!Z||Z.projectId!==S.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let V=await new yi(nt).runAndEvaluate(Z);return{healthy:V.result.status==="healthy",healthCheckId:Z.id,healthResultId:V.result.id,target:x}}}),...Bg({store:o.store,resolveDriver:t.releaseDriver??((S)=>({name:`${o.store.getResource(S.resourceId)?.provider??"provider"} release driver`,capability:()=>({strategy:S.strategy,supported:!1,explanation:"This dashboard process has no immutable activation driver configured for the target provider.",capacityMultiplier:1,costImpact:"none",rollback:"The previous release remains preserved; configure a release driver before retrying."}),activate:async()=>{throw Error("Immutable activation driver is not configured")},rollback:async()=>{throw Error("Immutable rollback driver is not configured")}})),resolveHealthGate:async(S,x)=>{let Z=nt.listHealthChecks(x.projectId,x.environmentId).find((tt)=>tt.enabled&&tt.name===S&&(!tt.resourceId||tt.resourceId===x.resourceId));if(!Z)return{healthy:!1,message:`Named health gate ${S} was not found for this release.`};let V=await new yi(nt).runAndEvaluate(Z);return{healthy:V.result.status==="healthy",evidence:{healthCheckId:Z.id,healthResultId:V.result.id,status:V.result.status,timings:V.result.timings},message:V.result.message}}})},{parallelism:t.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(S)=>console.error("ts-cloud deployment queue worker failed:",S)}):void 0;if($f(o),Qd(ot,Ye(o,String(f)),E),jt)Zd(o,jt.users),c_(F,o,jt.users);let Bt=r_({cwd:e,enabled:G,secret:vt,authentication:F,authorization:{store:o.store,organizationId:o.organization.id,projectId:o.project.id,defaultEnvironment:String(f)}}),Vt=new ms,ng=setInterval(()=>Vt.sweep(),60000);ng.unref?.();let fc=new rc,Po=new rc(3,900000,900000),_c=new rc(8,900000,900000),rg=setInterval(()=>fc.prune(),300000),ig=setInterval(()=>Po.prune(),300000),cg=setInterval(()=>_c.prune(),300000);if(rg.unref?.(),ig.unref?.(),cg.unref?.(),G){if(jt?.generated)console.warn(`
478
+ [output truncated]`}async function DR(t,e,n){let r=t.getReader(),i=new TextDecoder,c="";while(!0){let{done:a,value:l}=await r.read();if(a)break;let o=i.decode(l,{stream:!0});if(c+=o,o)n?.(e,o)}let d=i.decode();if(d)c+=d,n?.(e,d);return c}async function Vl(t,e){let n=Bun.spawn([process.execPath,e.cliEntry,...t.command],{cwd:e.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,...e.env}}),r=()=>{try{n.kill()}catch{}};if(e.signal?.aborted)r();else e.signal?.addEventListener("abort",r,{once:!0});try{let[i,c,d]=await Promise.all([DR(n.stdout,"stdout",e.onOutput),DR(n.stderr,"stderr",e.onOutput),n.exited]);return{action:t.id,command:["cloud",...t.command].join(" "),exitCode:d,ok:d===0,stdout:AR(i),stderr:AR(c)}}finally{e.signal?.removeEventListener("abort",r)}}function XP(){return Object.entries(process.env).filter(([t,e])=>!!e&&e.length>=8&&/(?:secret|token|password|passwd|private|credential|api.?key|access.?key)/i.test(t)).map(([,t])=>t)}var KP=new Set(["/server/sites","/server/deployments","/server/logs","/integrations","/applications/new","/applications/compose","/operations/queue","/operations/previews","/operations/releases","/operations/workloads","/operations/observability","/operations/alerts","/operations/jobs","/data/backups","/account/security","/security","/access-denied"]);function pP(t){let e=uc(t);if(e&&e!==".html")return!1;let n=t.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/")return!1;return!KP.has(n)}var mP={"/":"runtime:read","/server/activity":"audit:read","/server/sites":"project:read","/server/deployments":"deployments:read","/server/logs":"runtime:logs","/server/metrics":"runtime:read","/server/services":"runtime:read","/data/backups":"backups:read","/data/volumes":"data:read","/server/fleet":"fleet:read","/server/capacity":"fleet:read","/server/actions":"runtime:restart","/server/database":"data:read","/server/firewall":"fleet:read","/infrastructure/topology":"fleet:read","/server/security":"security:read","/security":"security:read","/integrations":"sources:read","/applications/new":"applications:read","/applications/compose":"applications:read","/operations/queue":"deployments:read","/operations/previews":"deployments:read","/operations/releases":"deployments:read","/operations/regions":"deployments:read","/operations/maintenance":"deployments:read","/operations/workloads":"runtime:read","/operations/observability":"runtime:logs","/operations/alerts":"runtime:read","/operations/jobs":"automation:read","/operations/configuration":"config:read","/server/ssh-keys":"fleet:read","/server/terminal":"runtime:terminal","/server/team":"users:read","/account/security":"project:read","/account/automation":"users:read","/serverless":"project:read","/serverless/deployments":"deployments:read","/serverless/logs":"runtime:logs","/serverless/metrics":"runtime:read","/serverless/traces":"runtime:read","/serverless/functions":"config:read","/serverless/queues":"data:read","/serverless/data":"data:read","/serverless/assets":"project:read","/serverless/secrets":"secrets:read","/serverless/firewall":"fleet:read","/serverless/alarms":"runtime:read","/serverless/cost":"project:read"};function yR(t,e){if(e.role==="admin")return!0;let n=uc(t);if(n&&n!==".html")return!0;if(e.organizationSource==="legacy")return!pP(t);let r=t.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/access-denied")return!0;let i=mP[r];return!!i&&!!e.capabilities?.includes(i)}function qP(t,e){let n=decodeURIComponent(e).replace(/^\/+/,""),i=wP(n===""?"index.html":n);if(i.startsWith("..")||i.includes("/../"))return null;let c=At(t,i);if(Tn(c)&&!nE(c).isDirectory())return c;if(!uc(c)&&Tn(`${c}.html`))return`${c}.html`;if(!uc(c)&&Tn(At(c,"index.html")))return At(c,"index.html");return null}async function PR(t,e){let n=qP(t,e);if(!n){let c=At(t,"404.html");if(Tn(c))return new Response(await ln(c),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return Eo("Not found",404)}if(nE(n).isDirectory())return Eo("Not found",404);let r=await ln(n),i=OP[uc(n)]??"application/octet-stream";return new Response(r,{headers:{"content-type":i}})}var _o=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],$R=new WeakMap;async function vR(t){let e=$R.get(t);if(e)return e;let n=await import("./chunk-qk9qgepa.js"),r=new n.SpendStore(t),i={store:r,service:new n.SpendService(r),gate:new n.SpendGate(t)};return $R.set(t,i),i}async function Sj(t={}){CP();let e=t.cwd??process.cwd(),n=t.host??$P,r=t.port??vP,i=t.cliEntry??process.argv[1];if(t.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await jP(e);let c=t.config??await $S(),d=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,a=re(c);if(d&&a&&!a.password)a.password=d;let l=c.infrastructure?.compute?.managedServices?.vitess;if(d&&l&&typeof l==="object"&&!l.password)l.password=d;let o=zf(e,c);if(o.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${o.reconciliation.failed} orphaned operation(s) as failed after restart.`);let u=Object.keys(c.environments??{}),f=WP(c,t.environment),R=HP(e),E=await br(c,f),y=new Map([[f,E]]),$=new Map([[f,Date.now()]]),C=new Map([[f,Date.now()]]),J=new Map,H=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),O=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),Y=On(c)!=="serverless",dt=(S)=>{let x=y.get(S);if(x&&!ER($.get(S),Date.now(),H))return Promise.resolve(x);let Z=J.get(S);if(Z)return Z;let V=!Y||ER(C.get(S),Date.now(),O),tt=br(c,S,{includeSiteHealth:V}).then((_t)=>{let w=y.get(S),ce=V?_t:MP(w,_t);if(y.set(S,ce),$.set(S,Date.now()),V)C.set(S,Date.now());if(w?._serverReachable!==ce._serverReachable||w?._metricsStatus!==ce._metricsStatus||(w?.sitesDetail?.length??0)!==(ce.sitesDetail?.length??0))Le();return ce}).finally(()=>J.delete(S));return J.set(S,tt),tt},m=pR(e),Ut=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(t.box&&Ut!=="0"&&(Ut==="1"||!c.cloud?.attachTo)){let S=!1,x=Date.now()+300000,Z=async()=>{if(S)return;S=!0;try{let tt=Date.now(),_t=tt>=x;if(_t)x=tt+300000;let w=o.environments.get(f);await Ll({controlPlane:o.store,projectId:o.project.id,environmentId:w?.id,config:c,environment:f,force:!0,lightweight:!0,includeSiteHealth:_t})}catch(tt){if(t.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${tt instanceof Error?tt.message:String(tt)}`)}finally{S=!1}};Z(),setInterval(()=>void Z(),60000).unref?.()}let Q=new Map,rt=new Map,Dt=new Set,Ke=0;function bn(S,x){if(S.role==="admin"&&!o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`))return S;let Z=o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`),V=Z?o.store.getMembershipForActor(o.organization.id,Z.id):void 0;if(!V||V.status!=="active")return{...S,role:"member",sites:{},capabilities:[]};let tt=o.store.listGrants(V.id),_t=o.store.resolveAuthorizationTarget(o.organization.id,V.scope)??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id}),w=lc({membership:V,grants:tt,target:_t});if(V.roleTemplate==="owner"||V.roleTemplate==="admin")return{...S,role:"admin",sites:{},organizationRole:V.roleTemplate,organizationSource:V.source,capabilities:w};let ce=o.environments.get(x),Lt={};for(let it of o.store.listResources(o.project.id,ce?.id).filter((at)=>at.kind==="application")){let at=o.store.resolveAuthorizationTarget(o.organization.id,{type:"resource",id:it.id});if(!at||!Ne({membership:V,grants:tt,capability:"project:read",target:at}).allowed)continue;Lt[it.slug]=Ne({membership:V,grants:tt,capability:"config:write",target:at}).allowed?"owner":"collaborator"}return{...S,role:"member",sites:Lt,organizationRole:V.roleTemplate,organizationSource:V.source,capabilities:w}}function Le(){Ke+=1,Q.clear();for(let S of Dt)Wr(S,{recursive:!0,force:!0});Dt.clear()}let pe=(S,x)=>`${x}:${S.role==="admin"?"admin":`member:${Object.entries(S.sites).sort(([Z],[V])=>Z.localeCompare(V)).map(([Z,V])=>`${Z}=${V}`).join(",")}`}:${[...S.capabilities??[]].sort().join(",")}`;async function me(S,x){let Z=bn(S,x),V=pe(Z,x),tt=Q.get(V);if(tt)return tt;let _t=rt.get(V);if(_t)return _t;let w=Ke,ce=(async()=>{let Lt=y.get(x)??await br(c,x);y.set(x,Lt);let it={...yl(Lt,{user:Z,slug:c.project.slug}),viewer:{role:Z.role,organizationRole:Z.organizationRole,organizationSource:Z.organizationSource,capabilities:Z.capabilities??[]}},at=await GP(e,it);if(at&&w!==Ke)return Wr(at,{recursive:!0,force:!0}),m?.uiRoot;if(at)Dt.add(at);let pt=at??m?.uiRoot;if(pt)Q.set(V,pt);return pt})();rt.set(V,ce);try{return await ce}finally{rt.delete(V)}}let qe=await me({username:"",passwordHash:"",role:"admin",sites:{}},f);if(!qe)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let P=new WeakMap,b=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",N=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(N&&t.box)throw Error("TS_CLOUD_DASHBOARD_AUTH=0 is refused in box mode: the dashboard is internet-facing there, and disabling auth would expose a root shell.");let G=!N,vt=mf(e),jt=G?n_(e,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,F=new Tc(o.store,{encryptionKey:Gn(e)}),gt=new jc(o.store),ot=new pi(o.store),q=new No(o.store,{encryptionKey:Gn(e)}),ie=new Jo(o.store),Ur=new bo(o.store,{cwd:e}),tn=new zo(o.store,{encryptionKey:Gn(e)}),yt=new Ot(o.store,{workerId:`dashboard:${process.pid}`}),kt=new Aa(o.store),gn=new Ba(o.store,Gn(e)),Wn=new CR(o.store),hc=new Zc(kt,yt,gn),Un=c.project?.region??"us-east-1",xl=Gn(e),we=new bR(Wn,{encryptionKey:xl,backends:[new OR(o.store,xl),new JR(new cc(Un),Un),new BR(new kR(Un),Un),new zR]});await WR(we,o,c);let Io=new Er(Un),cE={aws_rds:new Da(new Ca(Io)),aws_aurora:new ya(new Oa(Io)),aws_elasticache:new Pa(new Ja(new Hi(Un))),server:new $a(new pr),container:new va(new pr)},Ml=(S)=>cE[S.provider],Ft=new Ra(o.store),ir=new Mc(Ft,yt),Ql=new Ia(gn),dE={managed_database:new wa(kt,Io),logical_database:new Wa(kt,gn),volume:new ja,files:new ba(e),control_plane:new La(o.store,e),infrastructure:new Va(new ji(Un))},oE=(S)=>dE[S.resourceKind],aE=(S)=>S.provider==="aws_backup"?void 0:Ql,wo=new xR(o.store),Ao=[new VR,new NR(de(e,"volumes"))],un=new LR(wo,Ao,yt),vi=new Bs(o.store),en=new zs(vi,[new Zi("aws"),new Zi("hetzner"),new Zi("ssh")],yt),jn=new Ls(o.store),Gl=new Fs(jn,vi),cr=new Ms(o.store),Zl=new Qs(cr,yt),hn=new Ws(o.store),Do=new Us(hn,yt),Yl=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((S)=>new Hs(S,o.store,o.project.id,o.organization.id)),Xt=new ha(o.store),Xl=new ga(Xt,{queue:yt}),Ht=new Oc(o.store),Hn=new Cc(o.store),Oe=new lr(o.store),nt=new QR(o.store,{encryptionKey:Gn(e)}),sE=()=>vR(o.store);for(let S of o.environments.values())la(Xt,c,{organization:o.organization,project:o.project,environment:S,resources:o.store.listResources(o.project.id,S.id)});let Je=new GR(nt,{emailImpl:async(S)=>{let{email:x}=await import("./chunk-c1vcdgvr.js");return x.send(S)}}),Kl=async(S)=>{let x=KR(nt,o.project.id,S),Z=[];for(let V of x.filter((tt)=>tt.notify&&tt.alert))Z.push(...await Je.deliverAll(Je.enqueue(o.organization.id,V.alert,V.transition)));return Z.push(...await Je.deliverAll(Je.enqueueRemindersAndEscalations(o.organization.id,nt.listAlerts(o.project.id,{environmentId:S,states:["firing"]})))),Z.push(...await Je.retryDue()),{evaluations:x,deliveries:Z}},yo=!1,lE=async()=>{if(yo)return;yo=!0;try{for(let S of o.environments.values())for(let x of nt.listHealthChecks(o.project.id,S.id).filter((Z)=>Z.enabled)){let Z=nt.listHealthResults(x.id,1)[0];if(Z&&Date.now()-new Date(Z.checkedAt).getTime()<x.intervalSeconds*1000)continue;let V=await new yi(nt).runAndEvaluate(x);for(let tt of V.evaluations.filter((_t)=>_t.notify&&_t.alert))await Je.deliverAll(Je.enqueue(o.organization.id,tt.alert,tt.transition))}}finally{yo=!1}},pl=setInterval(()=>{for(let S of o.environments.values())Kl(S.id).catch((x)=>console.error("ts-cloud alert evaluation failed:",x))},60000);pl.unref?.();let ml=setInterval(()=>{lE().catch((S)=>console.error("ts-cloud health check evaluation failed:",S))},30000);ml.unref?.();let ql=setInterval(()=>{try{Xl.tick()}catch(S){console.error("ts-cloud scheduled job evaluation failed:",S)}},30000);ql.unref?.();let tg=setInterval(()=>{try{ir.enqueueDue(),ir.enqueueRetention()}catch(S){console.error("ts-cloud backup policy evaluation failed:",S)}},30000);tg.unref?.(),Ht.cleanup();let eg=setInterval(()=>{try{Ht.cleanup()}catch(S){console.error("ts-cloud preview cleanup failed:",S)}},3600000);eg.unref?.();let gE=t.queueWorker??!0,uE=XP(),hE=async(S,x)=>{let V=(S.environmentId?o.store.listEnvironments(S.projectId).find((tt)=>tt.id===S.environmentId):void 0)?.slug??String(f);if(x.kind==="dashboard_operation"&&x.operationId){let tt=y.get(V)??E,_t=Dl(x.operationId,c,tt);if(!_t||_t.danger||!["scheduler","backup","worker"].includes(_t.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let w=await ao(c,V,_t);return{ok:w.ok,stdout:w.stdout,stderr:w.stderr??w.error,retryable:/temporar|unavailable|timeout|network/i.test(w.stderr??w.error??""),output:{command:w.command??null,operation:w.operation}}}if(x.kind==="serverless_scheduler"){let tt=await Wl(c,V,"run");return{ok:tt.ok,stdout:tt.stdout,stderr:tt.error,retryable:/temporar|unavailable|timeout|network/i.test(tt.error??""),output:{command:tt.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${x.kind}.`}},Sc=gE?new UR(yt,{...MR({store:o.store,execute:async(S,x)=>{let Z=x.operation.input&&typeof x.operation.input==="object"&&!Array.isArray(x.operation.input)?x.operation.input:{},V=Z.source&&typeof Z.source==="object"?Z.source:void 0,tt=e,_t,w,ce;try{if(V?.bindingId&&V?.connectionId&&V?.commitSha){let it=q.getBinding(String(V.bindingId)),at=q.getConnection(String(V.connectionId));if(!it||!at||it.connectionId!==at.id)throw Error("Queued source binding is no longer available");let Zt=(it.repositoryId?q.getRepository(it.repositoryId):q.listRepositories(at.id).find((Lr)=>Lr.fullName.toLowerCase()===it.repositoryFullName.toLowerCase()))?.cloneUrl;if(!Zt&&at.provider==="generic_ssh")Zt=`git@${new URL(at.host).hostname}:${it.repositoryFullName}.git`;if(!Zt)Zt=new URL(`/${it.repositoryFullName}.git`,at.host.endsWith("/")?at.host:`${at.host}/`).href;let U=it.deployKeyId?q.getDeployKey(it.deployKeyId):void 0,Ct=U&&it.deployKeyId?{...U,privateKey:q.getDeployPrivateKey(it.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(at.provider)&&S.target.previewId){let Lr=xn(at,q.getCredential(at.id)),z=Ht.previews.getInstance(S.target.previewId);ce=async(Be,Ic)=>{try{await Lr.setCommitStatus(it.repositoryFullName,String(V.commitSha),{state:Be,url:z?.url,description:Ic})}catch(Fr){x.log(`Could not publish source status: ${Fr instanceof Error?Fr.message:String(Fr)}`,{stream:"stderr"})}},await ce("pending",`Preview deployment started for ${String(V.commitSha).slice(0,12)}`)}_t=Nl(At(Ro(),"ts-cloud-queued-source-")),x.log(`Checking out immutable source commit ${V.commitSha}.`,{stream:"system"}),tt=(await Qo({remote:Zt,binding:it,destination:At(_t,"checkout"),ref:String(V.branch??it.defaultBranch),commitSha:String(V.commitSha)},{credential:q.getCredential(at.id),deployKey:Ct})).directory}if(x.operation.kind!=="preview.destroy"){let it=S.target.previewId?Ht.previews.getInstance(S.target.previewId):void 0,at=it?Ht.previews.getDefinition(it.definitionId):void 0,pt=x.operation.resourceId?o.store.getResource(x.operation.resourceId):void 0;if(w=await we.resolve({projectId:o.project.id,environmentId:x.operation.environmentId,resourceId:x.operation.resourceId,functionId:pt?.kind==="function"?pt.id:void 0,previewId:it?.id,trustedPreview:!!it&&!it.fork,allowedPreviewSecrets:at?.inheritedSecrets}),w.warnings.some((Zt)=>Zt.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${w.warnings.filter((Zt)=>Zt.code==="missing_required").map((Zt)=>Zt.key).join(", ")}`);if(x.operation.resourceId)for(let Zt of Object.values(w.entries))Wn.setDependency({entryId:Zt.id,resourceId:x.operation.resourceId,injectionTarget:"environment",required:Zt.required,requiresRedeploy:!0});x.log(`Resolved configuration ${w.configurationHash.slice(0,18)} for ${Object.keys(w.values).length} keys.`,{stream:"system"})}let Lt=await Vl(S,{cwd:tt,cliEntry:i,signal:x.signal,env:w?.values,onOutput:(it,at)=>x.log(at,{stream:it,step:"execute",secrets:[...uE,...Object.entries(w?.entries??{}).filter(([,pt])=>pt.kind==="secret").map(([pt])=>w.values[pt]).filter(Boolean)]})});if(Lt.ok&&x.operation.resourceId&&w)for(let it of Object.values(w.entries))Wn.setDependency({entryId:it.id,resourceId:x.operation.resourceId,injectionTarget:"environment",required:it.required,requiresRedeploy:!1,lastDeployedVersion:it.version});return await ce?.(Lt.ok?"success":"failure",Lt.ok?`Preview is ready at ${String(V?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(V?.commitSha).slice(0,12)}`),Lt}catch(Lt){throw await ce?.("error",`Preview deployment could not complete at ${String(V?.commitSha).slice(0,12)}`),Lt}finally{if(_t)Wr(_t,{recursive:!0,force:!0})}}}),...Cu({store:Xt,executor:hE}),...Fu({store:kt,secrets:gn,resolveAdapter:Ml}),...CS(vi,en.drivers),...XS(cr,[new Gs("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...VS({store:hn,cleanup:Yl}),...FR(wo,Ao),...Uu({store:Ft,queue:yt,resolveSource:oE,resolveDestination:aE,validateHealth:async(S,x)=>{if(!S.healthCheckId)return{healthy:!0,mode:"adapter"};let Z=nt.getHealthCheck(S.healthCheckId);if(!Z||Z.projectId!==S.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let V=await new yi(nt).runAndEvaluate(Z);return{healthy:V.result.status==="healthy",healthCheckId:Z.id,healthResultId:V.result.id,target:x}}}),...Bg({store:o.store,resolveDriver:t.releaseDriver??((S)=>({name:`${o.store.getResource(S.resourceId)?.provider??"provider"} release driver`,capability:()=>({strategy:S.strategy,supported:!1,explanation:"This dashboard process has no immutable activation driver configured for the target provider.",capacityMultiplier:1,costImpact:"none",rollback:"The previous release remains preserved; configure a release driver before retrying."}),activate:async()=>{throw Error("Immutable activation driver is not configured")},rollback:async()=>{throw Error("Immutable rollback driver is not configured")}})),resolveHealthGate:async(S,x)=>{let Z=nt.listHealthChecks(x.projectId,x.environmentId).find((tt)=>tt.enabled&&tt.name===S&&(!tt.resourceId||tt.resourceId===x.resourceId));if(!Z)return{healthy:!1,message:`Named health gate ${S} was not found for this release.`};let V=await new yi(nt).runAndEvaluate(Z);return{healthy:V.result.status==="healthy",evidence:{healthCheckId:Z.id,healthResultId:V.result.id,status:V.result.status,timings:V.result.timings},message:V.result.message}}})},{parallelism:t.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(S)=>console.error("ts-cloud deployment queue worker failed:",S)}):void 0;if($f(o),Qd(ot,Ye(o,String(f)),E),jt)Zd(o,jt.users),c_(F,o,jt.users);let Bt=r_({cwd:e,enabled:G,secret:vt,authentication:F,authorization:{store:o.store,organizationId:o.organization.id,projectId:o.project.id,defaultEnvironment:String(f)}}),Vt=new ms,ng=setInterval(()=>Vt.sweep(),60000);ng.unref?.();let fc=new rc,Po=new rc(3,900000,900000),_c=new rc(8,900000,900000),rg=setInterval(()=>fc.prune(),300000),ig=setInterval(()=>Po.prune(),300000),cg=setInterval(()=>_c.prune(),300000);if(rg.unref?.(),ig.unref?.(),cg.unref?.(),G){if(jt?.generated)console.warn(`
479
479
  ts-cloud dashboard: created the first admin.
480
480
  username: ${jt.generated.username}
481
481
  password: ${jt.generated.password}
@@ -497,7 +497,7 @@ This link expires ${A.invitation.expiresAt} and can be used once.`});return h({i
497
497
 
498
498
  This replacement link expires ${_.invitation.expiresAt} and can be used once.`});return h({invitation:_.invitation,token:_.token,acceptUrl:I,delivered:A})}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Invitation could not be resent."},409)}}if(w.pathname==="/api/organization/memberships"&&S.method==="PATCH"){let s=await B(S),g=o.store.getMembership(String(s.id??"")),_=fo(s.roleTemplate),I=sc(s);if(!g||g.organizationId!==o.organization.id)return h({ok:!1,error:"Membership was not found."},404);if(!_||!I)return h({ok:!1,error:"Choose a valid role template and resource scope."},422);let A=X(z);if((g.roleTemplate==="owner"||_==="owner")&&(!Xe(String(s.password??""),z.passwordHash)||A.membership?.roleTemplate!=="owner"))return h({ok:!1,error:"Ownership changes require an owner to re-enter their password."},401);let D=o.store.resolveAuthorizationTarget(o.organization.id,I)??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id}),k=o.store.listGrants(g.id),W=lc({membership:g,grants:k,target:D}),T={...g,roleTemplate:_,scope:I},et=lc({membership:T,grants:k,target:D}),j={gained:et.filter((K)=>!W.includes(K)),lost:W.filter((K)=>!et.includes(K))};if(s.preview===!0)return h({membership:g,proposed:{roleTemplate:_,scope:I},accessDiff:j});if(String(s.confirm??"")!==g.id)return h({ok:!1,error:`Confirm this change with membership ID ${g.id}.`,accessDiff:j},409);try{return h({membership:o.store.updateMembership({id:g.id,roleTemplate:_,scope:I,actorId:A.actor?.id}),accessDiff:j})}catch(K){return h({ok:!1,error:K instanceof Error?K.message:"Membership could not be updated."},409)}}if(w.pathname==="/api/organization/memberships"&&S.method==="DELETE"){let s=await B(S),g=o.store.getMembership(String(s.id??""));if(!g||g.organizationId!==o.organization.id)return h({ok:!1,error:"Membership was not found."},404);if(String(s.confirm??"")!==g.id)return h({ok:!1,error:`Confirm removal with membership ID ${g.id}.`},409);let _=X(z);if(g.roleTemplate==="owner"&&(_.membership?.roleTemplate!=="owner"||!Xe(String(s.password??""),z.passwordHash)))return h({ok:!1,error:"Removing an owner requires an owner to re-enter their current password."},401);try{return h({membership:o.store.revokeMembership(g.id,_.actor?.id)})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Membership could not be removed."},409)}}if(w.pathname==="/api/organization/grants"&&S.method==="POST"){let s=await B(S),g=String(s.capability??""),_=s.effect==="deny"?"deny":s.effect==="allow"?"allow":void 0,I=sc(s),A=X(z);if(!_||!I||!Uc.includes(g))return h({ok:!1,error:"Choose a valid capability, effect, and resource scope."},422);try{return h({grant:o.store.upsertGrant({organizationId:o.organization.id,membershipId:String(s.membershipId??""),effect:_,capability:g,scope:I,actorId:A.actor?.id})},201)}catch(v){return h({ok:!1,error:v instanceof Error?v.message:"Grant could not be created."},422)}}if(w.pathname==="/api/organization/grants"&&S.method==="DELETE"){let s=await B(S),g=X(z),_=o.store.getGrant(String(s.id??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Grant was not found."},404);return h({ok:o.store.removeGrant(_.id,g.actor?.id)})}if(w.pathname==="/api/tags"&&S.method==="GET")return h({tags:o.store.listTags(o.project.id),assignments:o.store.listResourceTags(o.project.id)});if(w.pathname==="/api/tags"&&S.method==="POST"){let s=await B(S),g=o.store.upsertTag(o.project.id,String(s.name??""),String(s.color??"#5a8be0"));if(s.resourceId)o.store.assignTag(String(s.resourceId),g.id);return h({tag:g},201)}if(w.pathname==="/api/tags"&&S.method==="DELETE"){let s=await B(S);return o.store.removeTag(String(s.resourceId??""),String(s.tagId??"")),h({ok:!0})}if(w.pathname==="/"&&!yR(w.pathname,Be))return new Response(null,{status:302,headers:{location:`/server/sites?env=${encodeURIComponent(U)}`}});if(w.pathname==="/"&&Ct?.mode==="serverless")return new Response(null,{status:302,headers:{location:`/serverless?env=${encodeURIComponent(U)}`}});let Ic=E_(w.pathname);if(Ic)return new Response(null,{status:308,headers:{location:`${Ic}?env=${encodeURIComponent(U)}`}});if(w.pathname==="/api/env"&&S.method==="POST"){let s=await B(S),g=String(s.env??"");if(!u.includes(g))return h({ok:!1,error:`Unknown environment '${g}'.`,environments:u},404);return h({ok:!0,environment:g,environments:u,href:`?env=${encodeURIComponent(g)}`})}if(w.pathname==="/api/config"){let s={...ZP(c),environment:U,environments:u};return h(w_(s,Be))}if(w.pathname==="/api/ssh-keys"&&S.method==="GET")return h({configPath:R,keys:gc($i(c))});if(w.pathname==="/api/ssh-keys"&&S.method==="POST"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=await ln(R,"utf8"),_=$i(c),I=qR({configText:g,name:String(s.name??""),publicKey:String(s.publicKey??""),existingKeys:_});return await Tr(R,I),IR(c,[..._,{name:String(s.name??"").trim(),publicKey:String(s.publicKey??"").trim().replace(/\s+/g," ")}]),h({ok:!0,configPath:R,keys:gc($i(c))})}if(w.pathname==="/api/ssh-keys"&&S.method==="DELETE"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??w.searchParams.get("name")??""),_=await ln(R,"utf8"),I=$i(c),A=tE({configText:_,name:g,existingKeys:I});return await Tr(R,A),IR(c,I.filter((v)=>v.name!==g.trim())),h({ok:!0,configPath:R,keys:gc($i(c))})}if(w.pathname==="/api/firewall"&&S.method==="GET")return h({configPath:R,alwaysOpen:[22,80,443],ports:Fl(c)});if(w.pathname==="/api/firewall"&&S.method==="POST"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=Number(s.port);if(!ic(g))return h({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let _=Fl(c),I=await ln(R,"utf8");try{await Tr(R,k_(I,g,_))}catch(D){return h({ok:!1,error:D?.message??String(D)},422)}let A=zr([..._,g]);wR(c,A);let v=s.apply===!1?null:await nc(c,U,`ufw allow ${g}/tcp`).catch((D)=>({ok:!1,error:String(D?.message??D)}));return h({ok:!0,configPath:R,ports:A,apply:v})}if(w.pathname==="/api/firewall"&&S.method==="DELETE"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=Number(s.port??w.searchParams.get("port"));if(!ic(g))return h({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let _=Fl(c),I=await ln(R,"utf8");await Tr(R,C_(I,g,_));let A=zr(_.filter((D)=>D!==g));wR(c,A);let v=s.apply===!1?null:await nc(c,U,`ufw delete allow ${g}/tcp`).catch((D)=>({ok:!1,error:String(D?.message??D)}));return h({ok:!0,configPath:R,ports:A,apply:v})}if(w.pathname==="/api/sites"&&S.method==="POST"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??"").trim(),_=String(s.root??"").trim();if(!g||!_)return h({ok:!1,error:"Site name and root are required."},422);let I={deploy:s.deploy==="bucket"?"bucket":"server",root:_,path:String(s.path??"").trim()||void 0,domain:String(s.domain??"").trim()||void 0,build:String(s.build??"").trim()||void 0,start:String(s.start??"").trim()||void 0,port:s.port?Number(s.port):void 0,type:String(s.type??"").trim()||void 0};if(I.port!==void 0&&(!Number.isInteger(I.port)||I.port<1||I.port>65535))return h({ok:!1,error:"Port must be a number between 1 and 65535."},422);let A=await ln(R,"utf8"),v=K_({configText:A,name:g,root:I.root,domain:I.domain,path:I.path,deploy:I.deploy,build:I.build,start:I.start,port:I.port,type:I.type});return await Tr(R,v),LP(c,g,Object.fromEntries(Object.entries(I).filter(([,D])=>D!==void 0))),Ct=await br(c,U),y.set(U,Ct),h({ok:!0,configPath:R,site:g,data:Ct})}if(w.pathname==="/api/sites"&&S.method==="DELETE"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??w.searchParams.get("name")??"").trim();if(!g||!c.sites?.[g])return h({ok:!1,error:`Site '${g}' was not found.`},404);let _=await ln(R,"utf8");return await Tr(R,p_({configText:_,name:g})),delete c.sites[g],Ct=await br(c,U),y.set(U,Ct),h({ok:!0,configPath:R,site:g,data:Ct})}if(w.pathname==="/api/sites"&&S.method==="PATCH"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??"").trim(),_=c.sites?.[g];if(!g||!_)return h({ok:!1,error:`Site '${g}' was not found.`},404);if(Be.role==="member"){let v=y_(s);if(!v.ok)return h({ok:!1,error:v.error},403);let D=P_({siteName:g,body:s,sites:c.sites??{},ownSites:Object.keys(Be.sites)});if(!D.ok)return h({ok:!1,error:D.error},409)}if(s.port!==void 0&&s.port!==null&&s.port!==""&&(!Number.isInteger(Number(s.port))||Number(s.port)<1||Number(s.port)>65535))return h({ok:!1,error:"Port must be a number between 1 and 65535."},422);if(typeof s.domain==="string"&&s.domain.trim()&&!Ul(s.domain.trim()))return h({ok:!1,error:`Domain '${s.domain.trim()}' is not a valid hostname.`},422);let I=await ln(R,"utf8"),A=(v,D)=>{I=m_({configText:I,siteName:g,key:v,valueText:D})};if(s.ssl!==void 0)A("ssl",q_(s.ssl)),_.ssl=s.ssl;if(s.env!==void 0&&s.env&&typeof s.env==="object")A("env",eR(s.env)),_.env=s.env;if(s.aliases!==void 0&&Array.isArray(s.aliases)){let v=s.aliases.map((D)=>String(D));A("aliases",nR(v)),_.aliases=v.map((D)=>D.trim().toLowerCase()).filter(Boolean)}if(s.redirects!==void 0&&s.redirects&&typeof s.redirects==="object")A("redirects",rR(s.redirects)),_.redirects=s.redirects;for(let v of["domain","path","build","start","type","root","php"])if(typeof s[v]==="string"&&s[v].trim())A(v,tR(String(s[v]).trim())),_[v]=String(s[v]).trim();if(s.port!==void 0&&s.port!==null&&s.port!=="")A("port",String(Number(s.port))),_.port=Number(s.port);return await Tr(R,I),Ct=await br(c,U),y.set(U,Ct),h({ok:!0,configPath:R,site:g,data:Ct})}if(w.pathname==="/api/sites/deploy"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim();if(!g||!c.sites?.[g])return h({ok:!1,error:`Site '${g}' was not found.`},404);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to deploy this site.`},409);let _=Ye(o,String(U));await new Cr(ot).run(new mi,{..._,artifactRoot:e}),Qd(ot,_,Ct??{});let I=Gd(ot,{scope:_,desiredConfigHash:o.project.desiredConfigHash});if(I.decision.outcome==="block")return h({ok:!1,error:`Deployment blocked by security policy: ${I.decision.explanation}`,securityReview:I},409);let A={id:`deploy:${g}`,label:`Deploy ${g}`,description:`Deploy the ${g} site for ${U}.`,command:["deploy","--env",U,"--site",g,"--yes"],mutates:!0},v=await Bn({controlPlane:o,environment:U,actor:z,kind:"dashboard.site.deploy",resourceSlug:g,input:{site:g},execute:()=>Vl(A,{cwd:e,cliEntry:i})});return h({...v.result,controlPlaneOperation:v.operation,securityReview:I})}if(w.pathname==="/api/actions")return h(iE(U));if(w.pathname==="/api/server/operations")return h(oo(c,Ct));if(w.pathname==="/api/runtime/workloads"&&S.method==="GET"){let s=await Ge(c,U);return h(s)}if(w.pathname==="/api/runtime/logs"&&S.method==="GET"){let s=String(w.searchParams.get("workload")??"");if(!s)return h({ok:!1,error:"A workload query parameter is required."},422);let g=Math.min(1000,Math.max(1,Number(w.searchParams.get("limit"))||200));try{return h(await new an(c,U).logs(s,{limit:g}))}catch(_){return h({ok:!1,error:String(_?.message??_)},404)}}if(w.pathname==="/api/runtime/log-sessions"&&S.method==="POST"){let s=await B(S),g=String(s.workloadId??"");if(!g)return h({ok:!1,error:"A workloadId is required."},422);let _=await Ge(c,U),I=_.workloads.find((D)=>D.id===g);if(!I)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);if(!I.capabilities.logs.supported)return h({ok:!1,error:I.capabilities.logs.reason??"Logs are unsupported for this workload."},409);let A=new an(c,U,{inventory:async()=>_}),v=Vt.create("logs",g);return(async()=>{let D=new Date(Date.now()-Math.min(3600000,Math.max(1000,Number(s.sinceMs)||60000)));try{for(let k=0;k<200&&!Vt.signal(v.id)?.aborted;k++){let W=await A.logs(g,{limit:Math.min(500,Math.max(1,Number(s.limit)||200)),since:D});for(let T of W.lines)if(Vt.append(v.id,`${T.timestamp?`${T.timestamp} `:""}${T.message}
499
499
  `),T.timestamp)D=new Date(Math.max(D.getTime(),new Date(T.timestamp).getTime()+1));await Bun.sleep(3000)}if(!Vt.signal(v.id)?.aborted)Vt.close(v.id,"complete")}catch(k){Vt.append(v.id,k instanceof Error?k.message:String(k),"stderr"),Vt.close(v.id,"failed",k instanceof Error?k.message:String(k))}})(),h({ok:!0,session:v,streamUrl:`/api/runtime/log-stream?id=${encodeURIComponent(v.id)}&workload=${encodeURIComponent(g)}`},201)}if((w.pathname==="/api/runtime/log-stream"||w.pathname==="/api/runtime/exec-stream")&&S.method==="GET"){let s=String(w.searchParams.get("id")??""),g=String(w.searchParams.get("workload")??""),_=Number(S.headers.get("last-event-id")??w.searchParams.get("after")??0)||0,I=Vt.read(s,g,_),A=w.pathname.includes("exec")?"exec":"logs";if(!I||I.kind!==A)return h({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return JP(Vt,I,_,S.signal)}if((w.pathname==="/api/runtime/log-sessions"||w.pathname==="/api/runtime/exec-sessions")&&S.method==="DELETE"){let s=await B(S),g=Vt.cancel(String(s.id??""),String(s.workloadId??""));if(!g)return h({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return h({ok:!0,session:g})}if(w.pathname==="/api/runtime/exec-sessions"&&S.method==="POST"){let s=await B(S),g=String(s.workloadId??""),_=await Ge(c,U),I=_.workloads.find((k)=>k.id===g);if(!I)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let A=Bt.resolveSession(S),v=new an(c,U,{inventory:async()=>_}),D=Vt.create("exec",g);return Bn({controlPlane:o,environment:U,actor:z,kind:"runtime.exec",resourceSlug:I.links.service,input:{workloadId:g,provider:I.provider,preset:s.preset?String(s.preset):null,freeForm:!!String(s.command??"").trim()},execute:()=>v.exec({workloadId:g,preset:["process","sockets","filesystem"].includes(String(s.preset))?String(s.preset):void 0,command:typeof s.command==="string"?s.command:void 0,confirm:String(s.confirm??""),recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A)})}).then(({result:k,operation:W})=>{if(Vt.append(D.id,`operation ${W.id}
500
- `,"system"),k.stdout)Vt.append(D.id,k.stdout,"stdout");if(k.stderr)Vt.append(D.id,k.stderr,"stderr");Vt.close(D.id,k.ok?"complete":"failed",k.error)}).catch((k)=>{let W=k instanceof Error?k.message:String(k);Vt.append(D.id,W,"stderr"),Vt.close(D.id,"failed",W)}),h({ok:!0,session:D,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(D.id)}&workload=${encodeURIComponent(g)}`},202)}if(w.pathname==="/api/runtime/files/read"&&S.method==="POST"){let s=await B(S),g=await Ge(c,U),_=Bt.resolveSession(S),I=await new an(c,U,{inventory:async()=>g}).readFile({workloadId:String(s.workloadId??""),path:String(s.path??""),confirm:String(s.confirm??""),recentAuth:!G||!!_&&F.isRecentlyAuthenticated(_)});return h(I,I.ok?200:409)}if(w.pathname==="/api/runtime/files/write"&&S.method==="POST"){let s=await B(S),g=await Ge(c,U),_=String(s.workloadId??""),I=g.workloads.find((k)=>k.id===_);if(!I)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let A=Bt.resolveSession(S),v=new an(c,U,{inventory:async()=>g}),D=await Bn({controlPlane:o,environment:U,actor:z,kind:"runtime.file.write",resourceSlug:I.links.service,input:{workloadId:_,provider:I.provider,path:String(s.path??""),bytes:Buffer.from(String(s.contentBase64??""),"base64").byteLength},execute:()=>v.writeFile({workloadId:_,path:String(s.path??""),contentBase64:String(s.contentBase64??""),confirm:String(s.confirm??""),recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A)})});return h({...D.result,controlPlaneOperation:D.operation},D.result.ok?200:409)}if(w.pathname==="/api/runtime/operations"&&S.method==="POST"){let s=await B(S),g=String(s.workloadId??""),_=String(s.action??"");if(!g||!["start","stop","restart","redeploy","scale","inspect"].includes(_))return h({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let I=await Ge(c,U),A=I.workloads.find((W)=>W.id===g);if(!A)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let v=Bt.resolveSession(S),D=new an(c,U,{inventory:async()=>I}),k=await Bn({controlPlane:o,environment:U,actor:z,kind:`runtime.${_}`,resourceSlug:A.links.service,input:{workloadId:g,provider:A.provider,action:_,replicas:s.replicas==null?null:Number(s.replicas)},execute:()=>D.run({workloadId:g,action:_,replicas:s.replicas==null?void 0:Number(s.replicas),confirm:String(s.confirm??""),recentAuth:!G||!!v&&F.isRecentlyAuthenticated(v)})});return h({...k.result,controlPlaneOperation:k.operation},k.result.ok?200:409)}if(w.pathname.startsWith("/api/protection")){let s=z.role==="admin"||Ec(z,"security:read"),g=z.role==="admin"||Ec(z,"security:manage");if(!s)return h({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:_,describePosture:I}=await import("./chunk-9v39615t.js"),A=new _(o.store),v=()=>{if(!g)throw Error("Changing protection controls requires security:manage.")};if(w.pathname==="/api/protection"&&S.method==="GET"){let D=A.current();return h({ok:!0,posture:I(D),controls:D,raw:A.raw()})}if(w.pathname==="/api/protection/attack-mode"&&S.method==="POST"){v();let D=await B(S);if(D.enabled===!1)return h({ok:!0,disabled:A.disableAttackMode()});return h({ok:!0,control:A.enableAttackMode({hours:D.hours==null?void 0:Number(D.hours),reason:String(D.reason??"Enabled from the dashboard."),actorId:X(z).actor?.id})})}if(w.pathname==="/api/protection/pause"&&S.method==="POST"){v();let D=await B(S);if(D.enabled===!1)return h({ok:!0,resumed:A.resumeMitigations()});return h({ok:!0,control:A.pauseMitigations({hours:D.hours==null?void 0:Number(D.hours),reason:String(D.reason??""),actorId:X(z).actor?.id})})}if(w.pathname==="/api/protection/ip-rules"&&S.method==="GET")return h({ok:!0,ipRules:A.current().ipRules});if(w.pathname==="/api/protection/ip-rules"&&(S.method==="POST"||S.method==="DELETE")){v();let D=await B(S),k=D.list==="allow"?"allow":"block",W=S.method==="POST"?A.addIpRule(k,String(D.cidr??"")):A.removeIpRule(k,String(D.cidr??""));return h({ok:!0,ipRules:W})}return h({ok:!1,error:"Protection endpoint was not found."},404)}if(w.pathname.startsWith("/api/spend/")||w.pathname==="/api/usage"){let s=await sE(),g=s.store,_=s.service,I=s.gate,A=z.role==="admin"||Ec(z,"billing:read"),v=z.role==="admin"||Ec(z,"billing:manage");if(!A)return h({ok:!1,error:"Spend data requires the billing:read capability."},403);let D=o.environments.get(U),k={organizationId:o.organization.id,projectId:o.project.id,environmentId:D?.id},W=()=>{if(!v)throw Error("Changing a budget requires the billing:manage capability.")};if(w.pathname==="/api/usage"&&S.method==="GET")return h({ok:!0,..._.usageReport({organizationId:k.organizationId,projectId:k.projectId,period:w.searchParams.get("period")??"monthly",timezone:w.searchParams.get("timezone")??void 0})});if(w.pathname==="/api/spend/budgets"&&S.method==="GET")return h({ok:!0,budgets:g.listBudgets({organizationId:k.organizationId,projectId:k.projectId}).map((T)=>({...T,status:_.status(T)}))});if(w.pathname==="/api/spend/budgets"&&S.method==="POST"){W();let T=await B(S),et=String(T.scope??"project"),j=g.createBudget({organizationId:k.organizationId,projectId:et==="organization"?void 0:k.projectId,environmentId:et==="environment"?k.environmentId:void 0,name:String(T.name??"").trim(),period:T.period??"monthly",timezone:T.timezone?String(T.timezone):void 0,softLimitCents:T.softLimitCents==null?void 0:Math.round(Number(T.softLimitCents)),hardLimitCents:T.hardLimitCents==null?void 0:Math.round(Number(T.hardLimitCents)),graceSeconds:T.graceSeconds==null?void 0:Number(T.graceSeconds),dryRun:T.dryRun!==!1});return h({ok:!0,budget:j})}if(w.pathname==="/api/spend/budgets"&&S.method==="PATCH"){W();let T=await B(S),et=String(T.id??""),j=g.getBudget(et);if(!j||j.organizationId!==k.organizationId)return h({ok:!1,error:"Budget was not found."},404);return h({ok:!0,budget:g.updateBudget(et,{softLimitCents:T.softLimitCents==null?j.softLimitCents:Math.round(Number(T.softLimitCents)),hardLimitCents:T.hardLimitCents==null?j.hardLimitCents:Math.round(Number(T.hardLimitCents)),enabled:T.enabled==null?j.enabled:T.enabled===!0,dryRun:T.dryRun==null?j.dryRun:T.dryRun===!0},T.expectedVersion==null?void 0:Number(T.expectedVersion))})}if(w.pathname==="/api/spend/budgets"&&S.method==="DELETE"){W();let T=await B(S),et=String(T.id??""),j=g.getBudget(et);if(!j||j.organizationId!==k.organizationId)return h({ok:!1,error:"Budget was not found."},404);let K=I.closeBudget(et);return g.deleteBudget(et),h({ok:!0,deleted:!0,lifted:K})}if(w.pathname==="/api/spend/check"&&S.method==="POST"){W();let T=await B(S),{SpendRunner:et}=await import("./chunk-b9qbp8j1.js"),j=new et({controlPlane:o.store,store:g,alerts:nt});if(T.apply!==!0){let L=g.budgetsForScope(k.organizationId,k.projectId,k.environmentId);return h({ok:!0,applied:!1,preview:L.map((M)=>_.status(M))})}let K=await j.run({...k,environmentKind:D?.kind});return h({ok:!0,applied:!0,result:K})}if(w.pathname==="/api/spend/enforcement"&&S.method==="GET")return h({ok:!0,enforcement:I.listUnder({organizationId:k.organizationId})});if(w.pathname==="/api/spend/release"&&S.method==="POST"){W();let T=await B(S),et=I.close(String(T.budgetId??""),T.action);return h({ok:et,released:et,note:et?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(w.pathname==="/api/spend/anomalies"&&S.method==="GET")return h({ok:!0,anomalies:g.listAnomalies({organizationId:k.organizationId,projectId:k.projectId,unacknowledgedOnly:w.searchParams.get("unacknowledged")==="true"})});if(w.pathname==="/api/spend/anomalies/acknowledge"&&S.method==="POST"){W();let T=await B(S);return h({ok:!0,acknowledged:g.acknowledgeAnomaly(String(T.id??""))})}return h({ok:!1,error:"Spend endpoint was not found."},404)}if(w.pathname.startsWith("/api/health/")||w.pathname.startsWith("/api/alerts")||w.pathname.startsWith("/api/notifications/")){let s=o.environments.get(U),g=o.store.listResources(o.project.id,s?.id),_=z.role==="admin"||!!s&&ki(z,s.id,"runtime:read")?g:g.filter((D)=>Kt(z,D.id,"runtime:read")),I=(D)=>!D||_.some((k)=>k.id===D),A=(D)=>{if(!D)return;let k=g.find((W)=>W.id===D||W.slug===D);if(!k)throw Error("Alert resource was not found.");if(!I(k.id))throw Error("Alert resource is outside your authorized scope.");return k.id},v=X(z).actor;if(w.pathname==="/api/health/checks"&&S.method==="GET")return h({ok:!0,checks:nt.listHealthChecks(o.project.id,s?.id).filter((D)=>I(D.resourceId)).map((D)=>({...D,results:nt.listHealthResults(D.id,20)}))});if(w.pathname==="/api/health/checks"&&S.method==="POST"){let D=await B(S),k=String(D.kind??"http");if(k==="command"&&z.role!=="admin")return h({ok:!1,error:"Command health checks require an administrator."},403);let W={method:String(D.config?.method??"GET").toUpperCase().slice(0,10),path:D.config?.path?String(D.config.path).slice(0,500):void 0,port:D.config?.port==null?void 0:Number(D.config.port),command:Array.isArray(D.config?.command)?D.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(D.config?.expectedStatuses)?D.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:D.config?.expectedBody?String(D.config.expectedBody).slice(0,500):void 0};return h({ok:!0,check:nt.createHealthCheck({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),name:String(D.name??""),kind:k,target:String(D.target??""),config:W,intervalSeconds:Number(D.intervalSeconds)||60,timeoutSeconds:Number(D.timeoutSeconds)||10,failureThreshold:Number(D.failureThreshold)||3,recoveryThreshold:Number(D.recoveryThreshold)||2,regions:Array.isArray(D.regions)?D.regions.map(String):["local"],enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/health/checks"&&S.method==="PATCH"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,check:nt.setHealthCheckEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/health/checks/test"&&S.method==="POST"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,productionIncidentCreated:!1,result:await new yi(nt).probe(k)})}if(w.pathname==="/api/health/checks/run"&&S.method==="POST"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);let W=await new yi(nt).runAndEvaluate(k),T=[];for(let et of W.evaluations.filter((j)=>j.notify&&j.alert)){let j=Je.enqueue(o.organization.id,et.alert,et.transition);T.push(...await Je.deliverAll(j))}return h({ok:!0,...W,deliveries:T})}if(w.pathname==="/api/alerts/rules"&&S.method==="GET")return h({ok:!0,rules:nt.listRules(o.project.id,s?.id).filter((D)=>I(D.resourceId))});if(w.pathname==="/api/alerts/rules"&&S.method==="POST"){let D=await B(S),k=D.healthCheckId?nt.getHealthCheck(String(D.healthCheckId)):void 0;if(D.healthCheckId&&(!k||!I(k.resourceId)))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,rule:nt.createRule({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource)??k?.resourceId,healthCheckId:k?.id,name:String(D.name??""),signal:String(D.signal??(k?"health":"")),operator:String(D.operator??(k?"unhealthy":"gt")),threshold:D.threshold==null?void 0:Number(D.threshold),recoveryThreshold:D.recoveryThreshold==null?void 0:Number(D.recoveryThreshold),windowMs:Number(D.windowMs)||300000,consecutive:Number(D.consecutive)||k?.failureThreshold||3,recoveryConsecutive:Number(D.recoveryConsecutive)||k?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(D.noDataPolicy))?D.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(D.severity))?D.severity:"warning",groupBy:Array.isArray(D.groupBy)?D.groupBy.map(String):[],labels:D.labels&&typeof D.labels==="object"?D.labels:{},enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/alerts/rules"&&S.method==="PATCH"){let D=await B(S),k=nt.getRule(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Alert rule was not found."},404);return h({ok:!0,rule:nt.setRuleEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/alerts/evaluate"&&S.method==="POST")return h({ok:!0,...await Kl(s?.id)});if(w.pathname==="/api/alerts"&&S.method==="GET")return h({ok:!0,alerts:nt.listAlerts(o.project.id,{environmentId:s?.id,states:w.searchParams.getAll("state").length?w.searchParams.getAll("state"):void 0,limit:Number(w.searchParams.get("limit"))||200}).filter((D)=>I(D.resourceId)).map((D)=>({...D,deliveries:nt.listDeliveries({alertId:D.id,limit:50})}))});if(w.pathname==="/api/alerts/action"&&S.method==="POST"){let D=await B(S),k=nt.getAlert(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Alert was not found."},404);let W=String(D.action??"");if(W==="acknowledge")return h({ok:!0,alert:nt.acknowledge(k.id,v?.id??"")});if(W==="assign")return h({ok:!0,alert:nt.assign(k.id,D.ownerActorId==="me"?v?.id:D.ownerActorId?String(D.ownerActorId):void 0,v?.id)});if(W==="silence"){if(z.role!=="admin")return h({ok:!1,error:"Silencing production alerts requires an administrator."},403);let T=Bt.resolveSession(S);if(G&&(!T||!F.isRecentlyAuthenticated(T)))return h({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return h({ok:!0,alert:nt.silenceAlert(k.id,String(D.until??""),v?.id)})}return h({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(w.pathname==="/api/alerts/silences"&&S.method==="POST"){let D=await B(S);return h({ok:!0,id:nt.createSilence({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),matcher:D.matcher,reason:String(D.reason??""),startsAt:String(D.startsAt??new Date().toISOString()),endsAt:String(D.endsAt??""),timezone:String(D.timezone??"UTC"),actorId:v?.id})},201)}if(w.pathname==="/api/notifications/channels"&&S.method==="GET")return h({ok:!0,channels:nt.listChannels(o.organization.id)});if(w.pathname==="/api/notifications/channels"&&S.method==="POST"){let D=await B(S),k=String(D.kind??""),W=k==="email"?{to:D.config?.to,from:D.config?.from}:k==="telegram"?{chatId:String(D.config?.chatId??"")}:{};return h({ok:!0,channel:nt.createChannel({organizationId:o.organization.id,name:String(D.name??""),kind:k,config:W,credential:D.credential?String(D.credential):void 0,actorId:v?.id})},201)}if(w.pathname==="/api/notifications/channels"&&S.method==="PATCH"){let D=await B(S),k=String(D.id??"");if(D.credential)return h({ok:!0,channel:nt.rotateChannel(k,String(D.credential))});let W=String(D.status??"paused");if(!["active","paused","disabled"].includes(W))return h({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return h({ok:!0,channel:nt.setChannelStatus(k,W)})}if(w.pathname==="/api/notifications/channels/test"&&S.method==="POST"){let D=await B(S);return h({ok:!0,productionIncidentCreated:!1,result:await Je.testChannel(String(D.id??""))})}if(w.pathname==="/api/notifications/routes"&&S.method==="GET")return h({ok:!0,routes:nt.listRoutes(o.organization.id)});if(w.pathname==="/api/notifications/routes"&&S.method==="POST"){let D=await B(S),k=Array.isArray(D.channelIds)?D.channelIds.map(String):[];if(k.some((W)=>nt.getChannel(W)?.organizationId!==o.organization.id))return h({ok:!1,error:"Route contains an unavailable channel."},422);return h({ok:!0,route:nt.createRoute({organizationId:o.organization.id,name:String(D.name??""),priority:Number(D.priority)||0,matcher:D.matcher&&typeof D.matcher==="object"?D.matcher:{},channelIds:k,quietHours:D.quietHours,groupWaitSeconds:Number(D.groupWaitSeconds)||30,reminderSeconds:D.reminderSeconds==null?void 0:Number(D.reminderSeconds),escalation:Array.isArray(D.escalation)?D.escalation:[],template:D.template?String(D.template):void 0,rateLimitPerMinute:Number(D.rateLimitPerMinute)||60,enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/notifications/routes"&&S.method==="PATCH"){let D=await B(S),k=nt.getRoute(String(D.id??""));if(!k||k.organizationId!==o.organization.id)return h({ok:!1,error:"Notification route was not found."},404);return h({ok:!0,route:nt.setRouteEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/notifications/routes/preview"&&S.method==="POST"){let D=await B(S),W=(D.alertId?nt.getAlert(String(D.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),dedupKey:"preview",groupKey:String(D.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(D.severity))?D.severity:"warning",title:String(D.title??"Rule preview"),evidence:{},failureCount:1,recoveryCount:0,occurrenceCount:1,firstSeenAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),firingAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return h({ok:!0,productionIncidentCreated:!1,matches:Je.preview(o.organization.id,W,String(D.eventType??"firing")).map((T)=>({route:T.route,channels:T.channels,quiet:T.quiet}))})}if(w.pathname==="/api/notifications/deliveries"&&S.method==="GET")return h({ok:!0,deliveries:nt.listDeliveries({alertId:w.searchParams.get("alertId")??void 0,states:w.searchParams.getAll("state"),limit:Number(w.searchParams.get("limit"))||200})});if(w.pathname==="/api/notifications/deliveries/retry"&&S.method==="POST"){let D=await B(S),k=nt.getDelivery(String(D.id??""));if(!k)return h({ok:!1,error:"Delivery was not found."},404);return nt.updateDelivery(k.id,{state:"retrying",attempt:Math.max(0,k.attempt-1),nextAttemptAt:new Date().toISOString()}),h({ok:!0,delivery:await Je.deliver(k.id)})}}if(w.pathname.startsWith("/api/jobs")||w.pathname.startsWith("/api/workers")){let s=o.environments.get(U),g=o.store.listResources(o.project.id,s?.id),I=z.role==="admin"||!!s&&ki(z,s.id,"automation:read")?g:g.filter((L)=>Kt(z,L.id,"automation:read")),A=(L)=>!L||I.some((M)=>M.id===L),v=X(z).actor,D=y.get(U)??E,k=oo(c,D),W=k.filter((L)=>!L.danger&&["scheduler","backup","worker"].includes(L.group)),T=On(c),et=()=>{let L=Bt.resolveSession(S);return!G||!!L&&F.isRecentlyAuthenticated(L)},j=(L)=>{if(!L||typeof L!=="object"||Array.isArray(L))return{};let M=Object.entries(L).slice(0,50);if(M.some(([,ct])=>typeof ct!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(ct)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(M)},K=(L,M,ct)=>o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,resourceId:ct,actorId:v?.id,type:`job.${L}`,payload:M});if(w.pathname==="/api/jobs/preview"&&S.method==="POST"){let L=await B(S);try{return h({ok:!0,productionExecutionCreated:!1,preview:_r(String(L.expression??""),String(L.timezone??"UTC"),new Date(L.from?String(L.from):Date.now()),Number(L.count)||5)})}catch(M){return h({ok:!1,error:M instanceof Error?M.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(w.pathname==="/api/jobs"&&S.method==="GET")return h({ok:!0,jobs:Xt.list(o.project.id,{environmentId:s?.id}).filter((L)=>A(L.resourceId)).map((L)=>({...L,preview:_r(L.normalizedExpression,L.timezone,new Date,5),capability:sa(L),lastExecution:Xt.listExecutions(L.id,1)[0]}))});if(w.pathname==="/api/jobs"&&S.method==="POST"){let L=await B(S),M=String(L.provider??(T==="serverless"?"eventbridge":"server")),ct=T==="serverless"?"eventbridge":"server";if(M!==ct)return h({ok:!1,error:`${T} environments accept ${ct} schedules through this adapter.`},422);let lt=L.operationId?String(L.operationId):void 0;if(M==="server"&&(!lt||!W.some((Nt)=>Nt.id===lt)))return h({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let It=sa({provider:M,expression:String(L.expression??""),flexibleMinutes:Number(L.flexibleMinutes)||0,missedRunPolicy:L.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(L.overlapPolicy))?L.overlapPolicy:"forbid"});if(!It.supported)return h({ok:!1,error:It.notes.join(" ")},422);let Pe=L.resourceId?g.find((Nt)=>Nt.id===L.resourceId||Nt.slug===L.resourceId):void 0;if(L.resourceId&&(!Pe||!A(Pe.id)))return h({ok:!1,error:"Job resource was not found."},404);try{let Nt=M==="server"?{kind:"dashboard_operation",operationId:lt}:{kind:"serverless_scheduler",action:"run"},Fn=Xt.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,resourceId:Pe?.id,name:String(L.name??""),provider:M,expression:String(L.expression??""),timezone:String(L.timezone??"UTC"),startsAt:L.startsAt?String(L.startsAt):void 0,endsAt:L.endsAt?String(L.endsAt):void 0,flexibleMinutes:Number(L.flexibleMinutes)||0,target:Nt,payloadRefs:j(L.payloadRefs),missedRunPolicy:L.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(L.overlapPolicy))?L.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(L.maxAttempts)||3,backoffSeconds:Number(L.backoffSeconds)||30,deadLetterRef:L.deadLetterRef?String(L.deadLetterRef):void 0},timeoutSeconds:Number(L.timeoutSeconds)||900,enabled:L.enabled!==!1,origin:"managed",ownerActorId:v?.id,observedState:{},reconciliationStatus:"pending"});return K("created",{jobId:Fn.id,provider:Fn.provider,expression:Fn.normalizedExpression},Fn.resourceId),h({ok:!0,job:Fn,capability:It},201)}catch(Nt){return h({ok:!1,error:Nt instanceof Error?Nt.message:"Scheduled job could not be created."},422)}}if(w.pathname==="/api/jobs"&&S.method==="PATCH"){let L=await B(S),M=Xt.get(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);if(M.origin==="config")return h({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let ct=L.missedRunPolicy==null?void 0:String(L.missedRunPolicy),lt=L.overlapPolicy==null?void 0:String(L.overlapPolicy);if(ct&&!["skip","catch_up"].includes(ct))return h({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(lt&&!["allow","forbid","replace"].includes(lt))return h({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let It=Xt.updateSchedule(M.id,{expression:L.expression?String(L.expression):void 0,timezone:L.timezone?String(L.timezone):void 0,missedRunPolicy:ct,overlapPolicy:lt,timeoutSeconds:L.timeoutSeconds==null?void 0:Number(L.timeoutSeconds)});return K("updated",{jobId:It.id,expression:It.normalizedExpression,version:It.version},It.resourceId),h({ok:!0,job:It})}catch(It){return h({ok:!1,error:It instanceof Error?It.message:"Scheduled job could not be updated."},422)}}if(w.pathname==="/api/jobs/action"&&S.method==="POST"){let L=await B(S),M=Xt.get(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);let ct=String(L.action??"");if(ct==="run"){let lt=Xl.enqueue(M,{trigger:"manual",actorId:v?.id});return K("run_queued",{jobId:M.id,executionId:lt.id},M.resourceId),h({ok:!0,execution:lt},202)}if(["disable","delete"].includes(ct)&&s?.kind==="production"){if(String(L.confirm??"")!==ct)return h({ok:!1,error:`Type "${ct}" to confirm this production change.`},409);if(!et())return h({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(ct==="enable"||ct==="disable"){let lt=Xt.setEnabled(M.id,ct==="enable");return K(ct==="enable"?"enabled":"disabled",{jobId:M.id},M.resourceId),h({ok:!0,job:lt})}if(ct==="delete")try{return Xt.remove(M.id),K("deleted",{jobId:M.id,name:M.name},M.resourceId),h({ok:!0,deleted:M.id})}catch(lt){return h({ok:!1,error:lt instanceof Error?lt.message:"Scheduled job could not be deleted."},409)}return h({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(w.pathname==="/api/jobs/history"&&S.method==="GET"){let L=Xt.get(String(w.searchParams.get("jobId")??""));if(!L||!A(L.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);return h({ok:!0,executions:Xt.listExecutions(L.id,Number(w.searchParams.get("limit"))||100).map((M)=>({...M,logs:M.operationId?yt.logs(M.operationId,{limit:500}):[]}))})}if(w.pathname==="/api/jobs/reconcile"&&S.method==="POST"){if(!s)return h({ok:!1,error:"Environment was not found."},404);let L=la(Xt,c,{organization:o.organization,project:o.project,environment:s,resources:g});return K("reconciled",L),h({ok:!0,reconciliation:L})}if(w.pathname==="/api/workers"&&S.method==="GET"){let L=Array.isArray(D.workersDetail??D.workers)?D.workersDetail??D.workers:[];return h({ok:!0,workers:Xt.listWorkers(o.project.id,s?.id).filter((M)=>A(M.resourceId)).map((M)=>{let ct=L.find((lt)=>lt.name===M.name||lt.site===M.target.site);return ct?{...M,observedState:{...M.observedState,status:ct.status??"configured",currentJob:ct.currentJob??null,failures:Number(ct.failed??ct.failures)||0,processed:Number(ct.processed)||0}}:M})})}if(w.pathname==="/api/workers/action"&&S.method==="POST"){let L=await B(S),M=Xt.getWorker(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Worker was not found."},404);let ct=String(L.action??"");if(ct==="restart"){if(String(L.confirm??"")!==M.name)return h({ok:!1,error:`Type "${M.name}" to restart this worker.`},409);let lt=k.find((Nt)=>Nt.id===M.target.operationId);if(!lt)return h({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let It=await ao(c,U,lt),Pe=Xt.reconcileWorker(M.id,It.ok?"in_sync":"unavailable",{...M.observedState,lastRestartAt:new Date().toISOString(),command:It.command??null,error:It.error??It.stderr??null});return K("worker_restarted",{workerId:M.id,ok:It.ok},M.resourceId),h({...It,worker:Pe},It.ok?200:409)}if(ct==="scale")return h({ok:!1,error:M.provider==="systemd"?"Systemd worker scale is config-managed; edit the worker definition and reconcile.":"This provider does not expose safe worker scaling through the current adapter."},422);return h({ok:!1,error:"Action must be restart or scale."},422)}}if(w.pathname.startsWith("/api/telemetry/")){let s=o.environments.get(U),g=new uo(o.store),_=o.store.listResources(o.project.id,s?.id),I=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(w.pathname)?"runtime:logs":"runtime:read",A=z.role==="admin"||!!s&&ki(z,s.id,I),v=A?_:_.filter((j)=>Kt(z,j.id,I)),D=(j)=>dR(v,A,j),k=(j)=>{let K=new Date,L={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},M=String(j.to??K.toISOString()),ct=String(j.from??new Date(new Date(M).getTime()-(L[String(j.range??"1h")]??L["1h"])).toISOString()),lt=(Pe)=>{let Nt=(Array.isArray(Pe)?Pe:String(Pe??"").split(",")).map(String).filter(Boolean);return Nt.length?Nt:void 0},It=lt(j.kinds)?.filter((Pe)=>["metric","log","trace","request","event"].includes(Pe));return{projectId:o.project.id,environmentId:s?.id,resourceIds:D(j.resources),kinds:It,names:lt(j.names),sources:lt(j.sources),levels:lt(j.levels),from:ct,to:M,text:String(j.text??"")||void 0,traceId:String(j.traceId??"")||void 0,requestId:String(j.requestId??"")||void 0,deploymentId:String(j.deploymentId??"")||void 0,releaseId:String(j.releaseId??"")||void 0,workloadId:String(j.workloadId??"")||void 0,cursor:String(j.cursor??"")||void 0,limit:Number(j.limit)||void 0}},W=Object.fromEntries(w.searchParams.entries()),T=(j=!1)=>Ll({controlPlane:o.store,projectId:o.project.id,environmentId:s?.id,config:c,environment:U,force:j,lightweight:!j}),et=()=>{let j=o.store.getSetting(`telemetry.collection:${o.project.id}:${s?.id??"all"}`)??{};return{generatedAt:String(j.generatedAt??new Date().toISOString()),cached:!0,statuses:Array.isArray(j.statuses)?j.statuses:[],errors:Array.isArray(j.errors)?j.errors:[],policy:j.policy??ac(o.store,o.project.id)}};if(w.pathname==="/api/telemetry/status"&&S.method==="GET"){T(!1);let j=et(),K=A?j.statuses:g.status(o.project.id,s?.id,j.policy.rawDays,j.policy.samplingRate,v.map((M)=>M.id)),L=K.reduce((M,ct)=>M+ct.estimatedDailyBytes*30,0);return h({ok:!0,generatedAt:j.generatedAt,cached:j.cached,sources:K,errors:A?j.errors:[],policy:j.policy,retention:{rawDays:j.policy.rawDays,downsampleAfterDays:j.policy.downsampleAfterDays,downsampleBucketMs:j.policy.downsampleBucketMs,maxRecords:j.policy.maxRecords},estimatedMonthlyBytes:L,estimatedMonthlyCostUsd:YR(L,j.policy),costEstimateConfigured:j.policy.estimatedStorageUsdPerGbMonth>0})}if(w.pathname==="/api/telemetry/settings"&&S.method==="GET")return h({ok:!0,policy:ac(o.store,o.project.id)});if(w.pathname==="/api/telemetry/settings"&&S.method==="PATCH"){let j=ZR(o.store,o.project.id,await B(S));return SR(o.project.id),h({ok:!0,policy:j})}if(w.pathname==="/api/telemetry/query"&&S.method==="GET"){T(!1);let j=et();return h({ok:!0,collection:{generatedAt:j.generatedAt,cached:j.cached},...g.query(k(W))})}if(w.pathname==="/api/telemetry/tail"&&S.method==="GET"){T(!1);let j=new TextEncoder,K=new Date,L=k({...W,kinds:W.kinds||"log,request,event,trace",from:W.from||new Date(K.getTime()-120000).toISOString(),to:K.toISOString(),limit:Math.min(1000,Number(W.limit)||200),cursor:void 0}),M=S.headers.get("last-event-id")||String(W.cursor??"")||void 0,ct,lt=!1,It=!1,Pe=new ReadableStream({start(Nt){let Fn=()=>{if(lt)return;if(lt=!0,ct)clearInterval(ct);S.signal.removeEventListener("abort",Fn);try{Nt.close()}catch{}},ag=async()=>{if(lt||It)return;It=!0;try{let or=g.tail({...L,to:new Date(Date.now()+1000).toISOString()},M);for(let sg of or.records)M=XR(sg)??M,Nt.enqueue(j.encode(`id: ${M??""}
500
+ `,"system"),k.stdout)Vt.append(D.id,k.stdout,"stdout");if(k.stderr)Vt.append(D.id,k.stderr,"stderr");Vt.close(D.id,k.ok?"complete":"failed",k.error)}).catch((k)=>{let W=k instanceof Error?k.message:String(k);Vt.append(D.id,W,"stderr"),Vt.close(D.id,"failed",W)}),h({ok:!0,session:D,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(D.id)}&workload=${encodeURIComponent(g)}`},202)}if(w.pathname==="/api/runtime/files/read"&&S.method==="POST"){let s=await B(S),g=await Ge(c,U),_=Bt.resolveSession(S),I=await new an(c,U,{inventory:async()=>g}).readFile({workloadId:String(s.workloadId??""),path:String(s.path??""),confirm:String(s.confirm??""),recentAuth:!G||!!_&&F.isRecentlyAuthenticated(_)});return h(I,I.ok?200:409)}if(w.pathname==="/api/runtime/files/write"&&S.method==="POST"){let s=await B(S),g=await Ge(c,U),_=String(s.workloadId??""),I=g.workloads.find((k)=>k.id===_);if(!I)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let A=Bt.resolveSession(S),v=new an(c,U,{inventory:async()=>g}),D=await Bn({controlPlane:o,environment:U,actor:z,kind:"runtime.file.write",resourceSlug:I.links.service,input:{workloadId:_,provider:I.provider,path:String(s.path??""),bytes:Buffer.from(String(s.contentBase64??""),"base64").byteLength},execute:()=>v.writeFile({workloadId:_,path:String(s.path??""),contentBase64:String(s.contentBase64??""),confirm:String(s.confirm??""),recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A)})});return h({...D.result,controlPlaneOperation:D.operation},D.result.ok?200:409)}if(w.pathname==="/api/runtime/operations"&&S.method==="POST"){let s=await B(S),g=String(s.workloadId??""),_=String(s.action??"");if(!g||!["start","stop","restart","redeploy","scale","inspect"].includes(_))return h({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let I=await Ge(c,U),A=I.workloads.find((W)=>W.id===g);if(!A)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let v=Bt.resolveSession(S),D=new an(c,U,{inventory:async()=>I}),k=await Bn({controlPlane:o,environment:U,actor:z,kind:`runtime.${_}`,resourceSlug:A.links.service,input:{workloadId:g,provider:A.provider,action:_,replicas:s.replicas==null?null:Number(s.replicas)},execute:()=>D.run({workloadId:g,action:_,replicas:s.replicas==null?void 0:Number(s.replicas),confirm:String(s.confirm??""),recentAuth:!G||!!v&&F.isRecentlyAuthenticated(v)})});return h({...k.result,controlPlaneOperation:k.operation},k.result.ok?200:409)}if(w.pathname.startsWith("/api/protection")){let s=z.role==="admin"||Ec(z,"security:read"),g=z.role==="admin"||Ec(z,"security:manage");if(!s)return h({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:_,describePosture:I}=await import("./chunk-21e0mavm.js"),A=new _(o.store),v=()=>{if(!g)throw Error("Changing protection controls requires security:manage.")};if(w.pathname==="/api/protection"&&S.method==="GET"){let D=A.current();return h({ok:!0,posture:I(D),controls:D,raw:A.raw()})}if(w.pathname==="/api/protection/attack-mode"&&S.method==="POST"){v();let D=await B(S);if(D.enabled===!1)return h({ok:!0,disabled:A.disableAttackMode()});return h({ok:!0,control:A.enableAttackMode({hours:D.hours==null?void 0:Number(D.hours),reason:String(D.reason??"Enabled from the dashboard."),actorId:X(z).actor?.id})})}if(w.pathname==="/api/protection/pause"&&S.method==="POST"){v();let D=await B(S);if(D.enabled===!1)return h({ok:!0,resumed:A.resumeMitigations()});return h({ok:!0,control:A.pauseMitigations({hours:D.hours==null?void 0:Number(D.hours),reason:String(D.reason??""),actorId:X(z).actor?.id})})}if(w.pathname==="/api/protection/ip-rules"&&S.method==="GET")return h({ok:!0,ipRules:A.current().ipRules});if(w.pathname==="/api/protection/ip-rules"&&(S.method==="POST"||S.method==="DELETE")){v();let D=await B(S),k=D.list==="allow"?"allow":"block",W=S.method==="POST"?A.addIpRule(k,String(D.cidr??"")):A.removeIpRule(k,String(D.cidr??""));return h({ok:!0,ipRules:W})}return h({ok:!1,error:"Protection endpoint was not found."},404)}if(w.pathname.startsWith("/api/spend/")||w.pathname==="/api/usage"){let s=await sE(),g=s.store,_=s.service,I=s.gate,A=z.role==="admin"||Ec(z,"billing:read"),v=z.role==="admin"||Ec(z,"billing:manage");if(!A)return h({ok:!1,error:"Spend data requires the billing:read capability."},403);let D=o.environments.get(U),k={organizationId:o.organization.id,projectId:o.project.id,environmentId:D?.id},W=()=>{if(!v)throw Error("Changing a budget requires the billing:manage capability.")};if(w.pathname==="/api/usage"&&S.method==="GET")return h({ok:!0,..._.usageReport({organizationId:k.organizationId,projectId:k.projectId,period:w.searchParams.get("period")??"monthly",timezone:w.searchParams.get("timezone")??void 0})});if(w.pathname==="/api/spend/budgets"&&S.method==="GET")return h({ok:!0,budgets:g.listBudgets({organizationId:k.organizationId,projectId:k.projectId}).map((T)=>({...T,status:_.status(T)}))});if(w.pathname==="/api/spend/budgets"&&S.method==="POST"){W();let T=await B(S),et=String(T.scope??"project"),j=g.createBudget({organizationId:k.organizationId,projectId:et==="organization"?void 0:k.projectId,environmentId:et==="environment"?k.environmentId:void 0,name:String(T.name??"").trim(),period:T.period??"monthly",timezone:T.timezone?String(T.timezone):void 0,softLimitCents:T.softLimitCents==null?void 0:Math.round(Number(T.softLimitCents)),hardLimitCents:T.hardLimitCents==null?void 0:Math.round(Number(T.hardLimitCents)),graceSeconds:T.graceSeconds==null?void 0:Number(T.graceSeconds),dryRun:T.dryRun!==!1});return h({ok:!0,budget:j})}if(w.pathname==="/api/spend/budgets"&&S.method==="PATCH"){W();let T=await B(S),et=String(T.id??""),j=g.getBudget(et);if(!j||j.organizationId!==k.organizationId)return h({ok:!1,error:"Budget was not found."},404);return h({ok:!0,budget:g.updateBudget(et,{softLimitCents:T.softLimitCents==null?j.softLimitCents:Math.round(Number(T.softLimitCents)),hardLimitCents:T.hardLimitCents==null?j.hardLimitCents:Math.round(Number(T.hardLimitCents)),enabled:T.enabled==null?j.enabled:T.enabled===!0,dryRun:T.dryRun==null?j.dryRun:T.dryRun===!0},T.expectedVersion==null?void 0:Number(T.expectedVersion))})}if(w.pathname==="/api/spend/budgets"&&S.method==="DELETE"){W();let T=await B(S),et=String(T.id??""),j=g.getBudget(et);if(!j||j.organizationId!==k.organizationId)return h({ok:!1,error:"Budget was not found."},404);let K=I.closeBudget(et);return g.deleteBudget(et),h({ok:!0,deleted:!0,lifted:K})}if(w.pathname==="/api/spend/check"&&S.method==="POST"){W();let T=await B(S),{SpendRunner:et}=await import("./chunk-qk9qgepa.js"),j=new et({controlPlane:o.store,store:g,alerts:nt});if(T.apply!==!0){let L=g.budgetsForScope(k.organizationId,k.projectId,k.environmentId);return h({ok:!0,applied:!1,preview:L.map((M)=>_.status(M))})}let K=await j.run({...k,environmentKind:D?.kind});return h({ok:!0,applied:!0,result:K})}if(w.pathname==="/api/spend/enforcement"&&S.method==="GET")return h({ok:!0,enforcement:I.listUnder({organizationId:k.organizationId})});if(w.pathname==="/api/spend/release"&&S.method==="POST"){W();let T=await B(S),et=I.close(String(T.budgetId??""),T.action);return h({ok:et,released:et,note:et?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(w.pathname==="/api/spend/anomalies"&&S.method==="GET")return h({ok:!0,anomalies:g.listAnomalies({organizationId:k.organizationId,projectId:k.projectId,unacknowledgedOnly:w.searchParams.get("unacknowledged")==="true"})});if(w.pathname==="/api/spend/anomalies/acknowledge"&&S.method==="POST"){W();let T=await B(S);return h({ok:!0,acknowledged:g.acknowledgeAnomaly(String(T.id??""))})}return h({ok:!1,error:"Spend endpoint was not found."},404)}if(w.pathname.startsWith("/api/health/")||w.pathname.startsWith("/api/alerts")||w.pathname.startsWith("/api/notifications/")){let s=o.environments.get(U),g=o.store.listResources(o.project.id,s?.id),_=z.role==="admin"||!!s&&ki(z,s.id,"runtime:read")?g:g.filter((D)=>Kt(z,D.id,"runtime:read")),I=(D)=>!D||_.some((k)=>k.id===D),A=(D)=>{if(!D)return;let k=g.find((W)=>W.id===D||W.slug===D);if(!k)throw Error("Alert resource was not found.");if(!I(k.id))throw Error("Alert resource is outside your authorized scope.");return k.id},v=X(z).actor;if(w.pathname==="/api/health/checks"&&S.method==="GET")return h({ok:!0,checks:nt.listHealthChecks(o.project.id,s?.id).filter((D)=>I(D.resourceId)).map((D)=>({...D,results:nt.listHealthResults(D.id,20)}))});if(w.pathname==="/api/health/checks"&&S.method==="POST"){let D=await B(S),k=String(D.kind??"http");if(k==="command"&&z.role!=="admin")return h({ok:!1,error:"Command health checks require an administrator."},403);let W={method:String(D.config?.method??"GET").toUpperCase().slice(0,10),path:D.config?.path?String(D.config.path).slice(0,500):void 0,port:D.config?.port==null?void 0:Number(D.config.port),command:Array.isArray(D.config?.command)?D.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(D.config?.expectedStatuses)?D.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:D.config?.expectedBody?String(D.config.expectedBody).slice(0,500):void 0};return h({ok:!0,check:nt.createHealthCheck({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),name:String(D.name??""),kind:k,target:String(D.target??""),config:W,intervalSeconds:Number(D.intervalSeconds)||60,timeoutSeconds:Number(D.timeoutSeconds)||10,failureThreshold:Number(D.failureThreshold)||3,recoveryThreshold:Number(D.recoveryThreshold)||2,regions:Array.isArray(D.regions)?D.regions.map(String):["local"],enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/health/checks"&&S.method==="PATCH"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,check:nt.setHealthCheckEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/health/checks/test"&&S.method==="POST"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,productionIncidentCreated:!1,result:await new yi(nt).probe(k)})}if(w.pathname==="/api/health/checks/run"&&S.method==="POST"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);let W=await new yi(nt).runAndEvaluate(k),T=[];for(let et of W.evaluations.filter((j)=>j.notify&&j.alert)){let j=Je.enqueue(o.organization.id,et.alert,et.transition);T.push(...await Je.deliverAll(j))}return h({ok:!0,...W,deliveries:T})}if(w.pathname==="/api/alerts/rules"&&S.method==="GET")return h({ok:!0,rules:nt.listRules(o.project.id,s?.id).filter((D)=>I(D.resourceId))});if(w.pathname==="/api/alerts/rules"&&S.method==="POST"){let D=await B(S),k=D.healthCheckId?nt.getHealthCheck(String(D.healthCheckId)):void 0;if(D.healthCheckId&&(!k||!I(k.resourceId)))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,rule:nt.createRule({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource)??k?.resourceId,healthCheckId:k?.id,name:String(D.name??""),signal:String(D.signal??(k?"health":"")),operator:String(D.operator??(k?"unhealthy":"gt")),threshold:D.threshold==null?void 0:Number(D.threshold),recoveryThreshold:D.recoveryThreshold==null?void 0:Number(D.recoveryThreshold),windowMs:Number(D.windowMs)||300000,consecutive:Number(D.consecutive)||k?.failureThreshold||3,recoveryConsecutive:Number(D.recoveryConsecutive)||k?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(D.noDataPolicy))?D.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(D.severity))?D.severity:"warning",groupBy:Array.isArray(D.groupBy)?D.groupBy.map(String):[],labels:D.labels&&typeof D.labels==="object"?D.labels:{},enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/alerts/rules"&&S.method==="PATCH"){let D=await B(S),k=nt.getRule(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Alert rule was not found."},404);return h({ok:!0,rule:nt.setRuleEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/alerts/evaluate"&&S.method==="POST")return h({ok:!0,...await Kl(s?.id)});if(w.pathname==="/api/alerts"&&S.method==="GET")return h({ok:!0,alerts:nt.listAlerts(o.project.id,{environmentId:s?.id,states:w.searchParams.getAll("state").length?w.searchParams.getAll("state"):void 0,limit:Number(w.searchParams.get("limit"))||200}).filter((D)=>I(D.resourceId)).map((D)=>({...D,deliveries:nt.listDeliveries({alertId:D.id,limit:50})}))});if(w.pathname==="/api/alerts/action"&&S.method==="POST"){let D=await B(S),k=nt.getAlert(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Alert was not found."},404);let W=String(D.action??"");if(W==="acknowledge")return h({ok:!0,alert:nt.acknowledge(k.id,v?.id??"")});if(W==="assign")return h({ok:!0,alert:nt.assign(k.id,D.ownerActorId==="me"?v?.id:D.ownerActorId?String(D.ownerActorId):void 0,v?.id)});if(W==="silence"){if(z.role!=="admin")return h({ok:!1,error:"Silencing production alerts requires an administrator."},403);let T=Bt.resolveSession(S);if(G&&(!T||!F.isRecentlyAuthenticated(T)))return h({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return h({ok:!0,alert:nt.silenceAlert(k.id,String(D.until??""),v?.id)})}return h({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(w.pathname==="/api/alerts/silences"&&S.method==="POST"){let D=await B(S);return h({ok:!0,id:nt.createSilence({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),matcher:D.matcher,reason:String(D.reason??""),startsAt:String(D.startsAt??new Date().toISOString()),endsAt:String(D.endsAt??""),timezone:String(D.timezone??"UTC"),actorId:v?.id})},201)}if(w.pathname==="/api/notifications/channels"&&S.method==="GET")return h({ok:!0,channels:nt.listChannels(o.organization.id)});if(w.pathname==="/api/notifications/channels"&&S.method==="POST"){let D=await B(S),k=String(D.kind??""),W=k==="email"?{to:D.config?.to,from:D.config?.from}:k==="telegram"?{chatId:String(D.config?.chatId??"")}:{};return h({ok:!0,channel:nt.createChannel({organizationId:o.organization.id,name:String(D.name??""),kind:k,config:W,credential:D.credential?String(D.credential):void 0,actorId:v?.id})},201)}if(w.pathname==="/api/notifications/channels"&&S.method==="PATCH"){let D=await B(S),k=String(D.id??"");if(D.credential)return h({ok:!0,channel:nt.rotateChannel(k,String(D.credential))});let W=String(D.status??"paused");if(!["active","paused","disabled"].includes(W))return h({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return h({ok:!0,channel:nt.setChannelStatus(k,W)})}if(w.pathname==="/api/notifications/channels/test"&&S.method==="POST"){let D=await B(S);return h({ok:!0,productionIncidentCreated:!1,result:await Je.testChannel(String(D.id??""))})}if(w.pathname==="/api/notifications/routes"&&S.method==="GET")return h({ok:!0,routes:nt.listRoutes(o.organization.id)});if(w.pathname==="/api/notifications/routes"&&S.method==="POST"){let D=await B(S),k=Array.isArray(D.channelIds)?D.channelIds.map(String):[];if(k.some((W)=>nt.getChannel(W)?.organizationId!==o.organization.id))return h({ok:!1,error:"Route contains an unavailable channel."},422);return h({ok:!0,route:nt.createRoute({organizationId:o.organization.id,name:String(D.name??""),priority:Number(D.priority)||0,matcher:D.matcher&&typeof D.matcher==="object"?D.matcher:{},channelIds:k,quietHours:D.quietHours,groupWaitSeconds:Number(D.groupWaitSeconds)||30,reminderSeconds:D.reminderSeconds==null?void 0:Number(D.reminderSeconds),escalation:Array.isArray(D.escalation)?D.escalation:[],template:D.template?String(D.template):void 0,rateLimitPerMinute:Number(D.rateLimitPerMinute)||60,enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/notifications/routes"&&S.method==="PATCH"){let D=await B(S),k=nt.getRoute(String(D.id??""));if(!k||k.organizationId!==o.organization.id)return h({ok:!1,error:"Notification route was not found."},404);return h({ok:!0,route:nt.setRouteEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/notifications/routes/preview"&&S.method==="POST"){let D=await B(S),W=(D.alertId?nt.getAlert(String(D.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),dedupKey:"preview",groupKey:String(D.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(D.severity))?D.severity:"warning",title:String(D.title??"Rule preview"),evidence:{},failureCount:1,recoveryCount:0,occurrenceCount:1,firstSeenAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),firingAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return h({ok:!0,productionIncidentCreated:!1,matches:Je.preview(o.organization.id,W,String(D.eventType??"firing")).map((T)=>({route:T.route,channels:T.channels,quiet:T.quiet}))})}if(w.pathname==="/api/notifications/deliveries"&&S.method==="GET")return h({ok:!0,deliveries:nt.listDeliveries({alertId:w.searchParams.get("alertId")??void 0,states:w.searchParams.getAll("state"),limit:Number(w.searchParams.get("limit"))||200})});if(w.pathname==="/api/notifications/deliveries/retry"&&S.method==="POST"){let D=await B(S),k=nt.getDelivery(String(D.id??""));if(!k)return h({ok:!1,error:"Delivery was not found."},404);return nt.updateDelivery(k.id,{state:"retrying",attempt:Math.max(0,k.attempt-1),nextAttemptAt:new Date().toISOString()}),h({ok:!0,delivery:await Je.deliver(k.id)})}}if(w.pathname.startsWith("/api/jobs")||w.pathname.startsWith("/api/workers")){let s=o.environments.get(U),g=o.store.listResources(o.project.id,s?.id),I=z.role==="admin"||!!s&&ki(z,s.id,"automation:read")?g:g.filter((L)=>Kt(z,L.id,"automation:read")),A=(L)=>!L||I.some((M)=>M.id===L),v=X(z).actor,D=y.get(U)??E,k=oo(c,D),W=k.filter((L)=>!L.danger&&["scheduler","backup","worker"].includes(L.group)),T=On(c),et=()=>{let L=Bt.resolveSession(S);return!G||!!L&&F.isRecentlyAuthenticated(L)},j=(L)=>{if(!L||typeof L!=="object"||Array.isArray(L))return{};let M=Object.entries(L).slice(0,50);if(M.some(([,ct])=>typeof ct!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(ct)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(M)},K=(L,M,ct)=>o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,resourceId:ct,actorId:v?.id,type:`job.${L}`,payload:M});if(w.pathname==="/api/jobs/preview"&&S.method==="POST"){let L=await B(S);try{return h({ok:!0,productionExecutionCreated:!1,preview:_r(String(L.expression??""),String(L.timezone??"UTC"),new Date(L.from?String(L.from):Date.now()),Number(L.count)||5)})}catch(M){return h({ok:!1,error:M instanceof Error?M.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(w.pathname==="/api/jobs"&&S.method==="GET")return h({ok:!0,jobs:Xt.list(o.project.id,{environmentId:s?.id}).filter((L)=>A(L.resourceId)).map((L)=>({...L,preview:_r(L.normalizedExpression,L.timezone,new Date,5),capability:sa(L),lastExecution:Xt.listExecutions(L.id,1)[0]}))});if(w.pathname==="/api/jobs"&&S.method==="POST"){let L=await B(S),M=String(L.provider??(T==="serverless"?"eventbridge":"server")),ct=T==="serverless"?"eventbridge":"server";if(M!==ct)return h({ok:!1,error:`${T} environments accept ${ct} schedules through this adapter.`},422);let lt=L.operationId?String(L.operationId):void 0;if(M==="server"&&(!lt||!W.some((Nt)=>Nt.id===lt)))return h({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let It=sa({provider:M,expression:String(L.expression??""),flexibleMinutes:Number(L.flexibleMinutes)||0,missedRunPolicy:L.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(L.overlapPolicy))?L.overlapPolicy:"forbid"});if(!It.supported)return h({ok:!1,error:It.notes.join(" ")},422);let Pe=L.resourceId?g.find((Nt)=>Nt.id===L.resourceId||Nt.slug===L.resourceId):void 0;if(L.resourceId&&(!Pe||!A(Pe.id)))return h({ok:!1,error:"Job resource was not found."},404);try{let Nt=M==="server"?{kind:"dashboard_operation",operationId:lt}:{kind:"serverless_scheduler",action:"run"},Fn=Xt.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,resourceId:Pe?.id,name:String(L.name??""),provider:M,expression:String(L.expression??""),timezone:String(L.timezone??"UTC"),startsAt:L.startsAt?String(L.startsAt):void 0,endsAt:L.endsAt?String(L.endsAt):void 0,flexibleMinutes:Number(L.flexibleMinutes)||0,target:Nt,payloadRefs:j(L.payloadRefs),missedRunPolicy:L.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(L.overlapPolicy))?L.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(L.maxAttempts)||3,backoffSeconds:Number(L.backoffSeconds)||30,deadLetterRef:L.deadLetterRef?String(L.deadLetterRef):void 0},timeoutSeconds:Number(L.timeoutSeconds)||900,enabled:L.enabled!==!1,origin:"managed",ownerActorId:v?.id,observedState:{},reconciliationStatus:"pending"});return K("created",{jobId:Fn.id,provider:Fn.provider,expression:Fn.normalizedExpression},Fn.resourceId),h({ok:!0,job:Fn,capability:It},201)}catch(Nt){return h({ok:!1,error:Nt instanceof Error?Nt.message:"Scheduled job could not be created."},422)}}if(w.pathname==="/api/jobs"&&S.method==="PATCH"){let L=await B(S),M=Xt.get(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);if(M.origin==="config")return h({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let ct=L.missedRunPolicy==null?void 0:String(L.missedRunPolicy),lt=L.overlapPolicy==null?void 0:String(L.overlapPolicy);if(ct&&!["skip","catch_up"].includes(ct))return h({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(lt&&!["allow","forbid","replace"].includes(lt))return h({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let It=Xt.updateSchedule(M.id,{expression:L.expression?String(L.expression):void 0,timezone:L.timezone?String(L.timezone):void 0,missedRunPolicy:ct,overlapPolicy:lt,timeoutSeconds:L.timeoutSeconds==null?void 0:Number(L.timeoutSeconds)});return K("updated",{jobId:It.id,expression:It.normalizedExpression,version:It.version},It.resourceId),h({ok:!0,job:It})}catch(It){return h({ok:!1,error:It instanceof Error?It.message:"Scheduled job could not be updated."},422)}}if(w.pathname==="/api/jobs/action"&&S.method==="POST"){let L=await B(S),M=Xt.get(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);let ct=String(L.action??"");if(ct==="run"){let lt=Xl.enqueue(M,{trigger:"manual",actorId:v?.id});return K("run_queued",{jobId:M.id,executionId:lt.id},M.resourceId),h({ok:!0,execution:lt},202)}if(["disable","delete"].includes(ct)&&s?.kind==="production"){if(String(L.confirm??"")!==ct)return h({ok:!1,error:`Type "${ct}" to confirm this production change.`},409);if(!et())return h({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(ct==="enable"||ct==="disable"){let lt=Xt.setEnabled(M.id,ct==="enable");return K(ct==="enable"?"enabled":"disabled",{jobId:M.id},M.resourceId),h({ok:!0,job:lt})}if(ct==="delete")try{return Xt.remove(M.id),K("deleted",{jobId:M.id,name:M.name},M.resourceId),h({ok:!0,deleted:M.id})}catch(lt){return h({ok:!1,error:lt instanceof Error?lt.message:"Scheduled job could not be deleted."},409)}return h({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(w.pathname==="/api/jobs/history"&&S.method==="GET"){let L=Xt.get(String(w.searchParams.get("jobId")??""));if(!L||!A(L.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);return h({ok:!0,executions:Xt.listExecutions(L.id,Number(w.searchParams.get("limit"))||100).map((M)=>({...M,logs:M.operationId?yt.logs(M.operationId,{limit:500}):[]}))})}if(w.pathname==="/api/jobs/reconcile"&&S.method==="POST"){if(!s)return h({ok:!1,error:"Environment was not found."},404);let L=la(Xt,c,{organization:o.organization,project:o.project,environment:s,resources:g});return K("reconciled",L),h({ok:!0,reconciliation:L})}if(w.pathname==="/api/workers"&&S.method==="GET"){let L=Array.isArray(D.workersDetail??D.workers)?D.workersDetail??D.workers:[];return h({ok:!0,workers:Xt.listWorkers(o.project.id,s?.id).filter((M)=>A(M.resourceId)).map((M)=>{let ct=L.find((lt)=>lt.name===M.name||lt.site===M.target.site);return ct?{...M,observedState:{...M.observedState,status:ct.status??"configured",currentJob:ct.currentJob??null,failures:Number(ct.failed??ct.failures)||0,processed:Number(ct.processed)||0}}:M})})}if(w.pathname==="/api/workers/action"&&S.method==="POST"){let L=await B(S),M=Xt.getWorker(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Worker was not found."},404);let ct=String(L.action??"");if(ct==="restart"){if(String(L.confirm??"")!==M.name)return h({ok:!1,error:`Type "${M.name}" to restart this worker.`},409);let lt=k.find((Nt)=>Nt.id===M.target.operationId);if(!lt)return h({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let It=await ao(c,U,lt),Pe=Xt.reconcileWorker(M.id,It.ok?"in_sync":"unavailable",{...M.observedState,lastRestartAt:new Date().toISOString(),command:It.command??null,error:It.error??It.stderr??null});return K("worker_restarted",{workerId:M.id,ok:It.ok},M.resourceId),h({...It,worker:Pe},It.ok?200:409)}if(ct==="scale")return h({ok:!1,error:M.provider==="systemd"?"Systemd worker scale is config-managed; edit the worker definition and reconcile.":"This provider does not expose safe worker scaling through the current adapter."},422);return h({ok:!1,error:"Action must be restart or scale."},422)}}if(w.pathname.startsWith("/api/telemetry/")){let s=o.environments.get(U),g=new uo(o.store),_=o.store.listResources(o.project.id,s?.id),I=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(w.pathname)?"runtime:logs":"runtime:read",A=z.role==="admin"||!!s&&ki(z,s.id,I),v=A?_:_.filter((j)=>Kt(z,j.id,I)),D=(j)=>dR(v,A,j),k=(j)=>{let K=new Date,L={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},M=String(j.to??K.toISOString()),ct=String(j.from??new Date(new Date(M).getTime()-(L[String(j.range??"1h")]??L["1h"])).toISOString()),lt=(Pe)=>{let Nt=(Array.isArray(Pe)?Pe:String(Pe??"").split(",")).map(String).filter(Boolean);return Nt.length?Nt:void 0},It=lt(j.kinds)?.filter((Pe)=>["metric","log","trace","request","event"].includes(Pe));return{projectId:o.project.id,environmentId:s?.id,resourceIds:D(j.resources),kinds:It,names:lt(j.names),sources:lt(j.sources),levels:lt(j.levels),from:ct,to:M,text:String(j.text??"")||void 0,traceId:String(j.traceId??"")||void 0,requestId:String(j.requestId??"")||void 0,deploymentId:String(j.deploymentId??"")||void 0,releaseId:String(j.releaseId??"")||void 0,workloadId:String(j.workloadId??"")||void 0,cursor:String(j.cursor??"")||void 0,limit:Number(j.limit)||void 0}},W=Object.fromEntries(w.searchParams.entries()),T=(j=!1)=>Ll({controlPlane:o.store,projectId:o.project.id,environmentId:s?.id,config:c,environment:U,force:j,lightweight:!j}),et=()=>{let j=o.store.getSetting(`telemetry.collection:${o.project.id}:${s?.id??"all"}`)??{};return{generatedAt:String(j.generatedAt??new Date().toISOString()),cached:!0,statuses:Array.isArray(j.statuses)?j.statuses:[],errors:Array.isArray(j.errors)?j.errors:[],policy:j.policy??ac(o.store,o.project.id)}};if(w.pathname==="/api/telemetry/status"&&S.method==="GET"){T(!1);let j=et(),K=A?j.statuses:g.status(o.project.id,s?.id,j.policy.rawDays,j.policy.samplingRate,v.map((M)=>M.id)),L=K.reduce((M,ct)=>M+ct.estimatedDailyBytes*30,0);return h({ok:!0,generatedAt:j.generatedAt,cached:j.cached,sources:K,errors:A?j.errors:[],policy:j.policy,retention:{rawDays:j.policy.rawDays,downsampleAfterDays:j.policy.downsampleAfterDays,downsampleBucketMs:j.policy.downsampleBucketMs,maxRecords:j.policy.maxRecords},estimatedMonthlyBytes:L,estimatedMonthlyCostUsd:YR(L,j.policy),costEstimateConfigured:j.policy.estimatedStorageUsdPerGbMonth>0})}if(w.pathname==="/api/telemetry/settings"&&S.method==="GET")return h({ok:!0,policy:ac(o.store,o.project.id)});if(w.pathname==="/api/telemetry/settings"&&S.method==="PATCH"){let j=ZR(o.store,o.project.id,await B(S));return SR(o.project.id),h({ok:!0,policy:j})}if(w.pathname==="/api/telemetry/query"&&S.method==="GET"){T(!1);let j=et();return h({ok:!0,collection:{generatedAt:j.generatedAt,cached:j.cached},...g.query(k(W))})}if(w.pathname==="/api/telemetry/tail"&&S.method==="GET"){T(!1);let j=new TextEncoder,K=new Date,L=k({...W,kinds:W.kinds||"log,request,event,trace",from:W.from||new Date(K.getTime()-120000).toISOString(),to:K.toISOString(),limit:Math.min(1000,Number(W.limit)||200),cursor:void 0}),M=S.headers.get("last-event-id")||String(W.cursor??"")||void 0,ct,lt=!1,It=!1,Pe=new ReadableStream({start(Nt){let Fn=()=>{if(lt)return;if(lt=!0,ct)clearInterval(ct);S.signal.removeEventListener("abort",Fn);try{Nt.close()}catch{}},ag=async()=>{if(lt||It)return;It=!0;try{let or=g.tail({...L,to:new Date(Date.now()+1000).toISOString()},M);for(let sg of or.records)M=XR(sg)??M,Nt.enqueue(j.encode(`id: ${M??""}
501
501
  event: record
502
502
  data: ${JSON.stringify(sg)}
503
503
 
@@ -508,5 +508,5 @@ data: ${JSON.stringify({message:or instanceof Error?or.message:String(or)})}
508
508
  data: ${JSON.stringify({cursor:M,at:new Date().toISOString()})}
509
509
 
510
510
  `))},5000),ct.unref?.(),S.signal.addEventListener("abort",Fn,{once:!0})},cancel(){if(lt=!0,ct)clearInterval(ct)}});return new Response(Pe,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}if(w.pathname==="/api/telemetry/series"&&S.method==="GET"){T(!1);let j=et(),K=["sum","avg","min","max","count","p50","p90","p95","p99"].includes(String(W.aggregation))?W.aggregation:"avg",L=k({...W,kinds:"metric",limit:5000}),M=g.series({...L,bucketMs:Number(W.bucketMs)||60000,aggregation:K,timezone:String(W.timezone??"UTC"),compareFrom:W.compareFrom,compareTo:W.compareTo});return h({ok:!0,collection:{generatedAt:j.generatedAt,cached:j.cached},query:{aggregation:K,bucketMs:Number(W.bucketMs)||60000,timezone:String(W.timezone??"UTC")},series:M})}if(w.pathname==="/api/telemetry/refresh"&&S.method==="POST")return h({ok:!0,...await T(!0)});if(w.pathname==="/api/telemetry/export"&&S.method==="POST"){let j=await B(S);await T(!1);let K=g.query({...k(j),limit:Math.min(5000,Number(j.limit)||5000),cursor:void 0});if((j.format==="csv"?"csv":"json")==="json")return new Response(JSON.stringify({exportedAt:new Date().toISOString(),query:k(j),...K},null,2),{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.json"',"content-type":"application/json; charset=utf-8"}});let M=["timestamp","kind","source","name","level","value","unit","message","traceId","requestId","deploymentId","releaseId","workloadId"],ct=[M.join(","),...K.records.map((lt)=>M.map((It)=>`"${String(lt[It]??"").replaceAll('"','""')}"`).join(","))].join(`
511
- `);return new Response(ct,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="GET"){let j=X(z);return h({ok:!0,queries:g.listSavedQueries(o.project.id,j.actor?.id)})}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="POST"){let j=await B(S),K=X(z);return h({ok:!0,query:g.saveQuery(o.project.id,K.actor?.id,String(j.name??""),k(j.query??j))},201)}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="DELETE"){let j=await B(S),K=X(z),L=g.deleteSavedQuery(o.project.id,K.actor?.id,String(j.id??""));return h({ok:L},L?200:404)}}if(w.pathname.startsWith("/api/configuration")){let s=o.environments.get(U),g=z.role==="admin"||!!Be.capabilities?.includes("secrets:read"),_=z.role==="admin"||!!Be.capabilities?.includes("secrets:write"),I={projectId:o.project.id,environmentId:s?.id},A={"cache-control":"no-store"};if(w.pathname==="/api/configuration"&&S.method==="GET"){let v=Object.fromEntries(w.searchParams),D=v.scopeType||v.scopeId?Di(v,I):void 0,k=["variable","secret"].includes(String(v.kind))?v.kind:void 0,W=D?.type==="preview"?Ht.previews.getInstance(D.id):void 0,T=W?Ht.previews.getDefinition(W.definitionId):void 0,et=D?await we.resolve({projectId:o.project.id,environmentId:D.environmentId,resourceId:D.resourceId,functionId:D.type==="function"?D.id:void 0,previewId:D.previewId,trustedPreview:!!W&&!W.fork,allowedPreviewSecrets:T?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:g}):void 0,j=o.store.listResources(o.project.id);return h({ok:!0,entries:we.list({projectId:o.project.id,scope:D,kind:k,search:v.search,canReadSecretMetadata:g}),effectiveEntries:et?Object.values(et.entries).filter((K)=>!k||K.kind===k).filter((K)=>!v.search||K.key.toLowerCase().includes(String(v.search).toLowerCase())):[],configurationHash:et?.configurationHash,warnings:et?.warnings??[],scopes:{project:o.project,environments:o.store.listEnvironments(o.project.id),resources:j.filter((K)=>K.kind!=="function"),functions:j.filter((K)=>K.kind==="function"),previews:Ht.previews.listInstances({projectId:o.project.id}).filter((K)=>K.status!=="destroyed").map((K)=>({id:K.id,name:K.name,environmentId:K.baseEnvironmentId,resourceId:K.resourceId,fork:K.fork,status:K.status}))}},200,A)}if(w.pathname==="/api/configuration/export"&&S.method==="GET"){let v=Di(Object.fromEntries(w.searchParams),I);return new Response(we.exportVariables({projectId:o.project.id,scope:v}),{headers:{...A,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(w.pathname==="/api/configuration/plan"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=v.values&&typeof v.values==="object"&&!Array.isArray(v.values)?Object.fromEntries(Object.entries(v.values).map(([W,T])=>[W,String(T)])):{};return h({ok:!0,plan:we.plan({projectId:o.project.id,scope:D,values:k,removeMissing:v.removeMissing===!0})},200,A)}if(w.pathname==="/api/configuration"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=v.kind==="secret"?"secret":"variable",W=String(v.key??"");if(k==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let T=await we.set({organizationId:o.organization.id,projectId:o.project.id,scope:D,key:W,kind:k,value:v.value==null?void 0:String(v.value),reference:v.reference==null?void 0:String(v.reference),backend:v.backend,required:v.required===!0,expectedVersion:v.expectedVersion==null?void 0:Number(v.expectedVersion),confirmed:String(v.confirm??"")===W,idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey,actorId:X(z).actor?.id});return h({ok:!0,entry:we.list({projectId:o.project.id,scope:D,canReadSecretMetadata:g}).find((et)=>et.id===T.entry.id),mutation:T.mutation,warnings:T.warnings},T.mutation.added.length?201:200,A)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T)},409,A)}}if(w.pathname==="/api/configuration/import"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=Array.isArray(v.secretKeys)?v.secretKeys.map(String):[];if(k.length&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let W=await we.importDotenv({organizationId:o.organization.id,projectId:o.project.id,scope:D,source:String(v.source??""),secretKeys:k,backend:v.backend,confirmed:v.confirm==="import",idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey,actorId:X(z).actor?.id});return h({ok:W.document.valid,diagnostics:W.document.diagnostics,mutation:W.mutation,warnings:W.warnings},W.document.valid?200:422,A)}catch(W){return h({ok:!1,error:W instanceof Error?W.message:String(W)},409,A)}}if(w.pathname==="/api/configuration/dependencies"&&S.method==="POST"){let v=await B(S),D=Wn.get(String(v.entryId??"")),k=o.store.getResource(String(v.resourceId??""));if(!D||D.projectId!==o.project.id||!k||k.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry or dependent resource was not found."},404,A);return h({ok:!0,dependency:Wn.setDependency({entryId:D.id,resourceId:k.id,injectionTarget:["native_reference","file"].includes(String(v.injectionTarget))?v.injectionTarget:"environment",required:v.required!==!1,requiresRedeploy:v.requiresRedeploy!==!1,lastDeployedVersion:v.lastDeployedVersion==null?void 0:Number(v.lastDeployedVersion)})},200,A)}if(w.pathname==="/api/configuration/transfer"&&S.method==="POST"){let v=await B(S),D=Wn.get(String(v.id??"")),k=Di({...v,scopeType:v.targetScopeType,scopeId:v.targetScopeId},I);if(!D||D.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry was not found."},404,A);if(D.kind==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let W=await we.transfer({entryId:D.id,targetScope:k,mode:v.mode==="move"?"move":"copy",confirmed:v.confirm===D.key,actorId:X(z).actor?.id,idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey});return h({ok:!0,entry:we.list({projectId:o.project.id,scope:k,canReadSecretMetadata:g}).find((T)=>T.id===W.entry.id),mutation:W.mutation},200,A)}catch(W){return h({ok:!1,error:W instanceof Error?W.message:String(W)},409,A)}}if(w.pathname==="/api/configuration/bulk"&&S.method==="POST"){let v=await B(S),D=Array.isArray(v.ids)?v.ids.map(String).slice(0,500):[],k=D.map((T)=>Wn.get(T)).filter((T)=>!!T&&T.projectId===o.project.id);if(k.length!==D.length)return h({ok:!1,error:"One or more configuration entries were not found."},404,A);if(k.some((T)=>T.kind==="secret")&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);if(v.action!=="delete"||v.confirm!=="bulk")return h({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,A);let W=[];try{for(let T of k)W.push(await we.remove({entryId:T.id,expectedVersion:T.version,confirmed:!0,actorId:X(z).actor?.id}));return h({ok:!0,removed:W.flatMap((T)=>T.removed),affectedResourceIds:[...new Set(W.flatMap((T)=>T.affectedResourceIds))].sort()},200,A)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T),partial:W.flatMap((et)=>et.removed)},409,A)}}if(w.pathname==="/api/configuration/reveal"&&S.method==="POST"){let v=await B(S),D=Bt.resolveSession(S);try{return h({ok:!0,value:await we.reveal({entryId:String(v.id??""),canRevealSecrets:g,recentlyAuthenticated:!G||!!D&&F.isRecentlyAuthenticated(D),actorId:X(z).actor?.id})},200,A)}catch(k){return h({ok:!1,error:k instanceof Error?k.message:String(k)},403,A)}}if(w.pathname==="/api/configuration"&&S.method==="DELETE"){let v=await B(S),D=Wn.get(String(v.id??""));if(D?.kind==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);if(!D||D.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry was not found."},404,A);try{return h({ok:!0,mutation:await we.remove({entryId:D.id,expectedVersion:Number(v.expectedVersion),confirmed:String(v.confirm??"")===D.key,actorId:X(z).actor?.id})},200,A)}catch(k){return h({ok:!1,error:k instanceof Error?k.message:String(k)},409,A)}}}if(w.pathname.startsWith("/api/fleet")){let s=X(z).actor?.id,g=(_,I=409)=>h({ok:!1,error:_ instanceof Error?_.message:String(_)},I,{"cache-control":"no-store"});if(w.pathname==="/api/fleet"&&S.method==="GET")return h({ok:!0,servers:vi.list(o.project.id),resources:o.store.listResources(o.project.id),operations:yt.list({projectId:o.project.id,limit:200}).filter((_)=>_.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(w.pathname==="/api/fleet"&&S.method==="POST"){let _=await B(S);try{return h({ok:!0,server:en.enroll({organizationId:o.organization.id,projectId:o.project.id,name:String(_.name??""),provider:["aws","hetzner"].includes(String(_.provider))?_.provider:"ssh",providerId:_.providerId?String(_.providerId):void 0,region:_.region?String(_.region):void 0,zone:_.zone?String(_.zone):void 0,endpoint:String(_.endpoint??""),sshUser:String(_.sshUser??"deploy"),sshPort:_.sshPort?Number(_.sshPort):22,credentialRef:String(_.credentialRef??""),roles:Array.isArray(_.roles)?_.roles:[],labels:_.labels&&typeof _.labels==="object"?_.labels:{}})},201)}catch(I){return g(I,422)}}if(w.pathname==="/api/fleet/action"&&S.method==="POST"){let _=await B(S),I=String(_.id??""),A=String(_.action??"");try{if(A==="test")return h({ok:!0,server:await en.test(I)});if(A==="validate")return h({ok:!0,server:await en.validate(I)});if(A==="review_host_key")return h({ok:!0,server:en.reviewHostKey(I,String(_.fingerprint??""))});if(A==="bootstrap")return h({ok:!0,...en.bootstrap(I,_.confirmed===!0)},_.confirmed===!0?202:200);if(A==="heartbeat")return h({ok:!0,server:en.heartbeat(I,{usage:_.usage&&typeof _.usage==="object"?_.usage:{}})});if(A==="drain")return h({ok:!0,server:en.drain(I,_.completed===!0)});if(A==="uncordon")return h({ok:!0,server:en.uncordon(I)});if(A==="archive")return h({ok:!0,server:en.archive(I,String(_.confirmation??""))});return g("Unsupported fleet action.",422)}catch(v){return g(v)}}}if(w.pathname.startsWith("/api/capacity")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/capacity"&&S.method==="GET")return h({ok:!0,pools:jn.listPools(o.project.id),placements:jn.listPlacements(o.project.id),servers:vi.list(o.project.id)},200,{"cache-control":"no-store"});if(w.pathname==="/api/capacity"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,pool:jn.createPool({organizationId:o.organization.id,projectId:o.project.id,name:String(g.name??""),purpose:String(g.purpose??"application"),backend:String(g.backend??"server"),region:g.region?String(g.region):void 0,architecture:g.architecture?String(g.architecture):void 0,labels:g.labels&&typeof g.labels==="object"?g.labels:{},requiredServerLabels:g.requiredServerLabels&&typeof g.requiredServerLabels==="object"?g.requiredServerLabels:{},toleratedTaints:Array.isArray(g.toleratedTaints)?g.toleratedTaints.map(String):[],capacity:g.capacity&&typeof g.capacity==="object"?g.capacity:{},maxWorkloads:Number(g.maxWorkloads??10),costWeight:Number(g.costWeight??1),spreadKey:g.spreadKey?String(g.spreadKey):void 0,concurrency:Number(g.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/member"&&S.method==="POST"){let g=await B(S);try{return jn.addMember(String(g.poolId??""),String(g.serverId??"")),h({ok:!0,pool:jn.getPool(String(g.poolId??""))})}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/explain"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,decisions:Gl.explain(o.project.id,{purpose:String(g.purpose??"application"),resources:g.resources&&typeof g.resources==="object"?g.resources:{},region:g.region?String(g.region):void 0,architecture:g.architecture?String(g.architecture):void 0,labels:g.labels&&typeof g.labels==="object"?g.labels:{}})})}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/action"&&S.method==="POST"){let g=await B(S);try{if(g.action==="drain")return h({ok:!0,...Gl.drainPool(String(g.poolId??""))});if(g.action==="enable")return h({ok:!0,pool:jn.updatePool(String(g.poolId??""),{status:"active"})});if(g.action==="disable")return h({ok:!0,pool:jn.updatePool(String(g.poolId??""),{status:"disabled"})});return s("Unsupported capacity action.",422)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/regions")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/regions"&&S.method==="GET")return h({ok:!0,topologies:cr.list(o.project.id).map((g)=>({topology:g,targets:cr.targets(g.id),channels:cr.channels(g.id),route:cr.route(g.id),executions:cr.executions(g.id)}))},200,{"cache-control":"no-store"});if(w.pathname==="/api/regions"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,topology:Zl.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:o.environments.get(U)?.id,name:String(g.name??""),hostname:String(g.hostname??""),regions:Array.isArray(g.regions)?g.regions:[],trafficPolicy:g.trafficPolicy==="weighted"||g.trafficPolicy==="latency"?g.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(g.replicate)?g.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(g.maxLagSeconds??30),retainOnDestroy:g.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:g.cdnEnabled===!0,wafEnabled:g.wafEnabled===!0})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/regions/action"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Zl.enqueue({topologyId:String(g.topologyId??""),kind:String(g.action??""),targetRegion:g.targetRegion?String(g.targetRegion):void 0,revision:g.revision?String(g.revision):void 0,manifest:g.manifest&&typeof g.manifest==="object"?g.manifest:{},confirmation:g.confirmation?String(g.confirmation):void 0,deleteData:g.deleteData===!0})},202)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/maintenance")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/maintenance"&&S.method==="GET")return h({ok:!0,manifests:hn.manifests(o.organization.id),windows:hn.windows(o.project.id),campaigns:hn.campaigns(o.project.id).map((g)=>({campaign:g,targets:hn.targets(g.id)})),cleanups:hn.cleanups(o.project.id),drills:hn.drills(o.project.id)},200,{"cache-control":"no-store"});if(w.pathname==="/api/maintenance/cleanup-preview"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,plan:await Do.previewCleanup({projectId:o.project.id,kind:String(g.kind??"operations"),criteria:{olderThanDays:Number(g.olderThanDays??30)}},Yl)},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/cleanup-apply"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Do.enqueueCleanup(String(g.planId??""),String(g.confirmation??""))},202)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/drill"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,drill:hn.createDrill({projectId:o.project.id,scenario:String(g.scenario??"control_plane"),isolatedTarget:String(g.isolatedTarget??""),expectedRpoMinutes:Number(g.expectedRpoMinutes??60),expectedRtoMinutes:Number(g.expectedRtoMinutes??30),recoveryPointId:g.recoveryPointId?String(g.recoveryPointId):void 0,topologyId:g.topologyId?String(g.topologyId):void 0})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/drill-run"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Do.enqueueDrill(String(g.drillId??""))},202)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/volumes")){let s=o.environments.get(U),g=X(z).actor?.id,_=(I,A=409)=>h({ok:!1,error:I instanceof Error?I.message:String(I)},A,{"cache-control":"no-store"});if(w.pathname==="/api/volumes"&&S.method==="GET"){let I=wo.inventory(o.project.id,s?.id),A=o.store.listResources(o.project.id,s?.id).map((v)=>({id:v.id,name:v.name,slug:v.slug,kind:v.kind,provider:v.provider,providerId:v.providerId}));return h({ok:!0,volumes:I,resources:A,operations:yt.list({projectId:o.project.id,limit:100}).filter((v)=>v.operation.kind.startsWith("volume.")),recoveryPoints:Ft.listRecoveryPoints(o.project.id).filter((v)=>v.kind==="volume"),providers:Ao.map((v)=>({provider:v.provider,type:v.type,capabilities:v.capabilities()}))},200,{"cache-control":"no-store"})}if(w.pathname==="/api/volumes"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,resourceId:I.resourceId?String(I.resourceId):void 0,name:String(I.name??""),provider:String(I.provider??"docker"),type:I.type==="docker"?"docker":I.type,capacityBytes:I.capacityBytes==null?void 0:Number(I.capacityBytes),filesystem:I.filesystem?String(I.filesystem):void 0,encrypted:I.encrypted===!0,desiredState:I.desiredState&&typeof I.desiredState==="object"?I.desiredState:{},actorId:g})},202,{"cache-control":"no-store"})}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/attach"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.attach(String(I.volumeId??""),{resourceId:String(I.resourceId??""),targetPath:String(I.targetPath??""),readOnly:I.readOnly===!0,uid:I.uid==null?void 0:Number(I.uid),gid:I.gid==null?void 0:Number(I.gid),mode:I.mode?String(I.mode):void 0,propagation:I.propagation,driverOptions:I.driverOptions&&typeof I.driverOptions==="object"?I.driverOptions:{},actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/detach"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.detach(String(I.volumeId??""),String(I.attachmentId??""),{force:I.force===!0,drained:I.drained===!0,unmounted:I.unmounted===!0,confirmation:I.confirmation?String(I.confirmation):void 0,actorId:g})},202)}catch(A){return _(A)}}if(w.pathname==="/api/volumes/resize"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.resize(String(I.volumeId??""),Number(I.capacityBytes),{drained:I.drained===!0,actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/snapshot"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.snapshot(String(I.volumeId??""),{name:I.name?String(I.name):void 0,actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/restore"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.restore(String(I.snapshotId??""),{name:String(I.name??""),actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/discover"&&S.method==="POST")try{return h({ok:!0,volumes:await un.discover({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,actorId:g})})}catch(I){return _(I,502)}if(w.pathname==="/api/volumes/adopt"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,volume:un.adopt(String(I.volumeId??""),{name:String(I.name??""),actorId:g})})}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes"&&S.method==="DELETE"){let I=await B(S),A=Bt.resolveSession(S);try{return h({ok:!0,...un.delete(String(I.volumeId??""),{recentAuthAt:!G||A&&F.isRecentlyAuthenticated(A)?new Date().toISOString():void 0,confirmation:I.confirmation?String(I.confirmation):void 0,backupOverride:I.backupOverride===!0,backupOverrideConfirmation:I.backupOverrideConfirmation?String(I.backupOverrideConfirmation):void 0,actorId:g})},202)}catch(v){return _(v)}}}if(w.pathname==="/api/backups"&&S.method==="GET"){let s=o.environments.get(U),g=Ft.listPolicies(o.project.id,s?.id),_=new Set(g.map((k)=>k.id)),I=Ft.listRecoveryPoints(o.project.id).filter((k)=>!k.policyId||_.has(k.policyId)),A=Ft.listJobs(o.project.id).filter((k)=>!k.policyId||_.has(k.policyId)),v=(k)=>({...k,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!k.credentialRef,clientEncryptionConfigured:!!k.encryptionKeyRef}),D=await Promise.all(Ft.listDestinations(o.project.id).map(async(k)=>({...v(k),credentialStatus:await Wu(k,gn)})));return h({ok:!0,destinations:D,policies:g,recoveryPoints:I,jobs:A,coverage:Ft.coverage(o.project.id).filter((k)=>_.has(k.policy.id)),resources:s?o.store.listResources(o.project.id,s.id).map((k)=>({id:k.id,name:k.name,slug:k.slug,kind:k.kind})):[]})}if(w.pathname==="/api/backups/destinations"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim(),_=String(s.provider??""),I=String(s.encryption??"provider"),A=`secret://data-services/backups/${o.project.id}/${g}`,v=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(_))return h({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(I))return h({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let D,k;if(s.credentials&&typeof s.credentials==="object"&&!Array.isArray(s.credentials))D=`${A}/credentials`,await gn.put(D,JSON.stringify(s.credentials)),v.push(D);if(I!=="provider"){let T=String(s.encryptionKey??"");if(T.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");k=`${A}/encryption-key`,await gn.put(k,T),v.push(k)}let W=Ft.createDestination({organizationId:o.organization.id,projectId:o.project.id,name:g,provider:_,endpoint:s.endpoint?String(s.endpoint):void 0,endpointPolicy:s.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:s.bucket?String(s.bucket):void 0,prefix:String(s.prefix??""),region:s.region?String(s.region):Un,forcePathStyle:s.forcePathStyle===!0,credentialRef:D,encryption:I,encryptionKeyRef:k,immutability:s.immutability&&typeof s.immutability==="object"&&!Array.isArray(s.immutability)?s.immutability:{},status:"untested"});return h({ok:!0,destination:{...W,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!D,clientEncryptionConfigured:!!k}},201)}catch(D){for(let k of v)await gn.remove(k).catch(()=>{});return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}if(w.pathname==="/api/backups/destinations/test"&&S.method==="POST"){let s=await B(S),g=Ft.getDestination(String(s.id??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Backup destination was not found."},404);if(g.provider==="aws_backup")return h({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await Ql.test(g),h({ok:!0,destination:Ft.recordDestinationTest(g.id,{ok:!0})})}catch(_){let I=_ instanceof Error?_.message:String(_);return Ft.recordDestinationTest(g.id,{ok:!1,error:I}),h({ok:!1,error:I},502)}}if(w.pathname==="/api/backups/policies"&&S.method==="POST"){let s=await B(S),g=o.environments.get(U),_=Ft.getDestination(String(s.destinationId??"")),I=String(s.resourceKind??""),A=s.dataServiceId?String(s.dataServiceId):void 0,v=A?kt.get(A):void 0,D=s.resourceId?String(s.resourceId):void 0,k=D?o.store.getResource(D):void 0;if(!g)return h({ok:!1,error:"Environment was not found."},404);if(!_||_.projectId!==o.project.id)return h({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(I))return h({ok:!1,error:"A supported backup resource kind is required."},422);if(A&&(!v||v.projectId!==o.project.id||v.environmentId!==g.id))return h({ok:!1,error:"Data service was not found in this environment."},404);if(D&&(!k||k.projectId!==o.project.id||k.environmentId!==g.id))return h({ok:!1,error:"Resource was not found in this environment."},404);if(I==="managed_database"&&!v)return h({ok:!1,error:"Managed database policies require a data service."},422);if(I==="logical_database"&&(!v||!["container","server"].includes(v.provider)))return h({ok:!1,error:"Logical database policies require an on-box data service."},422);if(I==="volume"&&(!k||!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(String(s.volumeName??""))))return h({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let W=Array.isArray(s.includePatterns)?s.includePatterns.map(String).filter(Boolean):[];if(I==="files"&&(!k||!W.length))return h({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(I==="control_plane"&&_.encryption==="provider")return h({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(I==="infrastructure"&&(_.provider!=="aws_backup"||!W.some((T)=>T.startsWith("resource:arn:"))||!W.some((T)=>T.startsWith("role:arn:"))))return h({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let T=Ft.createPolicy({organizationId:o.organization.id,projectId:o.project.id,environmentId:g.id,resourceId:D,dataServiceId:A,destinationId:_.id,name:String(s.name??"").trim(),resourceKind:I,schedule:String(s.schedule??"daily"),timezone:String(s.timezone??"UTC"),retention:s.retention&&typeof s.retention==="object"&&!Array.isArray(s.retention)?s.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(s.compression))?s.compression:"gzip",encryption:["destination","client_side","both"].includes(String(s.encryption))?s.encryption:"destination",includePatterns:I==="volume"?[String(s.volumeName),...W]:W,excludePatterns:Array.isArray(s.excludePatterns)?s.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(s.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(s.expectedRtoMinutes)||120),healthCheckId:s.healthCheckId?String(s.healthCheckId):void 0,enabled:s.enabled!==!1});return h({ok:!0,policy:T},201)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T)},422)}}if(w.pathname==="/api/backups/run"&&S.method==="POST"){let s=await B(S),g=Ft.getPolicy(String(s.policyId??"")),_=o.environments.get(U);if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Backup policy was not found in this environment."},404);try{let I=ir.enqueueBackup(g,new Date().toISOString(),X(z).actor?.id);return h({ok:!0,job:I},202)}catch(I){return h({ok:!1,error:I instanceof Error?I.message:String(I)},409)}}if(w.pathname==="/api/backups/verify"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.recoveryPointId??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);return h({ok:!0,job:ir.enqueueVerification(g)},202)}if(w.pathname==="/api/backups/restore"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.recoveryPointId??"")),_=s.mode==="in_place"?"in_place":"isolated",I=s.target&&typeof s.target==="object"&&!Array.isArray(s.target)?{...s.target,inPlace:_==="in_place"}:{inPlace:_==="in_place"},A=Bt.resolveSession(S),v={mode:_,target:I,targetName:String(s.targetName??""),confirm:s.confirm?String(s.confirm):void 0,recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A),downtimeAcknowledged:s.downtimeAcknowledged===!0,safetyBackupId:s.safetyBackupId?String(s.safetyBackupId):void 0};if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);if(s.drill===!0&&_!=="isolated")return h({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let D=ir.planRestore(g,v);if(s.execute!==!0)return h({ok:!0,plan:D,executionCreated:!1});let k=ir.enqueueRestore(g,{...v,drill:s.drill===!0,actorId:X(z).actor?.id});return h({ok:!0,plan:D,job:k},202)}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},409)}}if(w.pathname==="/api/backups/recovery-points"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.id??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);if(s.held==null&&s.pinned==null)return h({ok:!1,error:"held or pinned must be provided."},422);return h({ok:!0,recoveryPoint:Ft.updateRecoveryPoint(g.id,{held:s.held==null?g.held:s.held===!0,pinned:s.pinned==null?g.pinned:s.pinned===!0})})}if(w.pathname==="/api/backups/retention"&&S.method==="POST")return h({ok:!0,jobs:ir.enqueueRetention()},202);if(w.pathname==="/api/data-services/capabilities"&&S.method==="GET"){let s=String(w.searchParams.get("engine")??""),g=String(w.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(s)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(g))return h({ok:!1,error:"A supported engine and provider are required."},422);return h({ok:!0,engine:s,provider:g,capabilities:Li(s,g)})}if(w.pathname==="/api/data-services"&&S.method==="GET"){let s=o.environments.get(U),g=kt.list(o.project.id,s?.id).map((_)=>{let I=kt.credential(_.id);return{..._,credentialRef:void 0,credential:I?{configured:!0,username:I.username,version:I.version,rotatedAt:I.rotatedAt}:void 0,dependencies:kt.dependencies(_.id).map((A)=>({resourceId:A.resourceId,requiresRedeploy:A.requiresRedeploy}))}});return h({ok:!0,services:g})}if(w.pathname==="/api/data-services/preview"&&S.method==="POST"){let s=await B(S);if(s.id){let I=kt.get(String(s.id)),A=o.environments.get(U),v=String(s.action??"");if(!I||I.projectId!==o.project.id||I.environmentId!==A?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!_o.includes(v))return h({ok:!1,error:`Action must be one of: ${_o.join(", ")}.`},422);try{return h({ok:!0,plan:hc.plan(I,v,s.changes??{})})}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}let g=String(s.engine??""),_=String(s.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(g)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(_))return h({ok:!1,error:"A supported engine and provider are required."},422);return h({ok:!0,capabilities:Li(g,_),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(w.pathname==="/api/data-services"&&S.method==="POST"){let s=await B(S),g=String(s.engine??""),_=String(s.provider??""),I=o.environments.get(U),A=X(z);if(!I)return h({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(g)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(_))return h({ok:!1,error:"A supported engine and provider are required."},422);let v={organizationId:o.organization.id,projectId:o.project.id,environmentId:I.id,resourceId:s.resourceId?String(s.resourceId):void 0,name:String(s.name??"").trim(),engine:g,provider:_,placement:String(s.placement??s.name??"").trim(),engineVersion:s.engineVersion?String(s.engineVersion):void 0,plan:String(s.plan??(_==="aws_elasticache"?"cache.t4g.micro":_==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:s.storageGb==null?void 0:Number(s.storageGb),highAvailability:s.highAvailability===!0,publicExposure:s.publicExposure===!0,allowedCidrs:Array.isArray(s.allowedCidrs)?s.allowedCidrs.map(String):[],desiredState:s.desiredState&&typeof s.desiredState==="object"&&!Array.isArray(s.desiredState)?s.desiredState:{},observedState:{},origin:s.adopt===!0?"adopted":"managed",managementEnabled:s.adopt!==!0,ownerActorId:A.actor?.id,username:s.username?String(s.username):void 0};try{if(s.adopt===!0){let k=kt.create({...v,status:"adopted",credentialRef:void 0});return h({ok:!0,service:k,readOnly:!0},201)}if(!Ml({provider:_,engine:g}))return h({ok:!1,error:`No ${_}/${g} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let D=await hc.create(v);return h({ok:!0,service:D.service,operationId:D.operationId,oneTimeCredential:D.credential},201)}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}if(w.pathname==="/api/data-services/connections"&&S.method==="GET"){let s=kt.get(String(w.searchParams.get("id")??"")),g=o.environments.get(U);if(!s||s.projectId!==o.project.id||s.environmentId!==g?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);let _=typeof s.observedState.endpoint==="string"?s.observedState.endpoint:void 0,I=typeof s.observedState.readerEndpoint==="string"?s.observedState.readerEndpoint:void 0,A=Number(s.observedState.port)||(s.engine==="postgres"?5432:s.engine==="redis"?6379:s.engine==="mongodb"?27017:s.engine==="libsql"?8080:3306),v=typeof s.observedState.database==="string"?s.observedState.database:void 0,D=typeof s.observedState.tls==="boolean"?s.observedState.tls:s.provider.startsWith("aws_"),k=[..._?[{type:s.publicExposure?"external":"internal",host:_,port:A,database:v,tls:D}]:[],...I?[{type:"internal",host:I,port:A,database:v,tls:D}]:[],{type:"tunnel",host:_??s.placement,port:A,database:v,tls:D}];return h({ok:!0,serviceId:s.id,guidance:Lu(s,k)})}if(w.pathname==="/api/data-services/action"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=String(s.action??"");if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!_o.includes(I))return h({ok:!1,error:`Action must be one of: ${_o.join(", ")}.`},422);let A=s.changes&&typeof s.changes==="object"&&!Array.isArray(s.changes)?s.changes:{};try{let v=hc.plan(g,I,A);if(s.execute!==!0)return h({ok:!0,plan:v,productionExecutionCreated:!1});let D=hc.enqueue(g,I,A,X(z).actor?.id);return h({ok:!0,plan:v,operationId:D},202)}catch(v){return h({ok:!1,error:v instanceof Error?v.message:String(v)},409)}}if(w.pathname==="/api/data-services/dependencies"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=o.store.getResource(String(s.resourceId??""));if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!I||I.projectId!==o.project.id||I.environmentId!==_?.id)return h({ok:!1,error:"Dependent resource was not found in this environment."},404);if(s.remove===!0)return h({ok:kt.removeDependency(g.id,I.id)});return kt.addDependency({serviceId:g.id,resourceId:I.id,secretRef:g.credentialRef??`secret://data-services/${g.projectId}/${g.name}`,requiresRedeploy:s.requiresRedeploy!==!1}),h({ok:!0,dependencies:kt.dependencies(g.id).map((A)=>({resourceId:A.resourceId,requiresRedeploy:A.requiresRedeploy}))})}if(w.pathname==="/api/data-services/management"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U);if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(g.origin!=="adopted"||s.reviewed!==!0||s.confirm!==g.name)return h({ok:!1,error:`Enabling management requires reviewed=true and typing ${g.name}.`},409);return h({ok:!0,service:kt.update(g.id,g.version,{managementEnabled:!0})})}if(w.pathname==="/api/data-services/reveal"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=g?kt.credential(g.id):void 0;if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!I)return h({ok:!1,error:"No managed credential is configured."},404);return h({ok:!0,credential:{username:I.username,password:await gn.resolve(I.secretRef),version:I.version}},200,{"cache-control":"no-store"})}if(w.pathname==="/api/databases"&&S.method==="GET")return h(await Tf(c,U));if(w.pathname==="/api/databases"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim();if(!zn(g))return h({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return h({...await bf(c,U,g),name:g})}if(w.pathname==="/api/databases/vitess"&&S.method==="GET"){let s=await Hf(c,U);return h({...s,unhealthy:Lf(s.tablets),missingPrimary:Ff(s)})}if(w.pathname==="/api/databases/vitess/provision"&&S.method==="POST"){let s=await B(S);try{return h(await pf(c,U,{keyspace:String(s.keyspace??""),username:String(s.username??""),password:String(s.password??""),sharded:s.sharded===!0,confirm:String(s.confirm??"")}))}catch(g){return h({ok:!1,error:g instanceof Error?g.message:String(g)},422)}}if(w.pathname==="/api/databases/vitess/migrations"&&S.method==="GET"){let s=w.searchParams.get("keyspace")??void 0;return h(await Zf(c,U,s))}if(w.pathname==="/api/databases/vitess/migrations/action"&&S.method==="POST"){let s=await B(S),g=String(s.uuid??"").trim(),_=String(s.action??"");if(!["retry","cancel","cleanup","complete"].includes(_))return h({ok:!1,error:"Unknown migration action."},422);return h(await Yf(c,U,g,_))}if(w.pathname==="/api/databases/vitess/keyspaces"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim(),_=s.sharded===!0;return h(await Mf(c,U,g,{sharded:_}))}if(w.pathname==="/api/databases/vitess/vschema"&&S.method==="POST"){let s=await B(S),g=String(s.keyspace??"").trim(),_=typeof s.vschema==="string"?s.vschema:JSON.stringify(s.vschema??null);return h(await Qf(c,U,g,_))}if(w.pathname==="/api/databases/vitess/schema"&&S.method==="POST"){let s=await B(S),g=String(s.sql??"");return h(await Gf(c,U,g))}if(w.pathname==="/api/databases/vitess/install-client"&&S.method==="POST")return h(await xf(c,U));if(w.pathname==="/api/databases/backups"&&S.method==="GET")return h(await jf(c,U));if(w.pathname==="/api/databases/backup"&&S.method==="POST"){let s=await B(S),g=String(s.database??"").trim();if(!zn(g))return h({ok:!1,error:"Database name must be a valid identifier."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to back up this database.`},409);return h(await Uf(c,U,g))}if(w.pathname==="/api/databases/users"&&S.method==="POST"){let s=await B(S),g=String(s.username??"").trim(),_=String(s.password??""),I=String(s.database??"").trim()||void 0,A=s.access==="readonly"?"readonly":"all";if(!zn(g))return h({ok:!1,error:"Username must be a valid identifier."},422);if(!_)return h({ok:!1,error:"Password is required."},422);if(I&&!zn(I))return h({ok:!1,error:"Database must be a valid identifier."},422);return h({...await Wf(c,U,{username:g,password:_,database:I,access:A}),username:g})}if(w.pathname==="/api/dashboard-data")return Ct=y.get(U)??await dt(U),dt(U),h(yl(Ct,{user:Be,slug:c.project.slug}));if(w.pathname==="/api/users"&&S.method==="GET")return h({ok:!0,users:Ie(e).map(Ii)});if(w.pathname==="/api/users"&&S.method==="POST"){let s=await B(S),g=String(s.username??"").trim();if(!no(g))return h({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let _=s.sites&&typeof s.sites==="object"?s.sites:{},I=new Set(Object.keys(c.sites??{})),A={};for(let[k,W]of Object.entries(_)){if(!I.has(k))return h({ok:!1,error:`Site '${k}' was not found.`},404);if(W!=="owner"&&W!=="collaborator")return h({ok:!1,error:`Unknown site role '${W}'. Use 'owner' or 'collaborator'.`},422);A[k]=W}let v=typeof s.password==="string"&&s.password.trim()?s.password.trim():void 0;if(v&&v.length<12)return h({ok:!1,error:"Password must be at least 12 characters."},422);let D=ec(e,{username:g,password:v,name:typeof s.name==="string"?s.name:void 0,sites:A});return Zd(o,Ie(e)),Le(),h({ok:!0,user:Ii(D.user),password:D.password})}if(w.pathname==="/api/users"&&S.method==="DELETE"){let s=await B(S),g=String(s.username??"").trim();if(g.toLowerCase()===z.username.toLowerCase())return h({ok:!1,error:"You cannot remove your own account."},409);let _=He(Ie(e),g),I=_?o.store.getActorByExternalId("user",`dashboard:${_.username.toLowerCase()}`):void 0,A=I?o.store.getMembershipForActor(o.organization.id,I.id):void 0;if(A&&A.source!=="legacy")return h({ok:!1,error:"Organization members must be removed from Organization access."},409);let v=Il(e,g);if(!v.ok)return h(v,409);return Zd(o,Ie(e)),Q.clear(),h({ok:!0,username:g})}if(w.pathname==="/api/actions/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.action?YP(s.action,U):void 0;if(!g)return h({ok:!1,error:"Unknown dashboard action."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this action.`},409);let _=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.action.${g.id}`,input:{action:g.id},execute:()=>Vl(g,{cwd:e,cliEntry:i})});return h({..._.result,controlPlaneOperation:_.operation})}if(w.pathname==="/api/server/operations/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.operation?Dl(s.operation,c,Ct):void 0;if(!g)return h({ok:!1,error:"Unknown or unavailable server operation."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this operation.`},409);let _=Ye(o,String(U));await new Cr(ot).run(new mi,{..._,artifactRoot:e});let I=Gd(ot,{scope:_,desiredConfigHash:o.project.desiredConfigHash});if(I.decision.outcome==="block")return h({ok:!1,error:`Operation blocked by security policy: ${I.decision.explanation}`,securityReview:I},409);let A=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.server.${g.id}`,resourceSlug:g.target,input:{operation:g.id,target:g.target,to:s.to??null},execute:()=>ao(c,U,g,{to:s.to})});return h({...A.result,controlPlaneOperation:A.operation,securityReview:I})}if(w.pathname==="/api/server/command"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="run")return h({ok:!1,error:'Type "run" to execute this command on the server.'},409);let g=await Bn({controlPlane:o,environment:U,actor:z,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>nc(c,U,String(s.command??""))});return h({...g.result,controlPlaneOperation:g.operation})}if(w.pathname==="/api/serverless/operations")return h(zl(c,U,Ct));if(w.pathname==="/api/serverless/operations/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.operation?j_(s.operation,c,U,Ct):void 0;if(!g)return h({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this operation.`},409);let _=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.serverless.${g.id}`,input:{operation:g.id,min:s.min??null,max:s.max??null},execute:()=>H_(c,U,g,{min:s.min,max:s.max})});return Ct=await br(c,U),y.set(U,Ct),h({..._.result,controlPlaneOperation:_.operation})}if(w.pathname==="/api/serverless/command"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="run")return h({ok:!1,error:'Type "run" to execute this command.'},409);return h(await L_(c,U,String(s.command??"")))}if(w.pathname==="/api/serverless/dlq"&&S.method==="GET"){let s=Number(w.searchParams.get("max"))||10;return h(await F_(c,U,s))}if(w.pathname==="/api/serverless/dlq/redrive"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="redrive")return h({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return h(await V_(c,U,{max:s.max,targetQueue:s.targetQueue}))}if(w.pathname==="/api/serverless/dlq/purge"&&S.method==="POST"){if((await S.json().catch(()=>({}))).confirm!=="purge")return h({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return h(await N_(c,U))}if(w.pathname==="/api/serverless/secrets"&&S.method==="GET")return h({secrets:x_(c,U)});if(w.pathname==="/api/serverless/secrets"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.secretId??"").trim();if(!g)return h({ok:!1,error:"A secret id is required."},422);if(typeof s.value!=="string"||s.value==="")return h({ok:!1,error:"A non-empty value is required."},422);return h(await M_(c,U,g,s.value))}if(w.pathname==="/api/serverless/secrets"&&S.method==="DELETE"){let s=await S.json().catch(()=>({})),g=String(s.secretId??"").trim();if(!g)return h({ok:!1,error:"A secret id is required."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to delete this secret.`},409);return h(await Q_(c,U,g))}if(w.pathname==="/api/serverless/functions/config"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.mode??"").trim();if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to update this function.`},409);return h(await G_(c,U,g,{memory:s.memory,timeout:s.timeout}))}if(w.pathname==="/api/serverless/alarms"&&S.method==="GET")return h(await Z_(c,U));if(w.pathname==="/api/serverless/alarms"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.preset??"").trim(),_=Number(s.threshold);if(!g)return h({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(_))return h({ok:!1,error:"A numeric threshold is required."},422);return h(await Y_(c,U,g,_))}if(w.pathname==="/api/serverless/alarms"&&S.method==="DELETE"){let s=await S.json().catch(()=>({})),g=String(s.name??"").trim();if(!g)return h({ok:!1,error:"An alarm name is required."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to delete this alarm.`},409);return h(await X_(c,U,g))}if(w.pathname==="/api/serverless/traces"&&S.method==="GET"){let s=Number(w.searchParams.get("minutes"))||30;return h(await lo(c,U,s))}if(w.pathname==="/api/serverless/scheduler"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.action??"").trim();if(g!=="enable"&&g!=="disable"&&g!=="run")return h({ok:!1,error:"Unknown scheduler action."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to ${g} the scheduler.`},409);return h(await Wl(c,U,g))}if(!yR(w.pathname,Be))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(U)}`}});let Fr=await me(z,U);if(!Fr)return Eo("ts-cloud dashboard UI is unavailable.",503);return PR(Fr,w.pathname)}catch(dr){if(t.verbose)console.error(dr);return h({ok:!1,error:dr?.message??String(dr)},500)}})();if(!Lt)return Lt;if(_t&&(w.pathname.startsWith("/api/")||w.pathname.startsWith("/auth/"))){let it;if((V.headers.get("content-type")||"").includes("application/json"))it=await V.json().catch(()=>{return});let pt=Bt.resolveUser(S),Zt=pt?X(pt).actor:void 0;o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,actorId:Zt?.id,correlationId:tt,type:Lt.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Lt.status<400?"info":"warning",payload:zP(S.method,w.pathname,it,Lt.status,Date.now()-Z)})}return Lt.headers.set("x-request-id",tt),Lt}});Sc?.start();let fE=t.spendLoop??!0,og;if(fE)(async()=>{let{SpendRunner:S,SpendLoopLease:x,startSpendLoop:Z}=await import("./chunk-b9qbp8j1.js"),{store:V}=await vR(o.store),tt=new S({controlPlane:o.store,store:V,alerts:nt});og=Z(tt,{lease:new x(o.store,{owner:`dashboard:${process.pid}`}),onError:(_t)=>console.error(`[ts-cloud] spend cycle failed: ${_t instanceof Error?_t.message:String(_t)}`)})})();let _E=Hr.stop.bind(Hr);return Hr.stop=(S)=>{clearInterval(rg),clearInterval(ig),clearInterval(cg),clearInterval(ng),clearInterval(eg),clearInterval(pl),clearInterval(ml),clearInterval(ql),clearInterval(tg),Le(),Vt.clear(),Sc?.stop(),og?.();let x=_E(S);if(Sc)Sc.settled().finally(()=>o.store.close());else o.store.close();return x},{server:Hr,url:`http://${n}:${Hr.port}/`}}
511
+ `);return new Response(ct,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="GET"){let j=X(z);return h({ok:!0,queries:g.listSavedQueries(o.project.id,j.actor?.id)})}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="POST"){let j=await B(S),K=X(z);return h({ok:!0,query:g.saveQuery(o.project.id,K.actor?.id,String(j.name??""),k(j.query??j))},201)}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="DELETE"){let j=await B(S),K=X(z),L=g.deleteSavedQuery(o.project.id,K.actor?.id,String(j.id??""));return h({ok:L},L?200:404)}}if(w.pathname.startsWith("/api/configuration")){let s=o.environments.get(U),g=z.role==="admin"||!!Be.capabilities?.includes("secrets:read"),_=z.role==="admin"||!!Be.capabilities?.includes("secrets:write"),I={projectId:o.project.id,environmentId:s?.id},A={"cache-control":"no-store"};if(w.pathname==="/api/configuration"&&S.method==="GET"){let v=Object.fromEntries(w.searchParams),D=v.scopeType||v.scopeId?Di(v,I):void 0,k=["variable","secret"].includes(String(v.kind))?v.kind:void 0,W=D?.type==="preview"?Ht.previews.getInstance(D.id):void 0,T=W?Ht.previews.getDefinition(W.definitionId):void 0,et=D?await we.resolve({projectId:o.project.id,environmentId:D.environmentId,resourceId:D.resourceId,functionId:D.type==="function"?D.id:void 0,previewId:D.previewId,trustedPreview:!!W&&!W.fork,allowedPreviewSecrets:T?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:g}):void 0,j=o.store.listResources(o.project.id);return h({ok:!0,entries:we.list({projectId:o.project.id,scope:D,kind:k,search:v.search,canReadSecretMetadata:g}),effectiveEntries:et?Object.values(et.entries).filter((K)=>!k||K.kind===k).filter((K)=>!v.search||K.key.toLowerCase().includes(String(v.search).toLowerCase())):[],configurationHash:et?.configurationHash,warnings:et?.warnings??[],scopes:{project:o.project,environments:o.store.listEnvironments(o.project.id),resources:j.filter((K)=>K.kind!=="function"),functions:j.filter((K)=>K.kind==="function"),previews:Ht.previews.listInstances({projectId:o.project.id}).filter((K)=>K.status!=="destroyed").map((K)=>({id:K.id,name:K.name,environmentId:K.baseEnvironmentId,resourceId:K.resourceId,fork:K.fork,status:K.status}))}},200,A)}if(w.pathname==="/api/configuration/export"&&S.method==="GET"){let v=Di(Object.fromEntries(w.searchParams),I);return new Response(we.exportVariables({projectId:o.project.id,scope:v}),{headers:{...A,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(w.pathname==="/api/configuration/plan"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=v.values&&typeof v.values==="object"&&!Array.isArray(v.values)?Object.fromEntries(Object.entries(v.values).map(([W,T])=>[W,String(T)])):{};return h({ok:!0,plan:we.plan({projectId:o.project.id,scope:D,values:k,removeMissing:v.removeMissing===!0})},200,A)}if(w.pathname==="/api/configuration"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=v.kind==="secret"?"secret":"variable",W=String(v.key??"");if(k==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let T=await we.set({organizationId:o.organization.id,projectId:o.project.id,scope:D,key:W,kind:k,value:v.value==null?void 0:String(v.value),reference:v.reference==null?void 0:String(v.reference),backend:v.backend,required:v.required===!0,expectedVersion:v.expectedVersion==null?void 0:Number(v.expectedVersion),confirmed:String(v.confirm??"")===W,idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey,actorId:X(z).actor?.id});return h({ok:!0,entry:we.list({projectId:o.project.id,scope:D,canReadSecretMetadata:g}).find((et)=>et.id===T.entry.id),mutation:T.mutation,warnings:T.warnings},T.mutation.added.length?201:200,A)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T)},409,A)}}if(w.pathname==="/api/configuration/import"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=Array.isArray(v.secretKeys)?v.secretKeys.map(String):[];if(k.length&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let W=await we.importDotenv({organizationId:o.organization.id,projectId:o.project.id,scope:D,source:String(v.source??""),secretKeys:k,backend:v.backend,confirmed:v.confirm==="import",idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey,actorId:X(z).actor?.id});return h({ok:W.document.valid,diagnostics:W.document.diagnostics,mutation:W.mutation,warnings:W.warnings},W.document.valid?200:422,A)}catch(W){return h({ok:!1,error:W instanceof Error?W.message:String(W)},409,A)}}if(w.pathname==="/api/configuration/dependencies"&&S.method==="POST"){let v=await B(S),D=Wn.get(String(v.entryId??"")),k=o.store.getResource(String(v.resourceId??""));if(!D||D.projectId!==o.project.id||!k||k.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry or dependent resource was not found."},404,A);return h({ok:!0,dependency:Wn.setDependency({entryId:D.id,resourceId:k.id,injectionTarget:["native_reference","file"].includes(String(v.injectionTarget))?v.injectionTarget:"environment",required:v.required!==!1,requiresRedeploy:v.requiresRedeploy!==!1,lastDeployedVersion:v.lastDeployedVersion==null?void 0:Number(v.lastDeployedVersion)})},200,A)}if(w.pathname==="/api/configuration/transfer"&&S.method==="POST"){let v=await B(S),D=Wn.get(String(v.id??"")),k=Di({...v,scopeType:v.targetScopeType,scopeId:v.targetScopeId},I);if(!D||D.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry was not found."},404,A);if(D.kind==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let W=await we.transfer({entryId:D.id,targetScope:k,mode:v.mode==="move"?"move":"copy",confirmed:v.confirm===D.key,actorId:X(z).actor?.id,idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey});return h({ok:!0,entry:we.list({projectId:o.project.id,scope:k,canReadSecretMetadata:g}).find((T)=>T.id===W.entry.id),mutation:W.mutation},200,A)}catch(W){return h({ok:!1,error:W instanceof Error?W.message:String(W)},409,A)}}if(w.pathname==="/api/configuration/bulk"&&S.method==="POST"){let v=await B(S),D=Array.isArray(v.ids)?v.ids.map(String).slice(0,500):[],k=D.map((T)=>Wn.get(T)).filter((T)=>!!T&&T.projectId===o.project.id);if(k.length!==D.length)return h({ok:!1,error:"One or more configuration entries were not found."},404,A);if(k.some((T)=>T.kind==="secret")&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);if(v.action!=="delete"||v.confirm!=="bulk")return h({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,A);let W=[];try{for(let T of k)W.push(await we.remove({entryId:T.id,expectedVersion:T.version,confirmed:!0,actorId:X(z).actor?.id}));return h({ok:!0,removed:W.flatMap((T)=>T.removed),affectedResourceIds:[...new Set(W.flatMap((T)=>T.affectedResourceIds))].sort()},200,A)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T),partial:W.flatMap((et)=>et.removed)},409,A)}}if(w.pathname==="/api/configuration/reveal"&&S.method==="POST"){let v=await B(S),D=Bt.resolveSession(S);try{return h({ok:!0,value:await we.reveal({entryId:String(v.id??""),canRevealSecrets:g,recentlyAuthenticated:!G||!!D&&F.isRecentlyAuthenticated(D),actorId:X(z).actor?.id})},200,A)}catch(k){return h({ok:!1,error:k instanceof Error?k.message:String(k)},403,A)}}if(w.pathname==="/api/configuration"&&S.method==="DELETE"){let v=await B(S),D=Wn.get(String(v.id??""));if(D?.kind==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);if(!D||D.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry was not found."},404,A);try{return h({ok:!0,mutation:await we.remove({entryId:D.id,expectedVersion:Number(v.expectedVersion),confirmed:String(v.confirm??"")===D.key,actorId:X(z).actor?.id})},200,A)}catch(k){return h({ok:!1,error:k instanceof Error?k.message:String(k)},409,A)}}}if(w.pathname.startsWith("/api/fleet")){let s=X(z).actor?.id,g=(_,I=409)=>h({ok:!1,error:_ instanceof Error?_.message:String(_)},I,{"cache-control":"no-store"});if(w.pathname==="/api/fleet"&&S.method==="GET")return h({ok:!0,servers:vi.list(o.project.id),resources:o.store.listResources(o.project.id),operations:yt.list({projectId:o.project.id,limit:200}).filter((_)=>_.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(w.pathname==="/api/fleet"&&S.method==="POST"){let _=await B(S);try{return h({ok:!0,server:en.enroll({organizationId:o.organization.id,projectId:o.project.id,name:String(_.name??""),provider:["aws","hetzner"].includes(String(_.provider))?_.provider:"ssh",providerId:_.providerId?String(_.providerId):void 0,region:_.region?String(_.region):void 0,zone:_.zone?String(_.zone):void 0,endpoint:String(_.endpoint??""),sshUser:String(_.sshUser??"deploy"),sshPort:_.sshPort?Number(_.sshPort):22,credentialRef:String(_.credentialRef??""),roles:Array.isArray(_.roles)?_.roles:[],labels:_.labels&&typeof _.labels==="object"?_.labels:{}})},201)}catch(I){return g(I,422)}}if(w.pathname==="/api/fleet/action"&&S.method==="POST"){let _=await B(S),I=String(_.id??""),A=String(_.action??"");try{if(A==="test")return h({ok:!0,server:await en.test(I)});if(A==="validate")return h({ok:!0,server:await en.validate(I)});if(A==="review_host_key")return h({ok:!0,server:en.reviewHostKey(I,String(_.fingerprint??""))});if(A==="bootstrap")return h({ok:!0,...en.bootstrap(I,_.confirmed===!0)},_.confirmed===!0?202:200);if(A==="heartbeat")return h({ok:!0,server:en.heartbeat(I,{usage:_.usage&&typeof _.usage==="object"?_.usage:{}})});if(A==="drain")return h({ok:!0,server:en.drain(I,_.completed===!0)});if(A==="uncordon")return h({ok:!0,server:en.uncordon(I)});if(A==="archive")return h({ok:!0,server:en.archive(I,String(_.confirmation??""))});return g("Unsupported fleet action.",422)}catch(v){return g(v)}}}if(w.pathname.startsWith("/api/capacity")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/capacity"&&S.method==="GET")return h({ok:!0,pools:jn.listPools(o.project.id),placements:jn.listPlacements(o.project.id),servers:vi.list(o.project.id)},200,{"cache-control":"no-store"});if(w.pathname==="/api/capacity"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,pool:jn.createPool({organizationId:o.organization.id,projectId:o.project.id,name:String(g.name??""),purpose:String(g.purpose??"application"),backend:String(g.backend??"server"),region:g.region?String(g.region):void 0,architecture:g.architecture?String(g.architecture):void 0,labels:g.labels&&typeof g.labels==="object"?g.labels:{},requiredServerLabels:g.requiredServerLabels&&typeof g.requiredServerLabels==="object"?g.requiredServerLabels:{},toleratedTaints:Array.isArray(g.toleratedTaints)?g.toleratedTaints.map(String):[],capacity:g.capacity&&typeof g.capacity==="object"?g.capacity:{},maxWorkloads:Number(g.maxWorkloads??10),costWeight:Number(g.costWeight??1),spreadKey:g.spreadKey?String(g.spreadKey):void 0,concurrency:Number(g.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/member"&&S.method==="POST"){let g=await B(S);try{return jn.addMember(String(g.poolId??""),String(g.serverId??"")),h({ok:!0,pool:jn.getPool(String(g.poolId??""))})}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/explain"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,decisions:Gl.explain(o.project.id,{purpose:String(g.purpose??"application"),resources:g.resources&&typeof g.resources==="object"?g.resources:{},region:g.region?String(g.region):void 0,architecture:g.architecture?String(g.architecture):void 0,labels:g.labels&&typeof g.labels==="object"?g.labels:{}})})}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/action"&&S.method==="POST"){let g=await B(S);try{if(g.action==="drain")return h({ok:!0,...Gl.drainPool(String(g.poolId??""))});if(g.action==="enable")return h({ok:!0,pool:jn.updatePool(String(g.poolId??""),{status:"active"})});if(g.action==="disable")return h({ok:!0,pool:jn.updatePool(String(g.poolId??""),{status:"disabled"})});return s("Unsupported capacity action.",422)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/regions")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/regions"&&S.method==="GET")return h({ok:!0,topologies:cr.list(o.project.id).map((g)=>({topology:g,targets:cr.targets(g.id),channels:cr.channels(g.id),route:cr.route(g.id),executions:cr.executions(g.id)}))},200,{"cache-control":"no-store"});if(w.pathname==="/api/regions"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,topology:Zl.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:o.environments.get(U)?.id,name:String(g.name??""),hostname:String(g.hostname??""),regions:Array.isArray(g.regions)?g.regions:[],trafficPolicy:g.trafficPolicy==="weighted"||g.trafficPolicy==="latency"?g.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(g.replicate)?g.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(g.maxLagSeconds??30),retainOnDestroy:g.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:g.cdnEnabled===!0,wafEnabled:g.wafEnabled===!0})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/regions/action"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Zl.enqueue({topologyId:String(g.topologyId??""),kind:String(g.action??""),targetRegion:g.targetRegion?String(g.targetRegion):void 0,revision:g.revision?String(g.revision):void 0,manifest:g.manifest&&typeof g.manifest==="object"?g.manifest:{},confirmation:g.confirmation?String(g.confirmation):void 0,deleteData:g.deleteData===!0})},202)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/maintenance")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/maintenance"&&S.method==="GET")return h({ok:!0,manifests:hn.manifests(o.organization.id),windows:hn.windows(o.project.id),campaigns:hn.campaigns(o.project.id).map((g)=>({campaign:g,targets:hn.targets(g.id)})),cleanups:hn.cleanups(o.project.id),drills:hn.drills(o.project.id)},200,{"cache-control":"no-store"});if(w.pathname==="/api/maintenance/cleanup-preview"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,plan:await Do.previewCleanup({projectId:o.project.id,kind:String(g.kind??"operations"),criteria:{olderThanDays:Number(g.olderThanDays??30)}},Yl)},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/cleanup-apply"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Do.enqueueCleanup(String(g.planId??""),String(g.confirmation??""))},202)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/drill"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,drill:hn.createDrill({projectId:o.project.id,scenario:String(g.scenario??"control_plane"),isolatedTarget:String(g.isolatedTarget??""),expectedRpoMinutes:Number(g.expectedRpoMinutes??60),expectedRtoMinutes:Number(g.expectedRtoMinutes??30),recoveryPointId:g.recoveryPointId?String(g.recoveryPointId):void 0,topologyId:g.topologyId?String(g.topologyId):void 0})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/drill-run"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Do.enqueueDrill(String(g.drillId??""))},202)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/volumes")){let s=o.environments.get(U),g=X(z).actor?.id,_=(I,A=409)=>h({ok:!1,error:I instanceof Error?I.message:String(I)},A,{"cache-control":"no-store"});if(w.pathname==="/api/volumes"&&S.method==="GET"){let I=wo.inventory(o.project.id,s?.id),A=o.store.listResources(o.project.id,s?.id).map((v)=>({id:v.id,name:v.name,slug:v.slug,kind:v.kind,provider:v.provider,providerId:v.providerId}));return h({ok:!0,volumes:I,resources:A,operations:yt.list({projectId:o.project.id,limit:100}).filter((v)=>v.operation.kind.startsWith("volume.")),recoveryPoints:Ft.listRecoveryPoints(o.project.id).filter((v)=>v.kind==="volume"),providers:Ao.map((v)=>({provider:v.provider,type:v.type,capabilities:v.capabilities()}))},200,{"cache-control":"no-store"})}if(w.pathname==="/api/volumes"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,resourceId:I.resourceId?String(I.resourceId):void 0,name:String(I.name??""),provider:String(I.provider??"docker"),type:I.type==="docker"?"docker":I.type,capacityBytes:I.capacityBytes==null?void 0:Number(I.capacityBytes),filesystem:I.filesystem?String(I.filesystem):void 0,encrypted:I.encrypted===!0,desiredState:I.desiredState&&typeof I.desiredState==="object"?I.desiredState:{},actorId:g})},202,{"cache-control":"no-store"})}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/attach"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.attach(String(I.volumeId??""),{resourceId:String(I.resourceId??""),targetPath:String(I.targetPath??""),readOnly:I.readOnly===!0,uid:I.uid==null?void 0:Number(I.uid),gid:I.gid==null?void 0:Number(I.gid),mode:I.mode?String(I.mode):void 0,propagation:I.propagation,driverOptions:I.driverOptions&&typeof I.driverOptions==="object"?I.driverOptions:{},actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/detach"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.detach(String(I.volumeId??""),String(I.attachmentId??""),{force:I.force===!0,drained:I.drained===!0,unmounted:I.unmounted===!0,confirmation:I.confirmation?String(I.confirmation):void 0,actorId:g})},202)}catch(A){return _(A)}}if(w.pathname==="/api/volumes/resize"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.resize(String(I.volumeId??""),Number(I.capacityBytes),{drained:I.drained===!0,actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/snapshot"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.snapshot(String(I.volumeId??""),{name:I.name?String(I.name):void 0,actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/restore"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.restore(String(I.snapshotId??""),{name:String(I.name??""),actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/discover"&&S.method==="POST")try{return h({ok:!0,volumes:await un.discover({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,actorId:g})})}catch(I){return _(I,502)}if(w.pathname==="/api/volumes/adopt"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,volume:un.adopt(String(I.volumeId??""),{name:String(I.name??""),actorId:g})})}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes"&&S.method==="DELETE"){let I=await B(S),A=Bt.resolveSession(S);try{return h({ok:!0,...un.delete(String(I.volumeId??""),{recentAuthAt:!G||A&&F.isRecentlyAuthenticated(A)?new Date().toISOString():void 0,confirmation:I.confirmation?String(I.confirmation):void 0,backupOverride:I.backupOverride===!0,backupOverrideConfirmation:I.backupOverrideConfirmation?String(I.backupOverrideConfirmation):void 0,actorId:g})},202)}catch(v){return _(v)}}}if(w.pathname==="/api/backups"&&S.method==="GET"){let s=o.environments.get(U),g=Ft.listPolicies(o.project.id,s?.id),_=new Set(g.map((k)=>k.id)),I=Ft.listRecoveryPoints(o.project.id).filter((k)=>!k.policyId||_.has(k.policyId)),A=Ft.listJobs(o.project.id).filter((k)=>!k.policyId||_.has(k.policyId)),v=(k)=>({...k,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!k.credentialRef,clientEncryptionConfigured:!!k.encryptionKeyRef}),D=await Promise.all(Ft.listDestinations(o.project.id).map(async(k)=>({...v(k),credentialStatus:await Wu(k,gn)})));return h({ok:!0,destinations:D,policies:g,recoveryPoints:I,jobs:A,coverage:Ft.coverage(o.project.id).filter((k)=>_.has(k.policy.id)),resources:s?o.store.listResources(o.project.id,s.id).map((k)=>({id:k.id,name:k.name,slug:k.slug,kind:k.kind})):[]})}if(w.pathname==="/api/backups/destinations"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim(),_=String(s.provider??""),I=String(s.encryption??"provider"),A=`secret://data-services/backups/${o.project.id}/${g}`,v=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(_))return h({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(I))return h({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let D,k;if(s.credentials&&typeof s.credentials==="object"&&!Array.isArray(s.credentials))D=`${A}/credentials`,await gn.put(D,JSON.stringify(s.credentials)),v.push(D);if(I!=="provider"){let T=String(s.encryptionKey??"");if(T.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");k=`${A}/encryption-key`,await gn.put(k,T),v.push(k)}let W=Ft.createDestination({organizationId:o.organization.id,projectId:o.project.id,name:g,provider:_,endpoint:s.endpoint?String(s.endpoint):void 0,endpointPolicy:s.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:s.bucket?String(s.bucket):void 0,prefix:String(s.prefix??""),region:s.region?String(s.region):Un,forcePathStyle:s.forcePathStyle===!0,credentialRef:D,encryption:I,encryptionKeyRef:k,immutability:s.immutability&&typeof s.immutability==="object"&&!Array.isArray(s.immutability)?s.immutability:{},status:"untested"});return h({ok:!0,destination:{...W,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!D,clientEncryptionConfigured:!!k}},201)}catch(D){for(let k of v)await gn.remove(k).catch(()=>{});return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}if(w.pathname==="/api/backups/destinations/test"&&S.method==="POST"){let s=await B(S),g=Ft.getDestination(String(s.id??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Backup destination was not found."},404);if(g.provider==="aws_backup")return h({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await Ql.test(g),h({ok:!0,destination:Ft.recordDestinationTest(g.id,{ok:!0})})}catch(_){let I=_ instanceof Error?_.message:String(_);return Ft.recordDestinationTest(g.id,{ok:!1,error:I}),h({ok:!1,error:I},502)}}if(w.pathname==="/api/backups/policies"&&S.method==="POST"){let s=await B(S),g=o.environments.get(U),_=Ft.getDestination(String(s.destinationId??"")),I=String(s.resourceKind??""),A=s.dataServiceId?String(s.dataServiceId):void 0,v=A?kt.get(A):void 0,D=s.resourceId?String(s.resourceId):void 0,k=D?o.store.getResource(D):void 0;if(!g)return h({ok:!1,error:"Environment was not found."},404);if(!_||_.projectId!==o.project.id)return h({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(I))return h({ok:!1,error:"A supported backup resource kind is required."},422);if(A&&(!v||v.projectId!==o.project.id||v.environmentId!==g.id))return h({ok:!1,error:"Data service was not found in this environment."},404);if(D&&(!k||k.projectId!==o.project.id||k.environmentId!==g.id))return h({ok:!1,error:"Resource was not found in this environment."},404);if(I==="managed_database"&&!v)return h({ok:!1,error:"Managed database policies require a data service."},422);if(I==="logical_database"&&(!v||!["container","server"].includes(v.provider)))return h({ok:!1,error:"Logical database policies require an on-box data service."},422);if(I==="volume"&&(!k||!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(String(s.volumeName??""))))return h({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let W=Array.isArray(s.includePatterns)?s.includePatterns.map(String).filter(Boolean):[];if(I==="files"&&(!k||!W.length))return h({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(I==="control_plane"&&_.encryption==="provider")return h({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(I==="infrastructure"&&(_.provider!=="aws_backup"||!W.some((T)=>T.startsWith("resource:arn:"))||!W.some((T)=>T.startsWith("role:arn:"))))return h({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let T=Ft.createPolicy({organizationId:o.organization.id,projectId:o.project.id,environmentId:g.id,resourceId:D,dataServiceId:A,destinationId:_.id,name:String(s.name??"").trim(),resourceKind:I,schedule:String(s.schedule??"daily"),timezone:String(s.timezone??"UTC"),retention:s.retention&&typeof s.retention==="object"&&!Array.isArray(s.retention)?s.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(s.compression))?s.compression:"gzip",encryption:["destination","client_side","both"].includes(String(s.encryption))?s.encryption:"destination",includePatterns:I==="volume"?[String(s.volumeName),...W]:W,excludePatterns:Array.isArray(s.excludePatterns)?s.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(s.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(s.expectedRtoMinutes)||120),healthCheckId:s.healthCheckId?String(s.healthCheckId):void 0,enabled:s.enabled!==!1});return h({ok:!0,policy:T},201)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T)},422)}}if(w.pathname==="/api/backups/run"&&S.method==="POST"){let s=await B(S),g=Ft.getPolicy(String(s.policyId??"")),_=o.environments.get(U);if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Backup policy was not found in this environment."},404);try{let I=ir.enqueueBackup(g,new Date().toISOString(),X(z).actor?.id);return h({ok:!0,job:I},202)}catch(I){return h({ok:!1,error:I instanceof Error?I.message:String(I)},409)}}if(w.pathname==="/api/backups/verify"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.recoveryPointId??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);return h({ok:!0,job:ir.enqueueVerification(g)},202)}if(w.pathname==="/api/backups/restore"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.recoveryPointId??"")),_=s.mode==="in_place"?"in_place":"isolated",I=s.target&&typeof s.target==="object"&&!Array.isArray(s.target)?{...s.target,inPlace:_==="in_place"}:{inPlace:_==="in_place"},A=Bt.resolveSession(S),v={mode:_,target:I,targetName:String(s.targetName??""),confirm:s.confirm?String(s.confirm):void 0,recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A),downtimeAcknowledged:s.downtimeAcknowledged===!0,safetyBackupId:s.safetyBackupId?String(s.safetyBackupId):void 0};if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);if(s.drill===!0&&_!=="isolated")return h({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let D=ir.planRestore(g,v);if(s.execute!==!0)return h({ok:!0,plan:D,executionCreated:!1});let k=ir.enqueueRestore(g,{...v,drill:s.drill===!0,actorId:X(z).actor?.id});return h({ok:!0,plan:D,job:k},202)}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},409)}}if(w.pathname==="/api/backups/recovery-points"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.id??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);if(s.held==null&&s.pinned==null)return h({ok:!1,error:"held or pinned must be provided."},422);return h({ok:!0,recoveryPoint:Ft.updateRecoveryPoint(g.id,{held:s.held==null?g.held:s.held===!0,pinned:s.pinned==null?g.pinned:s.pinned===!0})})}if(w.pathname==="/api/backups/retention"&&S.method==="POST")return h({ok:!0,jobs:ir.enqueueRetention()},202);if(w.pathname==="/api/data-services/capabilities"&&S.method==="GET"){let s=String(w.searchParams.get("engine")??""),g=String(w.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(s)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(g))return h({ok:!1,error:"A supported engine and provider are required."},422);return h({ok:!0,engine:s,provider:g,capabilities:Li(s,g)})}if(w.pathname==="/api/data-services"&&S.method==="GET"){let s=o.environments.get(U),g=kt.list(o.project.id,s?.id).map((_)=>{let I=kt.credential(_.id);return{..._,credentialRef:void 0,credential:I?{configured:!0,username:I.username,version:I.version,rotatedAt:I.rotatedAt}:void 0,dependencies:kt.dependencies(_.id).map((A)=>({resourceId:A.resourceId,requiresRedeploy:A.requiresRedeploy}))}});return h({ok:!0,services:g})}if(w.pathname==="/api/data-services/preview"&&S.method==="POST"){let s=await B(S);if(s.id){let I=kt.get(String(s.id)),A=o.environments.get(U),v=String(s.action??"");if(!I||I.projectId!==o.project.id||I.environmentId!==A?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!_o.includes(v))return h({ok:!1,error:`Action must be one of: ${_o.join(", ")}.`},422);try{return h({ok:!0,plan:hc.plan(I,v,s.changes??{})})}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}let g=String(s.engine??""),_=String(s.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(g)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(_))return h({ok:!1,error:"A supported engine and provider are required."},422);return h({ok:!0,capabilities:Li(g,_),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(w.pathname==="/api/data-services"&&S.method==="POST"){let s=await B(S),g=String(s.engine??""),_=String(s.provider??""),I=o.environments.get(U),A=X(z);if(!I)return h({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(g)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(_))return h({ok:!1,error:"A supported engine and provider are required."},422);let v={organizationId:o.organization.id,projectId:o.project.id,environmentId:I.id,resourceId:s.resourceId?String(s.resourceId):void 0,name:String(s.name??"").trim(),engine:g,provider:_,placement:String(s.placement??s.name??"").trim(),engineVersion:s.engineVersion?String(s.engineVersion):void 0,plan:String(s.plan??(_==="aws_elasticache"?"cache.t4g.micro":_==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:s.storageGb==null?void 0:Number(s.storageGb),highAvailability:s.highAvailability===!0,publicExposure:s.publicExposure===!0,allowedCidrs:Array.isArray(s.allowedCidrs)?s.allowedCidrs.map(String):[],desiredState:s.desiredState&&typeof s.desiredState==="object"&&!Array.isArray(s.desiredState)?s.desiredState:{},observedState:{},origin:s.adopt===!0?"adopted":"managed",managementEnabled:s.adopt!==!0,ownerActorId:A.actor?.id,username:s.username?String(s.username):void 0};try{if(s.adopt===!0){let k=kt.create({...v,status:"adopted",credentialRef:void 0});return h({ok:!0,service:k,readOnly:!0},201)}if(!Ml({provider:_,engine:g}))return h({ok:!1,error:`No ${_}/${g} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let D=await hc.create(v);return h({ok:!0,service:D.service,operationId:D.operationId,oneTimeCredential:D.credential},201)}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}if(w.pathname==="/api/data-services/connections"&&S.method==="GET"){let s=kt.get(String(w.searchParams.get("id")??"")),g=o.environments.get(U);if(!s||s.projectId!==o.project.id||s.environmentId!==g?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);let _=typeof s.observedState.endpoint==="string"?s.observedState.endpoint:void 0,I=typeof s.observedState.readerEndpoint==="string"?s.observedState.readerEndpoint:void 0,A=Number(s.observedState.port)||(s.engine==="postgres"?5432:s.engine==="redis"?6379:s.engine==="mongodb"?27017:s.engine==="libsql"?8080:3306),v=typeof s.observedState.database==="string"?s.observedState.database:void 0,D=typeof s.observedState.tls==="boolean"?s.observedState.tls:s.provider.startsWith("aws_"),k=[..._?[{type:s.publicExposure?"external":"internal",host:_,port:A,database:v,tls:D}]:[],...I?[{type:"internal",host:I,port:A,database:v,tls:D}]:[],{type:"tunnel",host:_??s.placement,port:A,database:v,tls:D}];return h({ok:!0,serviceId:s.id,guidance:Lu(s,k)})}if(w.pathname==="/api/data-services/action"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=String(s.action??"");if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!_o.includes(I))return h({ok:!1,error:`Action must be one of: ${_o.join(", ")}.`},422);let A=s.changes&&typeof s.changes==="object"&&!Array.isArray(s.changes)?s.changes:{};try{let v=hc.plan(g,I,A);if(s.execute!==!0)return h({ok:!0,plan:v,productionExecutionCreated:!1});let D=hc.enqueue(g,I,A,X(z).actor?.id);return h({ok:!0,plan:v,operationId:D},202)}catch(v){return h({ok:!1,error:v instanceof Error?v.message:String(v)},409)}}if(w.pathname==="/api/data-services/dependencies"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=o.store.getResource(String(s.resourceId??""));if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!I||I.projectId!==o.project.id||I.environmentId!==_?.id)return h({ok:!1,error:"Dependent resource was not found in this environment."},404);if(s.remove===!0)return h({ok:kt.removeDependency(g.id,I.id)});return kt.addDependency({serviceId:g.id,resourceId:I.id,secretRef:g.credentialRef??`secret://data-services/${g.projectId}/${g.name}`,requiresRedeploy:s.requiresRedeploy!==!1}),h({ok:!0,dependencies:kt.dependencies(g.id).map((A)=>({resourceId:A.resourceId,requiresRedeploy:A.requiresRedeploy}))})}if(w.pathname==="/api/data-services/management"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U);if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(g.origin!=="adopted"||s.reviewed!==!0||s.confirm!==g.name)return h({ok:!1,error:`Enabling management requires reviewed=true and typing ${g.name}.`},409);return h({ok:!0,service:kt.update(g.id,g.version,{managementEnabled:!0})})}if(w.pathname==="/api/data-services/reveal"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=g?kt.credential(g.id):void 0;if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!I)return h({ok:!1,error:"No managed credential is configured."},404);return h({ok:!0,credential:{username:I.username,password:await gn.resolve(I.secretRef),version:I.version}},200,{"cache-control":"no-store"})}if(w.pathname==="/api/databases"&&S.method==="GET")return h(await Tf(c,U));if(w.pathname==="/api/databases"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim();if(!zn(g))return h({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return h({...await bf(c,U,g),name:g})}if(w.pathname==="/api/databases/vitess"&&S.method==="GET"){let s=await Hf(c,U);return h({...s,unhealthy:Lf(s.tablets),missingPrimary:Ff(s)})}if(w.pathname==="/api/databases/vitess/provision"&&S.method==="POST"){let s=await B(S);try{return h(await pf(c,U,{keyspace:String(s.keyspace??""),username:String(s.username??""),password:String(s.password??""),sharded:s.sharded===!0,confirm:String(s.confirm??"")}))}catch(g){return h({ok:!1,error:g instanceof Error?g.message:String(g)},422)}}if(w.pathname==="/api/databases/vitess/migrations"&&S.method==="GET"){let s=w.searchParams.get("keyspace")??void 0;return h(await Zf(c,U,s))}if(w.pathname==="/api/databases/vitess/migrations/action"&&S.method==="POST"){let s=await B(S),g=String(s.uuid??"").trim(),_=String(s.action??"");if(!["retry","cancel","cleanup","complete"].includes(_))return h({ok:!1,error:"Unknown migration action."},422);return h(await Yf(c,U,g,_))}if(w.pathname==="/api/databases/vitess/keyspaces"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim(),_=s.sharded===!0;return h(await Mf(c,U,g,{sharded:_}))}if(w.pathname==="/api/databases/vitess/vschema"&&S.method==="POST"){let s=await B(S),g=String(s.keyspace??"").trim(),_=typeof s.vschema==="string"?s.vschema:JSON.stringify(s.vschema??null);return h(await Qf(c,U,g,_))}if(w.pathname==="/api/databases/vitess/schema"&&S.method==="POST"){let s=await B(S),g=String(s.sql??"");return h(await Gf(c,U,g))}if(w.pathname==="/api/databases/vitess/install-client"&&S.method==="POST")return h(await xf(c,U));if(w.pathname==="/api/databases/backups"&&S.method==="GET")return h(await jf(c,U));if(w.pathname==="/api/databases/backup"&&S.method==="POST"){let s=await B(S),g=String(s.database??"").trim();if(!zn(g))return h({ok:!1,error:"Database name must be a valid identifier."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to back up this database.`},409);return h(await Uf(c,U,g))}if(w.pathname==="/api/databases/users"&&S.method==="POST"){let s=await B(S),g=String(s.username??"").trim(),_=String(s.password??""),I=String(s.database??"").trim()||void 0,A=s.access==="readonly"?"readonly":"all";if(!zn(g))return h({ok:!1,error:"Username must be a valid identifier."},422);if(!_)return h({ok:!1,error:"Password is required."},422);if(I&&!zn(I))return h({ok:!1,error:"Database must be a valid identifier."},422);return h({...await Wf(c,U,{username:g,password:_,database:I,access:A}),username:g})}if(w.pathname==="/api/dashboard-data")return Ct=y.get(U)??await dt(U),dt(U),h(yl(Ct,{user:Be,slug:c.project.slug}));if(w.pathname==="/api/users"&&S.method==="GET")return h({ok:!0,users:Ie(e).map(Ii)});if(w.pathname==="/api/users"&&S.method==="POST"){let s=await B(S),g=String(s.username??"").trim();if(!no(g))return h({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let _=s.sites&&typeof s.sites==="object"?s.sites:{},I=new Set(Object.keys(c.sites??{})),A={};for(let[k,W]of Object.entries(_)){if(!I.has(k))return h({ok:!1,error:`Site '${k}' was not found.`},404);if(W!=="owner"&&W!=="collaborator")return h({ok:!1,error:`Unknown site role '${W}'. Use 'owner' or 'collaborator'.`},422);A[k]=W}let v=typeof s.password==="string"&&s.password.trim()?s.password.trim():void 0;if(v&&v.length<12)return h({ok:!1,error:"Password must be at least 12 characters."},422);let D=ec(e,{username:g,password:v,name:typeof s.name==="string"?s.name:void 0,sites:A});return Zd(o,Ie(e)),Le(),h({ok:!0,user:Ii(D.user),password:D.password})}if(w.pathname==="/api/users"&&S.method==="DELETE"){let s=await B(S),g=String(s.username??"").trim();if(g.toLowerCase()===z.username.toLowerCase())return h({ok:!1,error:"You cannot remove your own account."},409);let _=He(Ie(e),g),I=_?o.store.getActorByExternalId("user",`dashboard:${_.username.toLowerCase()}`):void 0,A=I?o.store.getMembershipForActor(o.organization.id,I.id):void 0;if(A&&A.source!=="legacy")return h({ok:!1,error:"Organization members must be removed from Organization access."},409);let v=Il(e,g);if(!v.ok)return h(v,409);return Zd(o,Ie(e)),Q.clear(),h({ok:!0,username:g})}if(w.pathname==="/api/actions/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.action?YP(s.action,U):void 0;if(!g)return h({ok:!1,error:"Unknown dashboard action."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this action.`},409);let _=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.action.${g.id}`,input:{action:g.id},execute:()=>Vl(g,{cwd:e,cliEntry:i})});return h({..._.result,controlPlaneOperation:_.operation})}if(w.pathname==="/api/server/operations/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.operation?Dl(s.operation,c,Ct):void 0;if(!g)return h({ok:!1,error:"Unknown or unavailable server operation."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this operation.`},409);let _=Ye(o,String(U));await new Cr(ot).run(new mi,{..._,artifactRoot:e});let I=Gd(ot,{scope:_,desiredConfigHash:o.project.desiredConfigHash});if(I.decision.outcome==="block")return h({ok:!1,error:`Operation blocked by security policy: ${I.decision.explanation}`,securityReview:I},409);let A=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.server.${g.id}`,resourceSlug:g.target,input:{operation:g.id,target:g.target,to:s.to??null},execute:()=>ao(c,U,g,{to:s.to})});return h({...A.result,controlPlaneOperation:A.operation,securityReview:I})}if(w.pathname==="/api/server/command"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="run")return h({ok:!1,error:'Type "run" to execute this command on the server.'},409);let g=await Bn({controlPlane:o,environment:U,actor:z,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>nc(c,U,String(s.command??""))});return h({...g.result,controlPlaneOperation:g.operation})}if(w.pathname==="/api/serverless/operations")return h(zl(c,U,Ct));if(w.pathname==="/api/serverless/operations/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.operation?j_(s.operation,c,U,Ct):void 0;if(!g)return h({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this operation.`},409);let _=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.serverless.${g.id}`,input:{operation:g.id,min:s.min??null,max:s.max??null},execute:()=>H_(c,U,g,{min:s.min,max:s.max})});return Ct=await br(c,U),y.set(U,Ct),h({..._.result,controlPlaneOperation:_.operation})}if(w.pathname==="/api/serverless/command"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="run")return h({ok:!1,error:'Type "run" to execute this command.'},409);return h(await L_(c,U,String(s.command??"")))}if(w.pathname==="/api/serverless/dlq"&&S.method==="GET"){let s=Number(w.searchParams.get("max"))||10;return h(await F_(c,U,s))}if(w.pathname==="/api/serverless/dlq/redrive"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="redrive")return h({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return h(await V_(c,U,{max:s.max,targetQueue:s.targetQueue}))}if(w.pathname==="/api/serverless/dlq/purge"&&S.method==="POST"){if((await S.json().catch(()=>({}))).confirm!=="purge")return h({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return h(await N_(c,U))}if(w.pathname==="/api/serverless/secrets"&&S.method==="GET")return h({secrets:x_(c,U)});if(w.pathname==="/api/serverless/secrets"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.secretId??"").trim();if(!g)return h({ok:!1,error:"A secret id is required."},422);if(typeof s.value!=="string"||s.value==="")return h({ok:!1,error:"A non-empty value is required."},422);return h(await M_(c,U,g,s.value))}if(w.pathname==="/api/serverless/secrets"&&S.method==="DELETE"){let s=await S.json().catch(()=>({})),g=String(s.secretId??"").trim();if(!g)return h({ok:!1,error:"A secret id is required."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to delete this secret.`},409);return h(await Q_(c,U,g))}if(w.pathname==="/api/serverless/functions/config"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.mode??"").trim();if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to update this function.`},409);return h(await G_(c,U,g,{memory:s.memory,timeout:s.timeout}))}if(w.pathname==="/api/serverless/alarms"&&S.method==="GET")return h(await Z_(c,U));if(w.pathname==="/api/serverless/alarms"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.preset??"").trim(),_=Number(s.threshold);if(!g)return h({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(_))return h({ok:!1,error:"A numeric threshold is required."},422);return h(await Y_(c,U,g,_))}if(w.pathname==="/api/serverless/alarms"&&S.method==="DELETE"){let s=await S.json().catch(()=>({})),g=String(s.name??"").trim();if(!g)return h({ok:!1,error:"An alarm name is required."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to delete this alarm.`},409);return h(await X_(c,U,g))}if(w.pathname==="/api/serverless/traces"&&S.method==="GET"){let s=Number(w.searchParams.get("minutes"))||30;return h(await lo(c,U,s))}if(w.pathname==="/api/serverless/scheduler"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.action??"").trim();if(g!=="enable"&&g!=="disable"&&g!=="run")return h({ok:!1,error:"Unknown scheduler action."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to ${g} the scheduler.`},409);return h(await Wl(c,U,g))}if(!yR(w.pathname,Be))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(U)}`}});let Fr=await me(z,U);if(!Fr)return Eo("ts-cloud dashboard UI is unavailable.",503);return PR(Fr,w.pathname)}catch(dr){if(t.verbose)console.error(dr);return h({ok:!1,error:dr?.message??String(dr)},500)}})();if(!Lt)return Lt;if(_t&&(w.pathname.startsWith("/api/")||w.pathname.startsWith("/auth/"))){let it;if((V.headers.get("content-type")||"").includes("application/json"))it=await V.json().catch(()=>{return});let pt=Bt.resolveUser(S),Zt=pt?X(pt).actor:void 0;o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,actorId:Zt?.id,correlationId:tt,type:Lt.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Lt.status<400?"info":"warning",payload:zP(S.method,w.pathname,it,Lt.status,Date.now()-Z)})}return Lt.headers.set("x-request-id",tt),Lt}});Sc?.start();let fE=t.spendLoop??!0,og;if(fE)(async()=>{let{SpendRunner:S,SpendLoopLease:x,startSpendLoop:Z}=await import("./chunk-qk9qgepa.js"),{store:V}=await vR(o.store),tt=new S({controlPlane:o.store,store:V,alerts:nt});og=Z(tt,{lease:new x(o.store,{owner:`dashboard:${process.pid}`}),onError:(_t)=>console.error(`[ts-cloud] spend cycle failed: ${_t instanceof Error?_t.message:String(_t)}`)})})();let _E=Hr.stop.bind(Hr);return Hr.stop=(S)=>{clearInterval(rg),clearInterval(ig),clearInterval(cg),clearInterval(ng),clearInterval(eg),clearInterval(pl),clearInterval(ml),clearInterval(ql),clearInterval(tg),Le(),Vt.clear(),Sc?.stop(),og?.();let x=_E(S);if(Sc)Sc.settled().finally(()=>o.store.close());else o.store.close();return x},{server:Hr,url:`http://${n}:${Hr.port}/`}}
512
512
  export{Tc as w,Gn as x,ia as y,zf as z,$S as A,K_ as B,Zi as C,Bs as D,zs as E,Ls as F,Fs as G,Ms as H,Qs as I,Ws as J,Us as K,Hs as L,Hi as M,Li as N,Aa as O,Lu as P,Zc as Q,Da as R,ya as S,Pa as T,$a as U,va as V,Ca as W,Oa as X,Ja as Y,pr as Z,Ba as _,No as $,Qr as aa,Pc as ba,$c as ca,bi as da,mg as ea,Nr as fa,ko as ga,Fe as ha,Jo as ia,zo as ja,bo as ka,wc as la,oo as ma,Dl as na,ao as oa,nc as pa,Ji as qa,lr as ra,Xi as sa,pi as ta,Md as ua,Ye as va,$f as wa,sb as xa,lb as ya,Gd as za,Sb as Aa,kr as Ba,lg as Ca,jc as Da,fr as Ea,_r as Fa,sa as Ga,la as Ha,ga as Ia,ha as Ja,Ra as Ka,Ia as La,Mc as Ma,M1 as Na,Zs as Oa,Ys as Pa,nf as Qa,an as Ra,Ll as Sa,Sj as Ta};