@stacksjs/ts-cloud 0.12.12 → 0.12.14
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.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-16rs9egs.js +6 -0
- package/dist/bin/chunk-1j2sja1j.js +1 -0
- package/dist/bin/chunk-1rcsm0px.js +1 -0
- package/dist/bin/chunk-1s4dny8d.js +1 -0
- package/dist/bin/chunk-1wvrtg42.js +8 -0
- package/dist/bin/chunk-1x7mm26k.js +1 -0
- package/dist/bin/chunk-2paqksap.js +6 -0
- package/dist/bin/chunk-3gwmejhk.js +1 -0
- package/dist/bin/chunk-4201mvaj.js +2 -0
- package/dist/bin/chunk-49sthm4q.js +2 -0
- package/dist/bin/chunk-4yntpqbe.js +1 -0
- package/dist/bin/chunk-4zbnwt9b.js +2 -0
- package/dist/{chunk-2ybcnrte.js → bin/chunk-57w9nsjk.js} +3 -3
- package/dist/bin/chunk-61ysn56t.js +1 -0
- package/dist/bin/chunk-6vay4ggv.js +9 -0
- package/dist/bin/{chunk-wcem4cqb.js → chunk-7a7n6p2m.js} +2 -2
- package/dist/bin/chunk-7x0hrna6.js +1 -0
- package/dist/bin/{chunk-e2dnxp8d.js → chunk-80zkjpfz.js} +29 -29
- package/dist/bin/chunk-92nng29y.js +1 -0
- package/dist/bin/chunk-94cfdvrn.js +2 -0
- package/dist/bin/chunk-9q8zjavc.js +725 -0
- package/dist/bin/chunk-a929za72.js +2 -0
- package/dist/{chunk-ac87ds1k.js → bin/chunk-bckm6fre.js} +6 -6
- package/dist/bin/chunk-bj5nq0kn.js +7364 -0
- package/dist/bin/chunk-c51xp8f7.js +1 -0
- package/dist/bin/chunk-d7r6mhyv.js +34 -0
- package/dist/bin/chunk-dbmk60r7.js +60 -0
- package/dist/bin/chunk-dhxwmkhz.js +2 -0
- package/dist/bin/chunk-f1ke4ygp.js +1 -0
- package/dist/bin/chunk-f35pte64.js +44 -0
- package/dist/bin/{chunk-t5ngva49.js → chunk-f8mbjwme.js} +8 -8
- package/dist/bin/chunk-fnr6k11h.js +1 -0
- package/dist/bin/chunk-mzfct5en.js +1 -0
- package/dist/bin/chunk-n6qqa2fr.js +511 -0
- package/dist/bin/chunk-ngav845g.js +2 -0
- package/dist/bin/chunk-nrnq9adz.js +1 -0
- package/dist/bin/chunk-p36ns96s.js +1 -0
- package/dist/bin/chunk-pega3x2x.js +1 -0
- package/dist/bin/chunk-pt2bz3kr.js +1 -0
- package/dist/bin/chunk-q5aj280b.js +1 -0
- package/dist/bin/chunk-r6cvc2pr.js +1 -0
- package/dist/bin/chunk-rh2sqtew.js +1 -0
- package/dist/bin/chunk-rpg5k3wt.js +3 -0
- package/dist/bin/chunk-tkzpbb7n.js +1 -0
- package/dist/bin/chunk-vwyq2s2k.js +1 -0
- package/dist/bin/chunk-vx649y7t.js +1 -0
- package/dist/bin/chunk-vymg9ywg.js +2 -0
- package/dist/bin/chunk-w637s5q0.js +3 -0
- package/dist/bin/chunk-wge61ccr.js +2 -0
- package/dist/bin/{chunk-jxd3j00s.js → chunk-wr6a423y.js} +13 -13
- package/dist/bin/chunk-y7ece16e.js +111 -0
- package/dist/bin/chunk-ydpnsp4x.js +3 -0
- package/dist/bin/{chunk-t7rcfwqc.js → chunk-yhxpmk29.js} +32 -32
- package/dist/bin/chunk-yn34zgr2.js +1 -0
- package/dist/bin/chunk-ynr22ma8.js +2 -0
- package/dist/bin/chunk-yt8rgkqt.js +2 -0
- package/dist/bin/chunk-z2ez8wn9.js +37 -0
- package/dist/bin/cli.js +428 -428
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-30h9rgfn.js +6 -0
- package/dist/chunk-3kapcdpn.js +92 -0
- package/dist/chunk-5g1hsrab.js +4 -0
- package/dist/chunk-5qqb671d.js +1 -0
- package/dist/chunk-5ww7kc5z.js +114 -0
- package/dist/chunk-6g81m01r.js +141 -0
- package/dist/{chunk-q9a1z53k.js → chunk-6j8f4ahv.js} +51 -51
- package/dist/{chunk-6cxb8d6y.js → chunk-6nvn041c.js} +3 -3
- package/dist/chunk-7hy9p6xr.js +5 -0
- package/dist/chunk-7kwha0fw.js +585 -0
- package/dist/chunk-9mhcjht7.js +37 -0
- package/dist/chunk-9w32efae.js +1 -0
- package/dist/chunk-bqaqkmtr.js +2 -0
- package/dist/chunk-djd9xgkz.js +709 -0
- package/dist/chunk-e0919h5g.js +2 -0
- package/dist/{chunk-dndxwssj.js → chunk-e7ds04wb.js} +2 -2
- package/dist/chunk-fdexq9e1.js +1 -0
- package/dist/chunk-hw3p6pth.js +1 -0
- package/dist/chunk-jb8em9ba.js +2 -0
- package/dist/chunk-pkan6evc.js +2 -0
- package/dist/chunk-qzwack6w.js +44 -0
- package/dist/chunk-r5emv4x8.js +2 -0
- package/dist/chunk-thpce63q.js +34 -0
- package/dist/chunk-ttq6dvft.js +22 -0
- package/dist/chunk-vpy3zjqv.js +1 -0
- package/dist/chunk-vva43vnp.js +60 -0
- package/dist/{bin/chunk-m9r5jype.js → chunk-wjgnfg6q.js} +6 -6
- package/dist/chunk-wrnhbb13.js +1 -0
- package/dist/chunk-xxbvjq8g.js +7355 -0
- package/dist/chunk-zftpjxkr.js +2 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.d.ts +1 -0
- package/dist/drivers/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +91 -91
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/push/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +1 -1
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +7 -7
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +9 -9
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +9 -9
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +17 -17
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +5 -5
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +5 -5
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +5 -5
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +5 -5
- package/dist/ui/serverless.html +6 -6
- package/dist/ui-src/src/charts.ts +1141 -1294
- package/dist/ui-src/src/topology.ts +3 -3
- package/package.json +3 -3
- package/dist/bin/chunk-0b49jjgr.js +0 -2
- package/dist/bin/chunk-0xnnkeb1.js +0 -1
- package/dist/bin/chunk-227jmf2b.js +0 -2
- package/dist/bin/chunk-2nyyg44g.js +0 -1
- package/dist/bin/chunk-2ztr119n.js +0 -3
- package/dist/bin/chunk-43xj5cny.js +0 -1
- package/dist/bin/chunk-5w6y9pmz.js +0 -1
- package/dist/bin/chunk-5x4rdx8k.js +0 -37
- package/dist/bin/chunk-6zc6a6t3.js +0 -725
- package/dist/bin/chunk-7aagqqr9.js +0 -1
- package/dist/bin/chunk-85qrgshq.js +0 -44
- package/dist/bin/chunk-8zk8msx0.js +0 -2
- package/dist/bin/chunk-9j83q0r4.js +0 -1
- package/dist/bin/chunk-9nhqbes6.js +0 -60
- package/dist/bin/chunk-a4js49mx.js +0 -1
- package/dist/bin/chunk-a9e0hvwe.js +0 -6
- package/dist/bin/chunk-a9tgxf2h.js +0 -1
- package/dist/bin/chunk-aahrv359.js +0 -1
- package/dist/bin/chunk-bfx23be3.js +0 -1
- package/dist/bin/chunk-bpps61am.js +0 -111
- package/dist/bin/chunk-bzth6d1s.js +0 -6
- package/dist/bin/chunk-ca3taw2m.js +0 -1
- package/dist/bin/chunk-cgzp0328.js +0 -1
- package/dist/bin/chunk-d2aaef9v.js +0 -1
- package/dist/bin/chunk-e0z2t4mf.js +0 -6
- package/dist/bin/chunk-empfsmdk.js +0 -2
- package/dist/bin/chunk-er3mww4m.js +0 -1
- package/dist/bin/chunk-fmp5bv0j.js +0 -3
- package/dist/bin/chunk-g3kp5ddx.js +0 -1
- package/dist/bin/chunk-grepda40.js +0 -1
- package/dist/bin/chunk-h6xqtypj.js +0 -2
- package/dist/bin/chunk-hwk9ahms.js +0 -2
- package/dist/bin/chunk-k1xw3zbm.js +0 -34
- package/dist/bin/chunk-m07s5esk.js +0 -2
- package/dist/bin/chunk-n20kbxwb.js +0 -7364
- package/dist/bin/chunk-n2fnav53.js +0 -3
- package/dist/bin/chunk-nv211m42.js +0 -8
- package/dist/bin/chunk-psgjy3z4.js +0 -1
- package/dist/bin/chunk-qmnr82da.js +0 -1
- package/dist/bin/chunk-qqpb82ty.js +0 -2
- package/dist/bin/chunk-rqc8btkj.js +0 -2
- package/dist/bin/chunk-rs85xvt7.js +0 -1
- package/dist/bin/chunk-sj5csg49.js +0 -2
- package/dist/bin/chunk-tjgy10zm.js +0 -9
- package/dist/bin/chunk-v0beqdna.js +0 -1
- package/dist/bin/chunk-vf2s3tba.js +0 -1
- package/dist/bin/chunk-vzkfjrx2.js +0 -511
- package/dist/bin/chunk-wsh5ervz.js +0 -1
- package/dist/bin/chunk-xenhbdmr.js +0 -1
- package/dist/bin/chunk-xrdpxwbf.js +0 -1
- package/dist/bin/chunk-y68m9bx7.js +0 -2
- package/dist/chunk-4884der5.js +0 -1
- package/dist/chunk-4wdxsnn2.js +0 -44
- package/dist/chunk-5hhyyhjt.js +0 -1
- package/dist/chunk-5zkacdw1.js +0 -1
- package/dist/chunk-6f68caq0.js +0 -1
- package/dist/chunk-7z50g5xz.js +0 -4
- package/dist/chunk-8fh4m5ge.js +0 -1
- package/dist/chunk-97pb7wb1.js +0 -1
- package/dist/chunk-ea7tn8nn.js +0 -709
- package/dist/chunk-ess6vxfj.js +0 -2
- package/dist/chunk-j06r5rwv.js +0 -2
- package/dist/chunk-j1g67djb.js +0 -92
- package/dist/chunk-k8x8mrkr.js +0 -2
- package/dist/chunk-mnmz8t7q.js +0 -34
- package/dist/chunk-n1fyryha.js +0 -141
- package/dist/chunk-n1hg0jxs.js +0 -2
- package/dist/chunk-n5xmh0ma.js +0 -37
- package/dist/chunk-q22qfwsc.js +0 -22
- package/dist/chunk-r8t25tbm.js +0 -7355
- package/dist/chunk-t8hzekmk.js +0 -585
- package/dist/chunk-whyttetx.js +0 -5
- package/dist/chunk-yf8stygs.js +0 -114
- package/dist/chunk-ze5x2bpm.js +0 -2
- package/dist/chunk-zh0apedk.js +0 -60
- package/dist/chunk-zjyz926j.js +0 -2
|
@@ -1,511 +0,0 @@
|
|
|
1
|
-
import{Xa as sb}from"./chunk-sj5csg49.js";import{Ab as ma,Bb as rb,Jc as rp,Ya as Vo,Za as xe,_a as Uy,bd as X,cb as Do,cc as tp,cd as Qa,dd as np,ed as ep,gb as zy,hb as Vy,ib as qy,jb as Jy,kb as Wy,lb as Hy,mb as Gy,ob as Oo,pb as Hl,qb as _o,rb as Ky,sb as Yy,tb as Xy,ub as Ei,vb as po,wb as Zy,xb as eb,yb as my,zb as tb}from"./chunk-bpps61am.js";import{gd as Sn}from"./chunk-hwk9ahms.js";import{wd as Du}from"./chunk-t7rcfwqc.js";import{Ad as wh,xd as vh}from"./chunk-fmp5bv0j.js";import{Bd as hf,Cd as Ii,Gd as fa}from"./chunk-2ztr119n.js";import{Hd as uo}from"./chunk-0b49jjgr.js";import{Id as co,Pd as jh,Qd as Fh,Rd as Ru,Sd as xu,Xd as lt,Yd as Uh}from"./chunk-n2fnav53.js";import{_d as Vs}from"./chunk-8zk8msx0.js";import{$d as Oy,Ce as xr,Se as ca,Ve as ib,We as ob,Xe as fo,Ye as Au,gf as ha,ve as xm,we as Dm}from"./chunk-6zc6a6t3.js";import{Cf as Qy}from"./chunk-e0z2t4mf.js";import{$f as Iu,Gf as yh,Jf as bh,Pf as Sh,Qf as eh,Vf as th,Xf as gu}from"./chunk-tjgy10zm.js";import{tg as nb}from"./chunk-rqc8btkj.js";import{vg as Bh}from"./chunk-h6xqtypj.js";import{Cg as hr}from"./chunk-e2dnxp8d.js";import{Dg as _y,Gg as Ny,Hg as $y,Ig as My,Jg as Ly,Kg as jy,Lg as Fy}from"./chunk-nv211m42.js";import{Mg as Fo,Ng as $f,Og as zt,Pg as mo,Qg as $e,Rg as Mf,Sg as By}from"./chunk-jxd3j00s.js";import{ph as pe}from"./chunk-bzth6d1s.js";import{Ao as Lh,Kh as km,Nh as Bo,Oh as at,Rh as Pr,Th as it,Yh as Xd,mi as Mh}from"./chunk-n20kbxwb.js";import{Bp as ct}from"./chunk-m07s5esk.js";import{createHash as AT}from"node:crypto";import{existsSync as _r,mkdtempSync as Vu,readdirSync as wy,rmSync as Ln,statSync as ab}from"node:fs";import{readFile as ur,writeFile as $n}from"node:fs/promises";import{tmpdir as Sa}from"node:os";import{dirname as kT,extname as ho,join as Ie,normalize as RT,relative as PT,resolve as xT,sep as DT}from"node:path";import{fileURLToPath as OT}from"node:url";class Ra extends Error{status;code;requestId;constructor(e,t,r,n){super(r);this.status=e;this.code=t;this.requestId=n}}class ll{options;baseUrl;fetchFn;constructor(e){this.options=e;this.baseUrl=e.baseUrl.replace(/\/$/,""),this.fetchFn=e.fetch??fetch}async request(e,t={}){let r=await this.fetchFn(`${this.baseUrl}${e}`,{...t,headers:{accept:"application/json",authorization:`Bearer ${this.options.token}`,...t.headers}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Ra(r.status,n.error?.code??"api_error",n.error?.message??"API request failed.",n.error?.requestId??r.headers.get("x-request-id")??void 0);return n}listProjects(e={}){return this.request(`/api/v1/projects?${new URLSearchParams(Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,String(r)])))}`)}listEnvironments(e,t={}){return this.request(`/api/v1/projects/${encodeURIComponent(e)}/environments?${new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)])))}`)}listServices(e,t){return this.request(`/api/v1/services?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}listOperations(e){return this.request(`/api/v1/operations${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listComposeTemplates(){return this.request("/api/v1/compose-templates")}listComposeApplications(e,t){return this.request(`/api/v1/compose-applications?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}previewCompose(e){return this.request("/api/v1/compose-applications/preview",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createComposeApplication(e){return this.request("/api/v1/compose-applications",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}composeServices(e){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/services`)}composeAction(e,t,r={}){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}releaseCapabilities(e,t={}){return this.request(`/api/v1/releases/capabilities?${new URLSearchParams({kind:e,health:String(!!t.health),replicas:String(t.replicas??1)})}`)}listReleases(e,t={}){return this.request(`/api/v1/releases?${new URLSearchParams({projectId:e,...t})}`)}createReleaseArtifact(e){return this.request("/api/v1/release-artifacts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createRelease(e){return this.request("/api/v1/releases",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}releaseAction(e,t,r={}){return this.request(`/api/v1/releases/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}createDeployment(e,t){return this.request("/api/v1/deployments",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}detectApplication(e){return this.request("/api/v1/application-detections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}planApplication(e){return this.request("/api/v1/application-plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}listApplicationDrafts(e){return this.request(`/api/v1/application-drafts?projectId=${encodeURIComponent(e)}`)}createApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createApplication(e,t){return this.request("/api/v1/applications",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}uploadApplicationArtifact(e,t,r){return this.request("/api/v1/application-artifacts",{method:"POST",headers:{"content-type":"application/octet-stream","x-project-id":e,"x-artifact-filename":t},body:r})}listRegistryConnections(){return this.request("/api/v1/registry-connections")}createRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}disconnectRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({id:e})})}listQueue(e={}){let t=new URLSearchParams(Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)]));return this.request(`/api/v1/queue?${t}`)}operationLogs(e,t={}){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==void 0).map(([n,i])=>[n,String(i)]));return this.request(`/api/v1/operations/${encodeURIComponent(e)}/logs?${r}`)}streamOperationLogs(e,t=0){return this.fetchFn(`${this.baseUrl}/api/v1/operations/${encodeURIComponent(e)}/logs/stream`,{headers:{accept:"text/event-stream",authorization:`Bearer ${this.options.token}`,"last-event-id":String(t)}})}cancelOperation(e){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/cancel`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}retryOperation(e,t,r=0){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({errorClass:t,delayMs:r})})}queueSettings(){return this.request("/api/v1/queue/settings")}updateQueueSettings(e){return this.request("/api/v1/queue/settings",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"update queue limits",concurrency:e})})}listPreviews(e){return this.request(`/api/v1/previews${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listPreviewDefinitions(e){return this.request(`/api/v1/preview-definitions?projectId=${encodeURIComponent(e)}`)}createPreviewDefinition(e){return this.request("/api/v1/preview-definitions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createPreview(e){return this.request("/api/v1/previews",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}destroyPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/destroy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:t})})}extendPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/extend`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hours:t})})}rebuildPreview(e){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/rebuild`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}usage(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/usage${t.size>0?`?${t}`:""}`)}usageRollups(e){let t=new URLSearchParams({from:e.from,to:e.to});if(e.projectId)t.set("projectId",e.projectId);if(e.environmentId)t.set("environmentId",e.environmentId);if(e.limit)t.set("limit",String(e.limit));for(let r of e.meters??[])t.append("meter",r);return this.request(`/api/v1/usage/rollups?${t}`)}allowance(e="deploy",t={}){let r=new URLSearchParams({operation:e});if(t.projectId)r.set("projectId",t.projectId);if(t.environmentId)r.set("environmentId",t.environmentId);return this.request(`/api/v1/spend/allowance?${r}`)}budgets(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/spend/budgets${t.size>0?`?${t}`:""}`)}anomalies(e={}){let t=new URLSearchParams;if(e.projectId)t.set("projectId",e.projectId);if(e.since)t.set("since",e.since);if(e.unacknowledged)t.set("unacknowledged","true");return this.request(`/api/v1/spend/anomalies${t.size>0?`?${t}`:""}`)}}import{createHash as gS}from"node:crypto";import{lstatSync as Ib,readdirSync as Cb,readFileSync as Eb}from"node:fs";import{relative as Tb,resolve as pl,sep as Ab}from"node:path";function kb(e){return new Map(e.map((t)=>[t.path.replace(/^\.\//,"").replace(/\\/g,"/"),t]))}function dn(e,t,r){return{path:e,reason:t,weight:r}}function gl(e){try{return e?.content?JSON.parse(e.content):{}}catch{return{}}}function Vn(e,t,r,n,i,o){return{framework:e,strategy:t,confidence:r,evidence:n,defaults:{build:i,runtime:{target:t==="static"?"serverless":t==="serverless"?"serverless":t==="dockerfile"||t==="prebuilt_image"?"container":"server",architecture:"x86_64",port:t==="static"||t==="serverless"?void 0:3000,healthCheck:t==="static"?void 0:{protocol:"http",path:"/health"}}},description:o}}function qn(e){let t=kb(e.slice(0,1e4)),r=[];if(t.has("Dockerfile"))r.push(Vn("dockerfile","dockerfile",0.99,[dn("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 n=gl(t.get("composer.json"));if(t.has("artisan")&&n.require?.["laravel/framework"])r.push(Vn("laravel","server",0.98,[dn("artisan","Laravel Artisan entrypoint is present.",0.45),dn("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(t.has("composer.json"))r.push(Vn("php","server",0.82,[dn("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=gl(t.get("package.json"));if(t.has("package.json")){let o=t.has("bun.lock")||t.has("bun.lockb")||i.engines?.bun,s=o?"bun":"node",c=o?"bun":"node",u=[dn("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(o)u.push(dn(t.has("bun.lock")?"bun.lock":t.has("bun.lockb")?"bun.lockb":"package.json","Pins the Bun package manager/runtime.",0.35));let a=!!(i.dependencies?.vite||i.devDependencies?.vite||i.dependencies?.["@stacksjs/bunpress"]||i.devDependencies?.["@stacksjs/bunpress"])&&!i.scripts?.start,p=a?{kind:"static",installCommand:`${s} install --frozen-lockfile`,buildCommand:`${s} run build`,publishDirectory:"dist"}:{kind:"server",runtime:s,installCommand:`${s} install --frozen-lockfile`,buildCommand:i.scripts?.build?`${s} run build`:void 0,startCommand:i.scripts?.start?`${s} run start`:s==="bun"?"bun run index.ts":"node index.js"};r.push(Vn(c,p.kind,Math.min(0.94,u.reduce((f,y)=>f+y.weight,0)),u,p,a?"Install dependencies, build static assets, and publish the output directory.":`Install dependencies, build if configured, and start the ${s} server.`))}if(!r.length&&(t.has("index.html")||t.has("public/index.html")))r.push(Vn("static","static",0.78,[dn(t.has("index.html")?"index.html":"public/index.html","A static HTML entrypoint is present.",0.78)],{kind:"static",publishDirectory:t.has("index.html")?".":"public"},"Publish the static directory without a runtime process."));if(!r.length)r.push(Vn("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return r.sort((o,s)=>s.confidence-o.confidence||o.framework.localeCompare(s.framework))}function Pa(e,t={}){let r=pl(e),n=t.maxFiles??1e4,i=t.maxContentBytes??262144,o=[],s=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),c=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),u=(a)=>{for(let p of Cb(a).sort()){if(c.has(p))continue;let f=pl(a,p),y=Tb(r,f).split(Ab).join("/");if(!y||y.startsWith("../"))throw Error("Detection path escaped the application root");let b=Ib(f);if(b.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${y}`);if(b.isDirectory())u(f);else if(b.isFile()){if(o.length>=n)throw Error("Application file-count limit exceeded");let C={path:y,size:b.size};if(s.has(y)&&b.size<=i)C.content=Eb(f,"utf8");o.push(C)}}};return u(r),o}function Da(e){if(Array.isArray(e))return`[${e.map(Da).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Da(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function Pi(e){return!!e&&!e.startsWith("/")&&!e.split("/").includes("..")&&!/[\0\r\n]/.test(e)}function It(e,t,r,n){return{path:e,code:t,message:r,alternatives:n}}function xa(e){return JSON.parse(JSON.stringify(e))}function Rb(e){let t=Object.fromEntries(Object.entries(e.environment??{}).map(([r,n])=>[r,typeof n==="string"?n:`\${${n.secretRef}}`]));if(e.build.kind==="prebuilt_image"||e.build.kind==="dockerfile")return xa({infrastructure:{containers:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,cpu:e.runtime.cpu,memory:e.runtime.memoryMb,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,environment:t}}}});if(e.runtime.target==="serverless"||e.build.kind==="serverless")return xa({serverless:{apps:{[e.slug]:{source:e.source,build:e.build,architecture:e.runtime.architecture,environment:t,domain:e.domain}}}});return xa({sites:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,env:t,domain:e.domain?.hostname}}})}function Ft(e,t=[]){let r=[],n=(C)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(C),i=Object.fromEntries(Object.entries(e.environment??{}).map(([C,T])=>{if(typeof T==="string"&&n(C))return r.push(It(`environment.${C}`,"write_only_secret_required",`${C} must be supplied through the write-only secrets boundary.`)),[C,{secretRef:C}];return[C,T]})),o=e.build;if(e.build.kind==="dockerfile"&&e.build.buildArgs){let C=Object.fromEntries(Object.entries(e.build.buildArgs).map(([T,R])=>{if(n(T))return r.push(It(`build.buildArgs.${T}`,"write_only_build_secret_required",`${T} must be declared in secretNames instead of buildArgs.`)),[T,"[REDACTED]"];return[T,R]}));o={...e.build,buildArgs:C}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.slug))r.push(It("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!Pi((e.source.kind==="git"?e.source.monorepoRoot:e.source.kind==="local"?e.source.root:".")??"."))r.push(It("source","unsafe_source_root","Source root must stay inside the source tree."));if(e.source.kind==="git"&&e.source.sparsePaths?.some((C)=>!Pi(C)))r.push(It("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(e.build.kind==="dockerfile"&&(!Pi(e.build.context)||!Pi(e.build.dockerfile)))r.push(It("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(e.build.kind==="static"&&!Pi(e.build.publishDirectory))r.push(It("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(e.build.kind==="server"&&!e.build.startCommand.trim())r.push(It("build.startCommand","missing_start_command","A server start command is required.",["Use static output","Use a Dockerfile"]));if(e.source.kind==="image"&&e.build.kind!=="prebuilt_image")r.push(It("build.kind","image_requires_prebuilt","An OCI image source must use the prebuilt-image strategy.",["Select prebuilt image"]));if(e.build.kind==="prebuilt_image"&&e.runtime.target!=="container")r.push(It("runtime.target","image_requires_container","Prebuilt images require the container runtime target.",["Select container target"]));if(e.runtime.target==="serverless"&&e.build.kind==="dockerfile")r.push(It("runtime.target","unsupported_serverless_dockerfile","Dockerfile builds currently target the container service path.",["Select container target","Select serverless package"]));if(e.runtime.port!==void 0&&(!Number.isInteger(e.runtime.port)||e.runtime.port<1||e.runtime.port>65535))r.push(It("runtime.port","invalid_port","Port must be an integer from 1 to 65535."));let s=e.runtime.healthCheck;if(s&&s.protocol!=="tcp"&&(!s.path||!s.path.startsWith("/")||/[\r\n]/.test(s.path)))r.push(It("runtime.healthCheck.path","invalid_health_path","HTTP health checks require a path beginning with /."));if(e.domain?.hostname&&(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(e.domain.hostname)||e.domain.hostname.includes("..")))r.push(It("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let c=Object.values(i).flatMap((C)=>typeof C==="object"?[C.secretRef]:[]),u=[...new Set([...e.requiredSecretNames??[],...e.build.kind==="dockerfile"?e.build.secretNames??[]:[],...c])].sort(),a=new Set(t),p=u.filter((C)=>!a.has(C)),f={apiVersion:"ts-cloud.dev/v1",kind:"Application",metadata:{name:e.name,slug:e.slug,projectId:e.projectId,environmentId:e.environmentId},spec:{source:e.source,build:o,runtime:e.runtime,environment:i,domain:e.domain}},y=[...new Set([e.source.kind==="git"?"git:read":e.source.kind==="image"?"registry:pull":e.source.kind==="artifact"?"artifact:inspect":"filesystem:read",e.runtime.target==="container"?"containers":e.runtime.target==="serverless"?"serverless":"servers",e.domain?"dns":""])].filter(Boolean).sort(),b=[...new Set([e.runtime.target,e.runtime.cpu?`${e.runtime.cpu} vCPU`:"",e.runtime.memoryMb?`${e.runtime.memoryMb} MB memory`:"",(e.runtime.minInstances??0)>0?`${e.runtime.minInstances} minimum instances`:"scales from zero where supported",e.domain?"managed DNS/TLS":""])].filter(Boolean);return{valid:r.length===0&&p.length===0,issues:r,missingSecrets:p,manifest:f,configPatch:Rb({...e,build:o,environment:i}),capabilityRequirements:y,costDrivers:b,serializedManifest:`${Da(f)}
|
|
2
|
-
`}}function ml(e){let t=e.replace(/\\/g,"/");return!!t&&!t.startsWith("/")&&!/^[A-Za-z]:\//.test(t)&&!t.split("/").includes("..")&&!/[\0\r\n]/.test(t)}function fl(e,t,r={}){let n=r.maxBytes??104857600,i=r.maxEntries??1e4,o=r.maxExpandedBytes??524288000;if(e.byteLength>n)throw Error("Archive exceeds the compressed size limit");let s=new DataView(e.buffer,e.byteOffset,e.byteLength),c=[],u=0;if(t.toLowerCase().endsWith(".zip")||e[0]===80&&e[1]===75){let p=0;while(p+30<=e.length){let f=s.getUint32(p,!0);if(f===33639248||f===101010256)break;if(f!==67324752)throw Error("Malformed ZIP local header");let y=s.getUint16(p+6,!0),b=s.getUint32(p+18,!0),C=s.getUint32(p+22,!0),T=s.getUint16(p+26,!0),R=s.getUint16(p+28,!0);if(y&8)throw Error("ZIP data descriptors are not accepted for uploaded artifacts");let x=new TextDecoder().decode(e.subarray(p+30,p+30+T));if(!ml(x))throw Error(`Unsafe archive path: ${x}`);if(c.push(x),u+=C,c.length>i||u>o)throw Error("Archive expansion limit exceeded");p+=30+T+R+b}return{format:"zip",entries:c.length,expandedBytes:u,paths:c}}if(!t.toLowerCase().match(/\.(?:tar|tar\.gz|tgz)$/))throw Error("Only ZIP and uncompressed TAR artifacts are supported");let a=0;while(a+512<=e.length){let p=e.subarray(a,a+512);if(p.every((T)=>T===0))break;let f=(T,R)=>new TextDecoder().decode(p.subarray(T,T+R)).replace(/\0.*$/,""),y=`${f(345,155)}${f(345,155)?"/":""}${f(0,100)}`,b=Number.parseInt(f(124,12).trim()||"0",8),C=String.fromCharCode(p[156]??0);if(!ml(y))throw Error(`Unsafe archive path: ${y}`);if(C==="1"||C==="2")throw Error(`Archive links are not accepted: ${y}`);if(!Number.isFinite(b)||b<0)throw Error("Malformed TAR entry size");if(c.push(y),u+=b,c.length>i||u>o)throw Error("Archive expansion limit exceeded");a+=512+Math.ceil(b/512)*512}return{format:"tar",entries:c.length,expandedBytes:u,paths:c}}var hl=new Set(["source","build","runtime","environment","domain","review"]);function yl(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function bl(e){return/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(e)}function Sl(e){for(let[r,n]of Object.entries(e.environment??{}))if(typeof n==="string"&&bl(r)&&n)throw Error(`${r} must be stored through the write-only secrets boundary`);if(e.build.kind==="dockerfile"){for(let[r,n]of Object.entries(e.build.buildArgs??{}))if(bl(r)&&n)throw Error(`${r} must be declared as a build secret name`)}let t=JSON.stringify(e);if(/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(t))throw Error("Drafts cannot contain credential-bearing URLs")}function vl(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),schemaVersion:Number(e.schema_version),name:String(e.name),step:String(e.step),input:yl(e.input,{}),suppliedSecretNames:yl(e.supplied_secret_names,[]),status:String(e.status),version:Number(e.version),createdByActorId:e.created_by_actor_id?String(e.created_by_actor_id):void 0,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Oa{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}create(e){if(Sl(e.draft),e.draft.projectId!==e.projectId)throw Error("Draft project does not match its storage scope");let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Draft project was not found");let r=this.idFn(),n=this.now(),i=e.step??"source";if(!hl.has(i))throw Error("Invalid draft step");let o=[...new Set(e.suppliedSecretNames??[])].sort(),s=Ft(e.draft,o).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, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.projectId,e.name.trim().slice(0,100),i,JSON.stringify(e.draft),JSON.stringify(o),s,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,actorId:e.actorId,type:"application.draft.created",payload:{draftId:r,step:i,status:s,requiredSecretNames:e.draft.requiredSecretNames??[]}}),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM application_drafts WHERE id=?").get(e);return t?vl(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM application_drafts WHERE project_id=? ORDER BY updated_at DESC").all(e).map(vl)}update(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error(`Application draft ${e} changed since version ${t}`);if(!hl.has(r.step))throw Error("Invalid draft step");if(r.draft.projectId!==n.projectId)throw Error("Draft project cannot be changed");Sl(r.draft);let i=[...new Set(r.suppliedSecretNames??n.suppliedSecretNames)].sort(),o=Ft(r.draft,i).valid?"ready":"draft",s=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=?",[r.draft.name.slice(0,100),r.step,JSON.stringify(r.draft),JSON.stringify(i),o,s,e,t]).changes!==1)throw Error(`Application draft ${e} changed since version ${t}`);return this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,actorId:r.actorId,type:"application.draft.updated",payload:{draftId:e,fromVersion:t,toVersion:t+1,step:r.step,status:o}}),this.get(e)}markApplied(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error(`Application draft ${e} changed since version ${t}`);let i=Ft(n.input,n.suppliedSecretNames);if(!i.valid)throw Error(`Draft is not deployable: ${[...i.issues.map((s)=>s.message),...i.missingSecrets.map((s)=>`Missing secret ${s}`)].join("; ")}`);let o=this.now();return this.controlPlane.database.run("UPDATE application_drafts SET status='applied', step='review', version=version+1, updated_at=? WHERE id=? AND version=?",[o,e,t]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,actorId:r,type:"application.draft.applied",payload:$e({draftId:e,manifest:i.manifest})}),this.get(e)}}import{createCipheriv as Pb,createDecipheriv as xb,createHash as Cl,randomBytes as Db}from"node:crypto";function xi(e){return typeof e==="string"&&e?e:void 0}function _a(e){return Cl("sha256").update(e).digest("hex").slice(0,16)}function wl(e){let t=new URL(e.includes("://")?e:`https://${e}`);if(t.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(t.hostname))throw Error("Registry host must use HTTPS");if(t.username||t.password||t.search||t.hash)throw Error("Registry host cannot contain credentials");return`${t.protocol}//${t.host}`}function Ob(e){return{id:String(e.id),organizationId:String(e.organization_id),provider:String(e.provider),name:String(e.name),host:String(e.host),credentialConfigured:!!e.credential_ciphertext,credentialFingerprint:xi(e.credential_fingerprint),credentialExpiresAt:xi(e.credential_expires_at),status:String(e.status),healthMessage:xi(e.health_message),lastTestedAt:xi(e.last_tested_at),version:Number(e.version),createdByActorId:xi(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Na{controlPlane;key;nowFn;idFn;constructor(e,t){this.controlPlane=e;if(!t.encryptionKey)throw Error("Registry encryption key is required");this.key=Cl("sha256").update(`ts-cloud:registry:${t.encryptionKey}`).digest(),this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}encrypt(e){let t=Db(12),r=Pb("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Registry credential envelope is invalid");let o=xb("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}current(e){let t=Ob(e);return t.status!=="disconnected"&&t.credentialExpiresAt&&new Date(t.credentialExpiresAt).getTime()<=this.nowFn().getTime()?{...t,status:"expired",healthMessage:"Registry credential expired; rotate it before pulling images."}:t}create(e){if(!["docker_hub","ghcr","ecr","gcr","generic"].includes(e.provider))throw Error("A supported registry provider is required");let t=e.credential?JSON.stringify(e.credential):void 0,r=this.idFn(),n=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.provider,e.name.trim().slice(0,80),wl(e.host),t?this.encrypt(t):null,t?_a(t):null,e.credentialExpiresAt??null,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"registry.connection.created",payload:{connectionId:r,provider:e.provider,host:wl(e.host),credentialConfigured:!!t}}),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM registry_connections WHERE id=?").get(e);return t?this.current(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM registry_connections WHERE organization_id=? ORDER BY name").all(e).map((t)=>this.current(t))}credential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM registry_connections WHERE id=?").get(e);return t?.credential_ciphertext?JSON.parse(this.decrypt(String(t.credential_ciphertext))):void 0}rotate(e,t,r={}){let n=this.get(e);if(!n||n.status==="disconnected")throw Error("Registry connection was not found");let i=JSON.stringify(t);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),_a(i),r.expiresAt??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"registry.credential.rotated",payload:{connectionId:e,fingerprint:_a(i),expiresAt:r.expiresAt??null}}),this.get(e)}disconnect(e,t){let r=this.get(e);if(!r)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(),e]),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"registry.connection.disconnected",level:"warning",payload:{connectionId:e}}),this.get(e)}async test(e,t={}){let r=this.get(e);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active registry connection was not found");let n=this.credential(e),i=t.fetch??fetch,o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??15000),c=n?.token?`Bearer ${n.token}`:n?.username||n?.password?`Basic ${Buffer.from(`${n.username??""}:${n.password??""}`).toString("base64")}`:void 0;try{let u=await i(`${r.host}/v2/`,{method:"GET",redirect:"error",signal:o.signal,headers:c?{Authorization:c}:void 0}),a=u.headers.get("www-authenticate")??"";if(u.status===401&&a.startsWith("Bearer ")&&n){let y=Object.fromEntries([...a.slice(7).matchAll(/(\w+)="([^"]+)"/g)].map((x)=>[x[1],x[2]])),b=new URL(y.realm??"");if(b.protocol!=="https:")throw Error("Registry authentication realm must use HTTPS");if(y.service)b.searchParams.set("service",y.service);if(t.image)b.searchParams.set("scope",`repository:${El(t.image).repository}:pull`);let C=await i(b,{signal:o.signal,redirect:"error",headers:c?{Authorization:c}:void 0});if(!C.ok)throw Error(`Registry authentication failed (${C.status})`);let T=await C.json(),R=T.token??T.access_token;if(!R)throw Error("Registry did not return an access token");u=t.image?await Il(i,r.host,t.image,R,o.signal):await i(`${r.host}/v2/`,{signal:o.signal,redirect:"error",headers:{Authorization:`Bearer ${R}`}})}else if(u.ok&&t.image)u=await Il(i,r.host,t.image,n?.token,o.signal,c);let p=u.ok?"healthy":"degraded",f=u.ok?t.image?"Registry image is readable.":"Registry connection is healthy.":`Registry request failed (${u.status})`;return this.controlPlane.database.run("UPDATE registry_connections SET status=?, health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[p,f,this.now(),this.now(),e]),this.get(e)}catch(u){let a=o.signal.aborted?"Registry request timed out.":u instanceof Error?u.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=?",[a.slice(0,1000),this.now(),this.now(),e]),this.get(e)}finally{clearTimeout(s)}}}function El(e){let t=e.replace(/^https?:\/\//,""),r=t.indexOf("/");if(r<1)throw Error("Image must include registry/repository");let n=t.slice(r+1),i=n.lastIndexOf("@"),o=n.lastIndexOf(":"),s=i>=0?i:o>n.lastIndexOf("/")?o:-1,c=s>=0?n.slice(0,s):n,u=s>=0?n.slice(s+1):"latest";if(!/^[A-Za-z0-9_.\/-]+$/.test(c)||!/^[A-Za-z0-9_.:+-]+$/.test(u))throw Error("Image reference is invalid");return{repository:c,reference:u}}async function Il(e,t,r,n,i,o){let s=El(r);return e(`${t}/v2/${s.repository}/manifests/${encodeURIComponent(s.reference)}`,{method:"HEAD",redirect:"error",signal:i,headers:{Accept:"application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json",...n?{Authorization:`Bearer ${n}`}:o?{Authorization:o}:{}}})}import{createHash as _b}from"node:crypto";import{chmodSync as Tl,existsSync as Al,mkdirSync as Nb,renameSync as $b,unlinkSync as kl,writeFileSync as Mb}from"node:fs";import{basename as Lb,join as Bb}from"node:path";function $a(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),filename:String(e.filename),sha256:String(e.sha256),size:Number(e.size),format:String(e.format),entryCount:Number(e.entry_count),expandedBytes:Number(e.expanded_bytes),createdByActorId:e.created_by_actor_id?String(e.created_by_actor_id):void 0,createdAt:String(e.created_at)}}class Ma{controlPlane;root;idFn;nowFn;constructor(e,t){this.controlPlane=e;this.root=at(t.cwd,"artifacts"),this.idFn=t.id??(()=>crypto.randomUUID()),this.nowFn=t.now??(()=>new Date)}create(e){let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Artifact project was not found");let r=Lb(e.filename).slice(0,200);if(!r||r!==e.filename)throw Error("Artifact filename must not contain a path");let n=fl(e.bytes,r),i=_b("sha256").update(e.bytes).digest("hex"),o=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? AND sha256=?").get(e.projectId,i);if(o)return $a(o);let s=this.idFn();Nb(this.root,{recursive:!0,mode:448}),Tl(this.root,448);let c=Bb(this.root,`${s}.archive`),u=`${c}.partial`;try{Mb(u,e.bytes,{mode:384,flag:"wx"}),$b(u,c),Tl(c,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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[s,e.organizationId,e.projectId,r,c,i,e.bytes.byteLength,n.format,n.entries,n.expandedBytes,e.actorId??null,this.nowFn().toISOString()])}catch(a){if(Al(u))kl(u);if(Al(c))kl(c);throw a}return this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,actorId:e.actorId,type:"application.artifact.created",payload:{artifactId:s,filename:r,sha256:i,size:e.bytes.byteLength,entries:n.entries}}),this.get(s)}get(e){let t=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE id=?").get(e);return t?$a(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? ORDER BY created_at DESC").all(e).map($a)}}function Eo(e){let t=e.drafts.get(e.draftId);if(!t||t.version!==e.expectedVersion)throw Error(`Application draft ${e.draftId} changed since version ${e.expectedVersion}`);if(t.status==="applied")throw Error("Application draft was already applied");let r=e.controlPlane.getProject(t.projectId),n=r?e.controlPlane.listEnvironments(r.id).find((a)=>a.id===t.input.environmentId):void 0;if(!r||!n||n.projectId!==r.id||r.organizationId!==t.organizationId)throw Error("Draft deployment scope was not found");if(e.confirmEnvironment!==n.slug)throw Error(`Type ${n.slug} to confirm this deployment target`);let i=Ft(t.input,t.suppliedSecretNames);if(!i.valid)throw Error(`Application plan is invalid: ${[...i.issues.map((a)=>a.message),...i.missingSecrets.map((a)=>`Missing secret ${a}`)].join("; ")}`);let o=e.controlPlane.listResources(r.id,n.id).find((a)=>a.kind==="application"&&a.slug===t.input.slug),s=JSON.parse(JSON.stringify({manifest:i.manifest,configPatch:i.configPatch})),c=o?e.controlPlane.updateResource(o.id,o.version,{name:t.input.name,desiredState:s}):e.controlPlane.createResource({projectId:r.id,environmentId:n.id,kind:"application",slug:t.input.slug,name:t.input.name,desiredState:s,metadata:{source:"application-onboarding",draftId:t.id}}),u=new xe(e.controlPlane).enqueue({projectId:r.id,environmentId:n.id,resourceId:c.id,actorId:e.actorId,kind:"application.create",idempotencyKey:`application-draft:${t.id}:v${t.version}`,correlationId:`application-draft:${t.id}`,input:s,lockKey:`resource:${c.id}`,providerKey:c.provider??"default",buildSlot:t.input.build.kind!=="prebuilt_image",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return e.drafts.markApplied(t.id,t.version,e.actorId),e.controlPlane.appendEvent({organizationId:t.organizationId,projectId:r.id,resourceId:c.id,operationId:u.id,actorId:e.actorId,type:"application.create.queued",payload:{draftId:t.id,environment:n.slug,strategy:t.input.build.kind,costDrivers:i.costDrivers}}),{plan:i,resource:c,operation:u}}function Di(e){let t=["static","compute","serverless_zip","serverless_image"].includes(e.kind),r=["container","compose"].includes(e.kind)&&(e.replicas??1)>1,n=e.kind==="container"||e.kind==="serverless_zip"||e.kind==="serverless_image",i=(o,s)=>s&&(o==="atomic"?e.kind==="static"||e.hasHealthGate:e.hasHealthGate);return[{strategy:"atomic",supported:i("atomic",t),explanation:t?e.hasHealthGate||e.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",r),explanation:r?e.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",n),explanation:n?e.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",n),explanation:n?e.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 To(e,t){let r=Di(e).find((n)=>n.strategy===t);if(!r.supported)throw Error(`${t} is unavailable: ${r.explanation}`);return r}import{createHash as jb}from"node:crypto";var Fb=/^sha256:[a-f0-9]{64}$/,Ub=/^[a-f0-9]{40,64}$/i;function nr(e){return typeof e==="string"&&e?e:void 0}function un(e,t){try{return JSON.parse(String(e))}catch{return t}}function Rl(e){return{id:String(e.id),organizationId:String(e.organization_id),digest:String(e.digest),kind:String(e.kind),uri:String(e.uri),size:Number(e.size),mediaType:String(e.media_type),provenance:un(e.provenance,{}),attestation:un(e.attestation,{}),verifiedAt:String(e.verified_at),createdAt:String(e.created_at)}}function Pl(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),artifactId:String(e.artifact_id),kind:String(e.kind),sourceSha:nr(e.source_sha),configHash:String(e.config_hash),manifest:un(e.manifest,{}),provenance:un(e.provenance,{}),strategy:String(e.strategy),status:String(e.status),healthGate:e.health_gate==null?void 0:un(e.health_gate,void 0),hooks:un(e.hooks,{migrations:"none",preActivate:[],postActivate:[]}),drainSeconds:Number(e.drain_seconds),graceSeconds:Number(e.grace_seconds),automaticRollback:Number(e.automatic_rollback)===1,rollbackAttempts:Number(e.rollback_attempts),previousReleaseId:nr(e.previous_release_id),promotedFromReleaseId:nr(e.promoted_from_release_id),actorId:nr(e.actor_id),trigger:String(e.trigger),pinned:Number(e.pinned)===1,pinReason:nr(e.pin_reason),activatedAt:nr(e.activated_at),failedAt:nr(e.failed_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function zb(e){return{sequence:Number(e.sequence),id:String(e.id),releaseId:String(e.release_id),fromStatus:nr(e.from_status),toStatus:String(e.to_status),trafficPercent:e.traffic_percent==null?void 0:Number(e.traffic_percent),health:un(e.health,{}),message:String(e.message),operationId:nr(e.operation_id),createdAt:String(e.created_at)}}function Vb(e,t){let r=[],n=(i,o,s)=>{if(JSON.stringify(o)===JSON.stringify(s))return;if(o&&s&&typeof o==="object"&&typeof s==="object"&&!Array.isArray(o)&&!Array.isArray(s)){for(let c of[...new Set([...Object.keys(o),...Object.keys(s)])].sort())n(i?`${i}.${c}`:c,o[c],s[c]);return}r.push({path:i,...o!==void 0?{before:o}:{},...s!==void 0?{after:s}:{}})};return n("",e,t),r}class La{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}registerArtifact(e){if(!Fb.test(e.digest)||!/^(?:s3|https|oci|file):/.test(e.uri)||!Number.isInteger(e.size)||e.size<0)throw Error("Artifact requires a SHA-256 digest, supported immutable URI, and non-negative byte size");let t=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE organization_id=? AND digest=?").get(e.organizationId,e.digest);if(t)return Rl(t);let r=this.id(),n=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.digest,e.kind,e.uri,e.size,e.mediaType??"application/octet-stream",JSON.stringify($e(e.provenance??{})),JSON.stringify($e(e.attestation??{})),n,n]),this.getArtifact(r)}getArtifact(e){let t=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE id=?").get(e);return t?Rl(t):void 0}create(e){let t=this.getArtifact(e.artifactId),r=this.controlPlane.getResource(e.resourceId),n=this.controlPlane.listEnvironments(e.projectId).find((f)=>f.id===e.environmentId);if(!t||t.organizationId!==e.organizationId||t.kind!==e.kind)throw Error("Release artifact does not match the organization and deployable kind");if(!r||r.projectId!==e.projectId||r.environmentId!==e.environmentId||!n)throw Error("Release target scope does not match the resource");if(e.sourceSha&&!Ub.test(e.sourceSha))throw Error("Release source must be an immutable commit SHA");To({kind:e.kind,provider:r.provider,hasHealthGate:!!e.healthGate,replicas:e.replicas},e.strategy);let i=$e(e.config),o=jb("sha256").update(JSON.stringify(i)).digest("hex"),s=this.active(e.resourceId),c=this.id(),u=this.now().toISOString(),a=e.approvalRequired?"awaiting_approval":"built",p=e.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[c,e.organizationId,e.projectId,e.environmentId,e.resourceId,e.artifactId,e.kind,e.sourceSha??null,o,JSON.stringify($e(e.manifest)),JSON.stringify($e(e.provenance??{})),e.strategy,a,e.healthGate?JSON.stringify(e.healthGate):null,JSON.stringify(p),Math.max(0,Math.min(3600,Math.floor(e.drainSeconds??30))),Math.max(0,Math.min(3600,Math.floor(e.graceSeconds??30))),e.automaticRollback===!1?0:1,s?.id??null,e.promotedFromReleaseId??null,e.actorId??null,e.trigger??"manual",u,u]),this.recordTransition(c,void 0,a,{message:e.promotedFromReleaseId?"Immutable artifact promoted without rebuild.":"Immutable release record created."}),this.get(c)}get(e){let t=this.controlPlane.database.query("SELECT * FROM releases WHERE id=?").get(e);return t?Pl(t):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM releases ORDER BY created_at DESC, rowid DESC").all().map(Pl).filter((t)=>(!e.projectId||t.projectId===e.projectId)&&(!e.environmentId||t.environmentId===e.environmentId)&&(!e.resourceId||t.resourceId===e.resourceId)&&(!e.status||t.status===e.status))}active(e){return this.list({resourceId:e,status:"active"})[0]}transitions(e){return this.controlPlane.database.query("SELECT * FROM release_transitions WHERE release_id=? ORDER BY sequence").all(e).map(zb)}recordTransition(e,t,r,n){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(),e,t??null,r,n.trafficPercent??null,JSON.stringify($e(n.health??{})),n.message.slice(0,1000),n.operationId??null,this.now().toISOString()])}progress(e,t){let r=this.get(e);if(!r)throw Error(`Release ${e} was not found`);return this.recordTransition(e,r.status,r.status,t),this.transitions(e).at(-1)}transition(e,t,r){let n=this.get(e);if(!n)throw Error(`Release ${e} 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"]}[n.status].includes(t))throw Error(`Invalid release transition ${n.status} → ${t}`);let o=this.now().toISOString();if(t==="active"){let s=this.active(n.resourceId);if(s&&s.id!==e)this.controlPlane.database.run("UPDATE releases SET status='superseded', updated_at=? WHERE id=?",[o,s.id]),this.recordTransition(s.id,"active","superseded",{message:`Superseded by ${e}.`,operationId:r.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=?",[t,t==="rolled_back"?1:0,t,o,t,o,o,e]),this.recordTransition(e,n.status,t,r),this.get(e)}approve(e,t){let r=this.get(e);if(!r||r.status!=="awaiting_approval")throw Error("Release is not awaiting approval");let n=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 (?, ?, ?, ?, ?, ?, ?)",[n,e,r.environmentId,t.decision,t.actorId,t.comment?.slice(0,1000)??null,i]),this.transition(e,t.decision==="approved"?"built":"failed",{message:t.decision==="approved"?"Environment gate approved.":"Environment gate rejected."})}approvals(e){return this.controlPlane.database.query("SELECT * FROM release_approvals WHERE release_id=? ORDER BY created_at").all(e).map((t)=>({id:String(t.id),releaseId:String(t.release_id),environmentId:String(t.environment_id),decision:String(t.decision),actorId:String(t.actor_id),comment:nr(t.comment),createdAt:String(t.created_at)}))}promote(e,t){let r=this.get(e);if(!r||!["active","superseded"].includes(r.status))throw Error("Only a tested active/superseded release can be promoted");return this.create({organizationId:r.organizationId,projectId:r.projectId,environmentId:t.targetEnvironmentId,resourceId:t.targetResourceId,artifactId:r.artifactId,kind:r.kind,sourceSha:r.sourceSha,config:t.config,manifest:r.manifest,provenance:r.provenance,strategy:t.strategy??r.strategy,healthGate:t.healthGate??r.healthGate,hooks:r.hooks,drainSeconds:r.drainSeconds,graceSeconds:r.graceSeconds,automaticRollback:r.automaticRollback,promotedFromReleaseId:r.id,actorId:t.actorId,trigger:"promotion",approvalRequired:t.approvalRequired})}compare(e,t){let r=this.get(e),n=this.get(t);if(!r||!n)throw Error("Both releases are required for comparison");return{artifactChanged:r.artifactId!==n.artifactId,sourceChanged:r.sourceSha!==n.sourceSha,configChanged:r.configHash!==n.configHash,manifestChanges:Vb(r.manifest,n.manifest),dataCaveat:n.hooks.migrations==="none"?"No database migration is recorded.":`Database hooks are ${n.hooks.migrations}; release rollback does not roll back data.`}}pin(e,t,r){if(!this.get(e))throw Error("Release was not found");return this.controlPlane.database.run("UPDATE releases SET pinned=?, pin_reason=?, updated_at=? WHERE id=?",[t?1:0,t?r?.slice(0,500)??"operator":null,this.now().toISOString(),e]),this.get(e)}retentionCandidates(e){let t=Math.max(1,Math.min(100,Math.floor(e.keepPerResource??10))),r=new Map;for(let n of this.list()){let i=r.get(n.resourceId)??[];i.push(n),r.set(n.resourceId,i)}return[...r.values()].flatMap((n)=>n.slice(t)).filter((n)=>new Date(n.createdAt)<e.before&&!n.pinned&&!["active","activating","awaiting_approval"].includes(n.status)&&!this.list().some((i)=>i.previousReleaseId===n.id&&["active","activating"].includes(i.status)))}}class ln{controlPlane;releases;queue;constructor(e){this.controlPlane=e;this.releases=new La(e),this.queue=new xe(e)}enqueueActivation(e,t={}){let r=this.releases.get(e.id);if(!r)throw Error("Release was not found");if(!["built","failed","rolled_back","superseded"].includes(r.status))throw Error(`Release ${r.status} cannot be activated`);let n=t.action??"activate",i=this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,actorId:t.actorId,kind:`release.${n}`,idempotencyKey:`release:${r.id}:${n}:${r.rollbackAttempts}`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:t.targetReleaseId??null},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:r.automaticRollback?2:1,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return this.releases.transition(r.id,"activating",{message:`${n} queued.`,operationId:i.id,trafficPercent:0}),i}completeHealthGate(e,t){let r=this.releases.get(e);if(!r||r.status!=="activating")throw Error("Release is not activating");if(t.healthy)return{release:this.releases.transition(r.id,"active",{message:t.message??"Health gate passed; activation completed.",operationId:t.operationId,trafficPercent:100,health:t.health})};let n=this.releases.transition(r.id,"failed",{message:t.message??"Health gate failed.",operationId:t.operationId,trafficPercent:0,health:t.health}),i=r.previousReleaseId?this.releases.get(r.previousReleaseId):void 0;if(!r.automaticRollback||r.rollbackAttempts>=1||!i)return{release:n};let o=this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"release.rollback",idempotencyKey:`release:${r.id}:automatic-rollback`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:i.id,automatic:!0},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return{release:n,rollbackOperation:o}}enqueueRollback(e,t={}){let r=this.releases.get(e.id);if(!r||r.status!=="active")throw Error("Only the active release can be rolled back");let n=t.targetReleaseId?this.releases.get(t.targetReleaseId):r.previousReleaseId?this.releases.get(r.previousReleaseId):void 0;if(!n||n.resourceId!==r.resourceId||!["superseded","active"].includes(n.status))throw Error("Rollback requires a preserved prior release for the same resource");return this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,actorId:t.actorId,kind:"release.rollback",idempotencyKey:`release:${r.id}:manual-rollback:${n.id}`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:n.id,automatic:!1},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}}function qb(e){if(e.strategy==="canary")return[5,25,50,100].map((t,r)=>({step:`canary-${t}`,trafficPercent:t,waitSeconds:r===3?e.drainSeconds:e.graceSeconds,requiresHealth:!0}));if(e.strategy==="blue_green")return[{step:"green-health",trafficPercent:0,waitSeconds:e.graceSeconds,requiresHealth:!0},{step:"traffic-switch",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!0}];if(e.strategy==="rolling")return[{step:"rolling-replacement",trafficPercent:50,waitSeconds:e.graceSeconds,requiresHealth:!0},{step:"rolling-complete",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!0}];return[{step:"immutable-switch",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!!e.healthGate}]}async function xl(e,t){if(t.release.artifactId!==t.artifact.id)throw Error("Release activation artifact identity changed");To({kind:t.release.kind,hasHealthGate:!!t.release.healthGate,replicas:Number(t.release.manifest?.replicas)||void 0},t.release.strategy);let r=e.capability(t);if(!r.supported)throw Error(`${t.release.strategy} is unavailable in ${e.name}: ${r.explanation}`);return e.activate({...t,transitions:qb(t.release)})}async function Dl(e,t){if(!t.previous)throw Error("Rollback requires the preserved previous release");return e.rollback({...t,transitions:[{step:"rollback",trafficPercent:0,waitSeconds:t.release.drainSeconds,requiresHealth:!0}]})}var Jb=["release.activate","release.rollback"];function Wb(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Ol(e){let t=new ln(e.store),r=async(n)=>{let i=Wb(n.operation.input),o=typeof i.releaseId==="string"?i.releaseId:"",s=t.releases.get(o);if(!s)throw Error(`Queued release ${o||"(missing)"} was not found`);if(s.projectId!==n.operation.projectId||s.environmentId!==n.operation.environmentId||s.resourceId!==n.operation.resourceId)throw Error("Queued release does not match the operation scope");let c=t.releases.getArtifact(s.artifactId);if(!c||c.digest!==t.releases.getArtifact(s.artifactId)?.digest)throw Error("Immutable release artifact is unavailable");let u=typeof i.targetReleaseId==="string"&&i.targetReleaseId?i.targetReleaseId:s.previousReleaseId,a=u?t.releases.get(u):void 0;if(a&&(a.resourceId!==s.resourceId||a.artifactId===s.artifactId&&a.id===s.id))throw Error("Rollback target does not match the release resource");let p=await e.resolveDriver(s);n.checkpoint("verify",`Verifying ${c.digest} and ${s.configHash} for ${p.name}.`),n.log(`Artifact ${c.digest}; source ${s.sourceSha??"not recorded"}; config ${s.configHash}.`,{stream:"system"}),n.throwIfCancellationRequested();let f;try{f=n.operation.kind==="release.rollback"?await Dl(p,{release:s,artifact:c,previous:a}):await xl(p,{release:s,artifact:c,previous:a})}catch(y){if(n.operation.kind==="release.activate"&&t.releases.get(s.id)?.status==="activating")t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,message:y instanceof Error?y.message:String(y)});throw y}for(let y of f.transitions)t.releases.progress(s.id,{message:`${n.operation.kind==="release.rollback"?"Rollback":"Activation"} traffic at ${y.trafficPercent}%.`,trafficPercent:y.trafficPercent,health:y.observed,operationId:n.operation.id}),n.log(`Traffic ${y.trafficPercent}%: ${y.healthy?"healthy":"unhealthy"}.`,{stream:y.healthy?"step":"stderr",step:"health"});if(n.checkpoint("health","Evaluating the provider health result."),!f.activated||!f.healthy){if(n.operation.kind==="release.activate"&&t.releases.get(s.id)?.status==="activating")t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,health:{resourceVersions:f.resourceVersions},message:f.error??"Provider health gate failed."});throw Error(f.error??`${p.name} reported an unhealthy release`)}if(n.operation.kind==="release.activate"&&s.healthGate?.name){if(!e.resolveHealthGate)throw t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,message:`Named health gate ${s.healthGate.name} is not available to this worker.`}),Error(`Named health gate ${s.healthGate.name} is unavailable`);n.checkpoint("named-health-gate",`Waiting on ${s.healthGate.name}.`);let y=await e.resolveHealthGate(s.healthGate.name,s);if(n.log(`${s.healthGate.name}: ${y.healthy?"healthy":"unhealthy"}${y.message?` — ${y.message}`:""}.`,{stream:y.healthy?"step":"stderr",step:"health"}),!y.healthy)throw t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,health:y.evidence,message:y.message??`Named health gate ${s.healthGate.name} failed.`}),Error(y.message??`Named health gate ${s.healthGate.name} failed`)}if(n.operation.kind==="release.rollback"){let y=t.releases.get(s.id);if(y.status!=="rolled_back")t.releases.transition(y.id,"rolled_back",{message:`Traffic restored through ${p.name}.`,operationId:n.operation.id,trafficPercent:0,health:{resourceVersions:f.resourceVersions}});if(a&&a.status!=="active"){let b=a.status==="activating"?a:t.releases.transition(a.id,"activating",{message:"Rollback target restoring traffic.",operationId:n.operation.id,trafficPercent:0});t.releases.transition(b.id,"active",{message:"Previous immutable release restored.",operationId:n.operation.id,trafficPercent:100,health:{resourceVersions:f.resourceVersions}})}}else t.completeHealthGate(s.id,{healthy:!0,operationId:n.operation.id,health:{providerVersion:f.providerVersion??null,resourceVersions:f.resourceVersions},message:"Provider activation and health gates completed."});return n.checkpoint("finalize","Persisted the terminal release state."),{releaseId:s.id,artifactDigest:c.digest,provider:p.name,providerVersion:f.providerVersion??null,resourceVersions:f.resourceVersions,status:t.releases.get(s.id).status}};return Object.fromEntries(Jb.map((n)=>[n,r]))}import{createCipheriv as Hb,createDecipheriv as Gb,createHash as Ll,randomBytes as Ba}from"node:crypto";var Bl={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 Te(e){return typeof e==="string"&&e?e:void 0}function gn(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function ir(e){return JSON.stringify($e(e))}function pn(e){return Ll("sha256").update(e).digest("hex")}function _l(e){let t=e.trim().replace(/\/$/,""),r=new URL(t.includes("://")?t:`https://${t}`);if(r.username||r.password||r.search||r.hash)throw Error("Source host cannot contain credentials, a query, or a fragment");if(r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(r.hostname)))throw Error("Source host must use HTTPS");return`${r.protocol}//${r.host}${r.pathname.replace(/\/$/,"")}`}function Nl(e){let t=e.trim();if(t.length<2||t.length>80)throw Error("Connection name must contain 2-80 characters");return t}function ja(e){let t=e.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))throw Error("Repository must use owner/name format");return t}function $l(e){let t=e.trim()||".";if(t.startsWith("/")||t.split("/").includes("..")||/[\0\r\n]/.test(t))throw Error("Monorepo root must stay inside the repository");return t.replace(/^\.\//,"")||"."}function Ao(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Boolean))].slice(0,100)}function Kb(e){let t=e.trim();if(/\r|\n/.test(t)||/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(t))throw Error("Clone URL cannot contain credentials or control characters");if(!/^(?:https?:\/\/|ssh:\/\/|git@[A-Za-z0-9.-]+:)/.test(t))throw Error("Clone URL must use HTTPS or SSH");return t}function Qb(e){return{id:String(e.id),organizationId:String(e.organization_id),provider:String(e.provider),name:String(e.name),host:String(e.host),owner:Te(e.owner),authKind:String(e.auth_kind),credentialConfigured:!!e.credential_ciphertext,credentialFingerprint:Te(e.credential_fingerprint),grantedScopes:gn(e.granted_scopes,[]),capabilities:gn(e.capabilities,Bl[String(e.provider)]),status:String(e.status),healthMessage:Te(e.health_message),lastTestedAt:Te(e.last_tested_at),lastSyncedAt:Te(e.last_synced_at),credentialExpiresAt:Te(e.credential_expires_at),version:Number(e.version),createdByActorId:Te(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Fa(e){return{id:String(e.id),connectionId:String(e.connection_id),providerRepositoryId:String(e.provider_repository_id),fullName:String(e.full_name),cloneUrl:String(e.clone_url),defaultBranch:String(e.default_branch),visibility:String(e.visibility),archived:Number(e.archived)===1,metadata:gn(e.metadata,{}),syncedAt:String(e.synced_at)}}function Ml(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:Te(e.environment_id),resourceId:Te(e.resource_id),connectionId:String(e.connection_id),repositoryId:Te(e.repository_id),repositoryFullName:String(e.repository_full_name),defaultBranch:String(e.default_branch),branchRule:Te(e.branch_rule),tagRule:Te(e.tag_rule),monorepoRoot:String(e.monorepo_root),includePaths:gn(e.include_paths,[]),excludePaths:gn(e.exclude_paths,[]),submodules:Number(e.submodules)===1,cloneDepth:e.clone_depth==null?void 0:Number(e.clone_depth),deployKeyId:Te(e.deploy_key_id),autoDeploy:Number(e.auto_deploy)===1,pullRequestPreviews:Number(e.pull_request_previews)===1,status:String(e.status),disabledReason:Te(e.disabled_reason),version:Number(e.version),createdByActorId:Te(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ua(e){return{id:String(e.id),connectionId:String(e.connection_id),name:String(e.name),publicKey:String(e.public_key),publicKeyFingerprint:String(e.public_key_fingerprint),host:String(e.host),hostKey:String(e.host_key),hostKeyFingerprint:String(e.host_key_fingerprint),createdByActorId:Te(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function za(e){return{id:String(e.id),connectionId:String(e.connection_id),repositoryId:Te(e.repository_id),repositoryFullName:String(e.repository_full_name),providerWebhookId:Te(e.provider_webhook_id),events:gn(e.events,[]),status:String(e.status),healthMessage:Te(e.health_message),lastDeliveryAt:Te(e.last_delivery_at),lastReconciledAt:Te(e.last_reconciled_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Va(e){return{id:String(e.id),connectionId:String(e.connection_id),webhookId:String(e.webhook_id),providerDeliveryId:String(e.provider_delivery_id),event:String(e.event),action:Te(e.action),commitSha:Te(e.commit_sha),signatureStatus:String(e.signature_status),status:String(e.status),payloadSummary:gn(e.payload_summary,{}),operationId:Te(e.operation_id),error:Te(e.error),receivedAt:String(e.received_at),processedAt:Te(e.processed_at)}}class qa{controlPlane;key;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.key=t.encryptionKey?Ll("sha256").update(t.encryptionKey).digest():void 0,this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}encrypt(e){if(!this.key)throw Error("Source credential encryption key is not configured");let t=Ba(12),r=Hb("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){if(!this.key)throw Error("Source credential encryption key is not configured");let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted source credential is unavailable");let o=Gb("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}createConnection(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("Source connection organization was not found");let t=this.now(),r=this.idFn(),n=e.credential?JSON.stringify(e.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
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,[r,e.organizationId,e.provider,Nl(e.name),_l(e.host),e.owner?.trim()||null,e.authKind??(n?"access_token":"none"),n?this.encrypt(n):null,n?pn(n).slice(0,16):null,ir([...new Set(e.grantedScopes??[])].sort()),ir(Bl[e.provider]),e.credentialExpiresAt??null,e.createdByActorId??null,t,t]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.createdByActorId,type:"source.connection.created",payload:{connectionId:r,provider:e.provider,host:_l(e.host),owner:e.owner??null,scopes:e.grantedScopes??[]}}),this.getConnection(r)}getConnection(e){let t=this.controlPlane.database.query("SELECT * FROM source_connections WHERE id = ?").get(e);return t?this.currentConnection(t):void 0}listConnections(e){return this.controlPlane.database.query("SELECT * FROM source_connections WHERE organization_id = ? ORDER BY name").all(e).map((t)=>this.currentConnection(t))}currentConnection(e){let t=Qb(e);if(t.status!=="disconnected"&&t.credentialExpiresAt&&new Date(t.credentialExpiresAt).getTime()<=this.nowFn().getTime())return{...t,status:"expired",healthMessage:"Source credential expired; rotate it before deploying."};return t}getCredential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM source_connections WHERE id = ?").get(e);return t?.credential_ciphertext?JSON.parse(this.decrypt(String(t.credential_ciphertext))):void 0}rotateCredential(e,t,r={}){let n=this.getConnection(e);if(!n||n.status==="disconnected")throw Error("Active source connection was not found");let i=JSON.stringify(t);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),pn(i).slice(0,16),r.expiresAt??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"source.credential.rotated",payload:{connectionId:e,fingerprint:pn(i).slice(0,16),expiresAt:r.expiresAt??null}}),this.getConnection(e)}updateHealth(e,t){let r=this.getConnection(e);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active source connection was not found");let n=this.now(),i=t.grantedScopes?[...new Set(t.grantedScopes.map((o)=>o.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 = ?",[t.status,t.message?.slice(0,1000)??null,i?ir(i):null,t.tested?n:null,t.synced?n:null,n,e]),i&&JSON.stringify(i)!==JSON.stringify([...r.grantedScopes].sort()))this.controlPlane.appendEvent({organizationId:r.organizationId,type:"source.connection.scopes_updated",payload:{connectionId:e,grantedScopes:i}});return this.getConnection(e)}upsertRepository(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");let r=this.now(),n=this.controlPlane.database.query("SELECT id FROM source_repositories WHERE connection_id = ? AND provider_repository_id = ?").get(e.connectionId,e.providerRepositoryId),i=n?String(n.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
|
-
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,e.connectionId,e.providerRepositoryId,ja(e.fullName),Kb(e.cloneUrl),e.defaultBranch.trim()||"main",e.visibility,e.archived?1:0,ir(e.metadata),r]),Fa(this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(i))}listRepositories(e,t,r=100){let n=t?.trim().toLowerCase();return(n?this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? AND lower(full_name) LIKE ? ORDER BY full_name LIMIT ?").all(e,`%${n}%`,Math.min(500,r)):this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? ORDER BY full_name LIMIT ?").all(e,Math.min(500,r))).map(Fa)}getRepository(e){let t=this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(e);return t?Fa(t):void 0}createDeployKey(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status)||!t.capabilities.deployKeys)throw Error("An active deploy-key capable source connection is required");if(!/^ssh-(?:ed25519|rsa)\s+[A-Za-z0-9+/=]+/.test(e.publicKey.trim()))throw Error("A valid SSH public key is required");if(!/BEGIN (?:OPENSSH|RSA) PRIVATE KEY/.test(e.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(e.hostKey.trim()))throw Error("A pinned SSH host key is required");let r=this.idFn(),n=this.now(),i=`sha256:${pn(e.publicKey.trim())}`,o=`sha256:${pn(e.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.connectionId,Nl(e.name),e.publicKey.trim(),i,this.encrypt(e.privateKey),e.host.trim().toLowerCase(),e.hostKey.trim(),o,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"source.deploy_key.created",payload:{connectionId:e.connectionId,deployKeyId:r,publicFingerprint:i,hostFingerprint:o}}),Ua(this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(r))}getDeployKey(e){let t=this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(e);return t?Ua(t):void 0}listDeployKeys(e){return this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE connection_id = ? ORDER BY name, created_at").all(e).map(Ua)}revokeDeployKey(e,t){let r=this.getDeployKey(e),n=r?this.getConnection(r.connectionId):void 0;if(!r||!n)throw Error("Deploy key was not found");let i=this.listBindings({connectionId:n.id}).filter((s)=>s.deployKeyId===e),o=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=?",[o,e]),this.run("DELETE FROM source_deploy_keys WHERE id=?",[e])})(),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:t,type:"source.deploy_key.revoked",level:"warning",payload:{connectionId:n.id,deployKeyId:e,affectedBindingIds:i.map((s)=>s.id)}}),{affectedBindings:i}}getDeployPrivateKey(e){let t=this.controlPlane.database.query("SELECT private_key_ciphertext FROM source_deploy_keys WHERE id = ?").get(e);if(!t)throw Error("Deploy key was not found");return this.decrypt(String(t.private_key_ciphertext))}createBinding(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");if(e.repositoryId&&this.getRepository(e.repositoryId)?.connectionId!==t.id)throw Error("Repository does not belong to this connection");if(e.deployKeyId&&this.getDeployKey(e.deployKeyId)?.connectionId!==t.id)throw Error("Deploy key does not belong to this connection");let r=this.idFn(),n=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)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)`,[r,e.projectId,e.environmentId??null,e.resourceId??null,e.connectionId,e.repositoryId??null,ja(e.repositoryFullName),e.defaultBranch?.trim()||"main",e.branchRule?.trim()||null,e.tagRule?.trim()||null,$l(e.monorepoRoot??"."),ir(Ao(e.includePaths)),ir(Ao(e.excludePaths)),e.submodules?1:0,e.cloneDepth??null,e.deployKeyId??null,e.autoDeploy===!1?0:1,e.pullRequestPreviews===!1?0:1,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:e.projectId,actorId:e.actorId,type:"source.binding.created",payload:{bindingId:r,connectionId:e.connectionId,repository:e.repositoryFullName,branch:e.defaultBranch??"main"}}),this.getBinding(r)}getBinding(e){let t=this.controlPlane.database.query("SELECT * FROM source_bindings WHERE id = ?").get(e);return t?Ml(t):void 0}listBindings(e={}){return this.controlPlane.database.query("SELECT * FROM source_bindings ORDER BY created_at DESC").all().map(Ml).filter((r)=>(!e.connectionId||r.connectionId===e.connectionId)&&(!e.projectId||r.projectId===e.projectId)&&(!e.status||r.status===e.status))}updateBinding(e,t,r){let n=this.getBinding(e);if(!n||n.version!==t)throw Error(`Source binding ${e} changed since version ${t}`);let i=this.getConnection(n.connectionId);if((!i||["disconnected","expired"].includes(i.status))&&(r.status==="active"||r.autoDeploy===!0))throw Error("Rotate or reconnect the source credential before enabling this binding");if(r.deployKeyId&&this.getDeployKey(r.deployKeyId)?.connectionId!==n.connectionId)throw Error("Deploy key does not belong to this connection");let o=this.now();if(this.controlPlane.database.run("UPDATE source_bindings SET default_branch=?, branch_rule=?, tag_rule=?, monorepo_root=?, include_paths=?, exclude_paths=?, submodules=?, clone_depth=?, deploy_key_id=?, auto_deploy=?, pull_request_previews=?, status=?, disabled_reason=?, version=version+1, updated_at=? WHERE id=? AND version=?",[r.defaultBranch?.trim()||n.defaultBranch,r.branchRule===void 0?n.branchRule??null:r.branchRule.trim()||null,r.tagRule===void 0?n.tagRule??null:r.tagRule.trim()||null,r.monorepoRoot===void 0?n.monorepoRoot:$l(r.monorepoRoot),ir(r.includePaths===void 0?n.includePaths:Ao(r.includePaths)),ir(r.excludePaths===void 0?n.excludePaths:Ao(r.excludePaths)),r.submodules??n.submodules?1:0,r.cloneDepth===void 0?n.cloneDepth??null:r.cloneDepth,r.deployKeyId===void 0?n.deployKeyId??null:r.deployKeyId,r.autoDeploy??n.autoDeploy?1:0,r.pullRequestPreviews??n.pullRequestPreviews?1:0,r.status??n.status,r.disabledReason===void 0?n.disabledReason??null:r.disabledReason.slice(0,1000),o,e,t]).changes!==1)throw Error(`Source binding ${e} changed since version ${t}`);let c=this.getConnection(n.connectionId);return this.controlPlane.appendEvent({organizationId:c.organizationId,projectId:n.projectId,actorId:r.actorId,type:"source.binding.updated",payload:{bindingId:e,fromVersion:t,toVersion:t+1,status:r.status??n.status}}),this.getBinding(e)}createWebhook(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");if(e.repositoryId&&this.getRepository(e.repositoryId)?.connectionId!==t.id)throw Error("Repository does not belong to this connection");let r=this.idFn(),n=this.now(),i=e.endpointToken??Ba(24).toString("base64url"),o=e.secret??Ba(32).toString("base64url"),s=[...new Set(e.events??["push","pull_request"])].filter((c)=>["push","pull_request"].includes(c));if(!s.length)throw Error("At least one supported webhook event is required");return this.run("INSERT INTO source_webhooks (id, connection_id, repository_id, repository_full_name, endpoint_token_hash, endpoint_token_ciphertext, secret_ciphertext, events, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)",[r,e.connectionId,e.repositoryId??null,ja(e.repositoryFullName),pn(i),this.encrypt(i),this.encrypt(o),ir(s),n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,type:"source.webhook.created",payload:{webhookId:r,connectionId:t.id,repository:e.repositoryFullName,events:s}}),{webhook:{...this.getWebhook(r),endpointToken:i},secret:o}}getWebhook(e){let t=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE id = ?").get(e);return t?za(t):void 0}getWebhookByEndpointToken(e){let t=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE endpoint_token_hash = ?").get(pn(e));return t?za(t):void 0}getWebhookSecret(e){let t=this.controlPlane.database.query("SELECT secret_ciphertext FROM source_webhooks WHERE id = ?").get(e);if(!t)throw Error("Source webhook was not found");return this.decrypt(String(t.secret_ciphertext))}getWebhookEndpointToken(e){let t=this.controlPlane.database.query("SELECT endpoint_token_ciphertext FROM source_webhooks WHERE id = ?").get(e);if(!t?.endpoint_token_ciphertext)throw Error("Source webhook endpoint token is unavailable");return this.decrypt(String(t.endpoint_token_ciphertext))}listWebhooks(e){return this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE connection_id = ? ORDER BY repository_full_name").all(e).map(za)}updateWebhookState(e,t){let r=this.getWebhook(e);if(!r)throw Error("Source webhook was not found");let n=this.now();this.run("UPDATE source_webhooks SET provider_webhook_id=COALESCE(?, provider_webhook_id), status=?, health_message=?, last_reconciled_at=COALESCE(?, last_reconciled_at), updated_at=? WHERE id=?",[t.providerWebhookId??null,t.status,t.healthMessage?.slice(0,1000)??null,t.reconciled?n:null,n,e]);let i=this.getConnection(r.connectionId);if(i)this.controlPlane.appendEvent({organizationId:i.organizationId,type:"source.webhook.updated",payload:{webhookId:e,connectionId:i.id,repository:r.repositoryFullName,status:t.status,reconciled:t.reconciled??!1,providerWebhookId:t.providerWebhookId??r.providerWebhookId??null}});return this.getWebhook(e)}getDeliveryByProviderId(e,t){let r=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE connection_id = ? AND provider_delivery_id = ?").get(e,t);return r?Va(r):void 0}recordDelivery(e){let t=this.getDeliveryByProviderId(e.connectionId,e.providerDeliveryId);if(t)return{delivery:t,duplicate:!0};let r=this.idFn(),n=this.now();return this.controlPlane.database.transaction(()=>{this.run("INSERT INTO source_webhook_deliveries (id, connection_id, webhook_id, provider_delivery_id, event, action, commit_sha, signature_status, status, payload_summary, operation_id, error, received_at, processed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.connectionId,e.webhookId,e.providerDeliveryId,e.event.slice(0,100),e.action?.slice(0,100)??null,e.commitSha?.slice(0,128)??null,e.signatureStatus,e.status,ir(e.payloadSummary??{}),e.operationId??null,e.error?.slice(0,2000)??null,n,["enqueued","ignored","rejected","failed"].includes(e.status)?n:null]),this.run("UPDATE source_webhooks SET last_delivery_at=?, updated_at=? WHERE id=?",[n,n,e.webhookId])})(),{delivery:this.getDeliveryByProviderId(e.connectionId,e.providerDeliveryId),duplicate:!1}}updateDelivery(e,t){this.run("UPDATE source_webhook_deliveries SET status=?, operation_id=?, error=?, processed_at=? WHERE id=?",[t.status,t.operationId??null,t.error?.slice(0,2000)??null,this.now(),e]);let r=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE id = ?").get(e);if(!r)throw Error("Source webhook delivery was not found");return Va(r)}listDeliveries(e,t=100){return this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE webhook_id = ? ORDER BY received_at DESC LIMIT ?").all(e,Math.min(500,Math.max(1,t))).map(Va)}disconnectConnection(e,t){let r=this.getConnection(e);if(!r)throw Error("Source connection was not found");let n=this.listBindings({connectionId:e,status:"active"}),i=this.now();return this.controlPlane.database.transaction(()=>{this.run("UPDATE source_connections SET status='disconnected', credential_ciphertext=NULL, health_message='Disconnected by an administrator', version=version+1, updated_at=? WHERE id=?",[i,e]),this.run("UPDATE source_bindings SET status='disabled', auto_deploy=0, disabled_reason='Source connection was disconnected', version=version+1, updated_at=? WHERE connection_id=? AND status='active'",[i,e]),this.run("UPDATE source_webhooks SET status='disabled', health_message='Source connection was disconnected', updated_at=? WHERE connection_id=?",[i,e])})(),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"source.connection.disconnected",level:"warning",payload:{connectionId:e,affectedBindingIds:n.map((o)=>o.id),affectedRepositories:n.map((o)=>o.repositoryFullName)}}),{connection:this.getConnection(e),affectedBindings:n}}}import{createSign as Yb}from"node:crypto";class Jn extends Error{status;retryAfterSeconds;constructor(e,t,r){super(e);this.status=t;this.retryAfterSeconds=r;this.name="SourceProviderError"}}var Fl={repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0};function Ur(e){let t=Number(e??"1");return Number.isInteger(t)&&t>0?t:1}function zr(e){return Math.max(1,Math.min(100,e??50))}function _t(e){let t=e.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))throw Error("Repository must use owner/name format");return t}function Oi(e){let t=new URL(e);if(t.username||t.password||t.protocol!=="https:")throw Error("Webhook endpoint must be credential-free HTTPS");return t.href}function jl(e){return Buffer.from(e).toString("base64url")}function Xb(e,t){if(!e.appId||!e.privateKey)throw Error("GitHub App credentials require appId and privateKey");let r=jl(JSON.stringify({alg:"RS256",typ:"JWT"})),n=Math.floor(t.getTime()/1000)-30,i=jl(JSON.stringify({iat:n,exp:n+540,iss:e.appId})),o=Yb("RSA-SHA256");return o.update(`${r}.${i}`),o.end(),`${r}.${i}.${o.sign(e.privateKey).toString("base64url")}`}class _i{connection;credential;capabilities=Fl;fetchFn;timeoutMs;nowFn;constructor(e,t,r={}){this.connection=e;this.credential=t;this.fetchFn=r.fetch??((n,i)=>globalThis.fetch(n,i)),this.timeoutMs=Math.max(100,r.timeoutMs??20000),this.nowFn=r.now??(()=>new Date)}async request(e,t={}){let r=new URL(`${this.apiRoot().replace(/\/$/,"")}/`),n=new URL(e.replace(/^\//,""),r);if(n.origin!==r.origin)throw Error("Provider pagination cannot leave the configured host");let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeoutMs);try{let s=await this.fetchFn(n,{...t,redirect:"error",signal:i.signal,headers:{Accept:"application/json","User-Agent":"ts-cloud-source/1",...await this.authorization(),...t.headers}});if(!s.ok){let c=Number(s.headers.get("retry-after")??""),u=s.headers.get("x-request-id")??s.headers.get("x-github-request-id");throw new Jn(`Source provider request failed (${s.status})${u?` [request ${u}]`:""}`,s.status,Number.isFinite(c)?c:void 0)}if(s.status===204)return{data:void 0,headers:s.headers};return{data:await s.json(),headers:s.headers}}catch(s){if(s instanceof Jn)throw s;if(i.signal.aborted)throw new Jn(`Source provider request exceeded ${this.timeoutMs}ms`);throw new Jn(s instanceof Error?s.message.replace(/(?:token|password|secret)=[^\s&]+/gi,"$1=[REDACTED]"):"Source provider request failed")}finally{clearTimeout(o)}}async deleteWebhook(e,t){await this.request(this.webhookPath(e,t),{method:"DELETE"})}}class Ul extends _i{provider="github";installationToken;apiRoot(){return this.connection.host==="https://github.com"?"https://api.github.com":`${this.connection.host}/api/v3`}async authorization(){if(this.credential?.token)return{Authorization:`Bearer ${this.credential.token}`,"X-GitHub-Api-Version":"2022-11-28"};if(!this.credential?.installationId)return{};if(!this.installationToken||this.installationToken.expiresAt<this.nowFn().getTime()+60000){let e=Xb(this.credential,this.nowFn()),t=this.apiRoot().replace(/\/$/,""),r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{let i=await this.fetchFn(`${t}/app/installations/${encodeURIComponent(this.credential.installationId)}/access_tokens`,{method:"POST",signal:r.signal,redirect:"error",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"ts-cloud-source/1"}});if(!i.ok)throw new Jn(`GitHub App token refresh failed (${i.status})`,i.status);let o=await i.json();this.installationToken={value:o.token,expiresAt:new Date(o.expires_at).getTime()}}finally{clearTimeout(n)}}return{Authorization:`Bearer ${this.installationToken.value}`,"X-GitHub-Api-Version":"2022-11-28"}}async testConnection(){let e=this.credential?.installationId?"/installation/repositories?per_page=1":"/user",{data:t,headers:r}=await this.request(e);return{ok:!0,account:t.login??this.connection.owner,scopes:(r.get("x-oauth-scopes")??this.connection.grantedScopes.join(",")).split(",").map((n)=>n.trim()).filter(Boolean),message:"GitHub connection is healthy"}}async listRepositories(e={}){let t=zr(e.limit),r=Ur(e.cursor),n=this.credential?.installationId?`/installation/repositories?per_page=${t}&page=${r}`:`/user/repos?per_page=${t}&page=${r}&sort=updated`,{data:i}=await this.request(n),o=Array.isArray(i)?i:i.repositories;return{repositories:(e.search?o.filter((c)=>c.full_name.toLowerCase().includes(e.search.toLowerCase())):o).map((c)=>({providerRepositoryId:String(c.id),fullName:c.full_name,cloneUrl:c.clone_url,defaultBranch:c.default_branch||"main",visibility:c.visibility??(c.private?"private":"public"),archived:!!c.archived,metadata:{}})),nextCursor:o.length===t?String(r+1):void 0}}async refs(e,t,r={}){let n=zr(r.limit),i=Ur(r.cursor),{data:o}=await this.request(`/repos/${_t(e)}/${t}?per_page=${n}&page=${i}`);return{refs:o.map((s)=>({name:s.name,commitSha:s.commit.sha,protected:s.protected})),nextCursor:o.length===n?String(i+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repos/${_t(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:e.active,events:e.events,url:e.config.url??""}}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:JSON.stringify({name:"web",active:!0,events:t.events,config:{url:Oi(t.url),content_type:"json",secret:t.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PATCH",body:JSON.stringify({active:!0,events:r.events,config:{url:Oi(r.url),content_type:"json",secret:r.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){await this.request(`/repos/${_t(e)}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r.state,target_url:r.url,description:r.description.slice(0,140),context:r.context??"ts-cloud/preview"})})}}class zl extends _i{provider="gitlab";apiRoot(){return`${this.connection.host}/api/v4`}async authorization(){return this.credential?.token?{"PRIVATE-TOKEN":this.credential.token}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.username,scopes:this.connection.grantedScopes,message:"GitLab connection is healthy"}}async listRepositories(e={}){let t=zr(e.limit),r=Ur(e.cursor),n=e.search?`&search=${encodeURIComponent(e.search)}`:"",{data:i,headers:o}=await this.request(`/projects?membership=true&simple=true&order_by=last_activity_at&per_page=${t}&page=${r}${n}`);return{repositories:i.map((s)=>({providerRepositoryId:String(s.id),fullName:s.path_with_namespace,cloneUrl:s.http_url_to_repo,defaultBranch:s.default_branch??"main",visibility:s.visibility??"unknown",archived:!!s.archived,metadata:{}})),nextCursor:o.get("x-next-page")||void 0}}async refs(e,t,r={}){let n=zr(r.limit),i=Ur(r.cursor),{data:o,headers:s}=await this.request(`/projects/${encodeURIComponent(_t(e))}/repository/${t}?per_page=${n}&page=${i}`);return{refs:o.map((c)=>({name:c.name,commitSha:c.commit.id,protected:c.protected})),nextCursor:s.get("x-next-page")||void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/projects/${encodeURIComponent(_t(e))}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:!0,events:[...e.push_events?["push"]:[],...e.merge_requests_events?["pull_request"]:[]],url:e.url}}body(e){return JSON.stringify({url:Oi(e.url),token:e.secret,enable_ssl_verification:!0,push_events:e.events.includes("push"),merge_requests_events:e.events.includes("pull_request")})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PUT",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){let n=r.state==="failure"||r.state==="error"?"failed":r.state;await this.request(`/projects/${encodeURIComponent(_t(e))}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n,target_url:r.url,description:r.description.slice(0,255),name:r.context??"ts-cloud/preview"})})}}class Vl extends _i{provider="bitbucket";apiRoot(){return this.connection.host==="https://bitbucket.org"?"https://api.bitbucket.org/2.0":`${this.connection.host}/2.0`}async authorization(){return this.credential?.token?{Authorization:`Bearer ${this.credential.token}`}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.username??e.display_name,scopes:this.connection.grantedScopes,message:"Bitbucket connection is healthy"}}async listRepositories(e={}){if(!this.connection.owner)throw Error("Bitbucket repository discovery requires an owner/workspace");let t=Ur(e.cursor),r=zr(e.limit),n=e.search?`&q=name~%22${encodeURIComponent(e.search)}%22`:"",{data:i}=await this.request(`/repositories/${encodeURIComponent(this.connection.owner)}?pagelen=${r}&page=${t}${n}`);return{repositories:i.values.map((o)=>({providerRepositoryId:o.uuid,fullName:o.full_name,cloneUrl:o.links.clone.find((s)=>s.name==="https")?.href??o.links.clone[0]?.href??"",defaultBranch:o.mainbranch?.name??"main",visibility:o.is_private?"private":"public",archived:!1,metadata:{}})),nextCursor:i.next?String(t+1):void 0}}async refs(e,t,r={}){let n=Ur(r.cursor),i=zr(r.limit),{data:o}=await this.request(`/repositories/${_t(e)}/refs/${t}?pagelen=${i}&page=${n}`);return{refs:o.values.map((s)=>({name:s.name,commitSha:s.target.hash})),nextCursor:o.next?String(n+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repositories/${_t(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:e.uuid,active:e.active,events:e.events.map((t)=>t.replace("repo:push","push").replace("pullrequest:","pull_request:")),url:e.url}}body(e){return JSON.stringify({description:"ts-cloud deploy",url:Oi(e.url),active:!0,events:e.events.map((t)=>t==="push"?"repo:push":t.replace("pull_request:","pullrequest:"))})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.values.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PUT",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){let n=r.state==="success"?"SUCCESSFUL":r.state==="pending"?"INPROGRESS":"FAILED";await this.request(`/repositories/${_t(e)}/commit/${encodeURIComponent(t)}/statuses/build/ts-cloud-preview`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n,key:"ts-cloud-preview",name:r.context??"ts-cloud/preview",url:r.url,description:r.description.slice(0,255)})})}}class ql extends _i{provider="gitea";capabilities={...Fl,tokenRefresh:!1};apiRoot(){return`${this.connection.host}/api/v1`}async authorization(){return this.credential?.token?{Authorization:`token ${this.credential.token}`}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.login,scopes:this.connection.grantedScopes,message:"Gitea connection is healthy"}}async listRepositories(e={}){let t=Ur(e.cursor),r=zr(e.limit),n=e.search?`/repos/search?q=${encodeURIComponent(e.search)}&limit=${r}&page=${t}`:`/user/repos?limit=${r}&page=${t}`,{data:i,headers:o}=await this.request(n),s=Array.isArray(i)?i:i.data;return{repositories:s.map((c)=>({providerRepositoryId:String(c.id),fullName:c.full_name,cloneUrl:c.clone_url,defaultBranch:c.default_branch??"main",visibility:c.private?"private":"public",archived:!!c.archived,metadata:{}})),nextCursor:o.get("x-hasmore")==="true"||s.length===r?String(t+1):void 0}}async refs(e,t,r={}){let n=Ur(r.cursor),i=zr(r.limit),{data:o}=await this.request(`/repos/${_t(e)}/${t}?limit=${i}&page=${n}`);return{refs:o.map((s)=>({name:s.name,commitSha:s.commit.id})),nextCursor:o.length===i?String(n+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repos/${_t(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:e.active,events:e.events??[],url:e.config.url??""}}body(e){return JSON.stringify({type:"gitea",active:!0,events:e.events,config:{url:Oi(e.url),content_type:"json",secret:e.secret,insecure_ssl:"0"}})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PATCH",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){await this.request(`/repos/${_t(e)}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r.state,target_url:r.url,description:r.description.slice(0,140),context:r.context??"ts-cloud/preview"})})}}function Vr(e,t,r={}){switch(e.provider){case"github":return new Ul(e,t,r);case"gitlab":return new zl(e,t,r);case"bitbucket":return new Vl(e,t,r);case"gitea":return new ql(e,t,r);default:throw Error(`${e.provider} uses bounded Git discovery instead of a hosted provider API`)}}import{createHmac as Zb,timingSafeEqual as eS}from"node:crypto";function mt(e,t){if(e instanceof Headers)return e.get(t)??void 0;return Object.entries(e).find(([n])=>n.toLowerCase()===t.toLowerCase())?.[1]}function Jl(e,t){let r=Buffer.from(e),n=Buffer.from(t);return r.length===n.length&&eS(r,n)}function tS(e,t){return Zb("sha256",e).update(t).digest("hex")}function rS(e,t,r,n,i){if(e==="gitlab")return Jl(mt(r,"x-gitlab-token")??"",t);let o=e==="github"?mt(r,"x-hub-signature-256"):e==="gitea"?mt(r,"x-gitea-signature"):mt(r,"x-hub-signature")??mt(r,"x-ts-cloud-signature");if(!o)return!1;if(e==="generic_https"||e==="generic_ssh"){let s=Number(mt(r,"x-ts-cloud-timestamp"));if(!Number.isFinite(s)||Math.abs(i.getTime()-s*1000)>300000)return!1}return Jl(o.replace(/^sha256=/,""),tS(t,n))}function nS(e,t){return{github:["x-github-delivery"],gitlab:["x-gitlab-event-uuid","x-request-id"],bitbucket:["x-request-uuid"],gitea:["x-gitea-delivery"],generic_https:["x-ts-cloud-delivery"],generic_ssh:["x-ts-cloud-delivery"]}[e].map((n)=>mt(t,n)?.trim()).find(Boolean)}function qr(e){let t=String(e??"").trim().replace(/^\/+|\/+$/g,"");return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t)?t:""}function Ja(e){return[...new Set(e.flatMap((t)=>{if(!t||typeof t!=="object")return[];let r=t;return[...r.added??[],...r.modified??[],...r.removed??[]].map(String)}).filter((t)=>t&&!t.includes("\x00")).slice(0,500))]}function iS(e,t,r){let n=e,i=t,o=r;if(n==="github"){let s=mt(i,"x-github-event"),c=qr(o.repository?.full_name);if(s==="push")return{event:"push",repository:c,ref:String(o.ref??""),branch:String(o.ref??"").replace(/^refs\/heads\//,""),tag:String(o.ref??"").startsWith("refs/tags/")?String(o.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(o.after??o.head_commit?.id??""),changedPaths:Ja(o.commits??[]),deleted:o.deleted===!0||/^0{40,64}$/.test(String(o.after??""))};if(s==="pull_request")return{event:"pull_request",action:String(o.action??""),repository:c,branch:String(o.pull_request?.head?.ref??""),commitSha:String(o.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(o.number)||void 0,fork:qr(o.pull_request?.head?.repo?.full_name)!==c}}if(n==="gitlab"){let s=String(o.object_kind??"").toLowerCase(),c=qr(o.project?.path_with_namespace);if(s==="push"||s==="tag_push")return{event:"push",repository:c,ref:String(o.ref??""),branch:String(o.ref??"").replace(/^refs\/heads\//,""),tag:s==="tag_push"?String(o.ref??"").replace(/^refs\/tags\//,""):void 0,commitSha:String(o.checkout_sha??o.after??""),changedPaths:Ja(o.commits??[]),deleted:/^0{40,64}$/.test(String(o.after??""))};if(s==="merge_request")return{event:"pull_request",action:String(o.object_attributes?.action??o.object_attributes?.state??""),repository:c,branch:String(o.object_attributes?.source_branch??""),commitSha:String(o.object_attributes?.last_commit?.id??""),changedPaths:[],pullRequestNumber:Number(o.object_attributes?.iid)||void 0,fork:o.object_attributes?.source_project_id!==o.object_attributes?.target_project_id}}if(n==="bitbucket"){let s=mt(i,"x-event-key")??"",c=qr(o.repository?.full_name);if(s==="repo:push"){let u=o.push?.changes?.[0]??{},a=u.new??u.old??{},p=u.new?.target??u.old?.target;return{event:"push",repository:c,ref:String(a.name??""),branch:a.type==="branch"?String(a.name):void 0,tag:a.type==="tag"?String(a.name):void 0,commitSha:String(p?.hash??""),changedPaths:[],deleted:u.closed===!0||u.new==null}}if(s.startsWith("pullrequest:"))return{event:"pull_request",action:s.replace("pullrequest:",""),repository:c,branch:String(o.pullrequest?.source?.branch?.name??""),commitSha:String(o.pullrequest?.source?.commit?.hash??""),changedPaths:[],pullRequestNumber:Number(o.pullrequest?.id)||void 0,fork:qr(o.pullrequest?.source?.repository?.full_name)!==c}}if(n==="gitea"){let s=mt(i,"x-gitea-event"),c=qr(o.repository?.full_name);if(s==="push")return{event:"push",repository:c,ref:String(o.ref??""),branch:String(o.ref??"").replace(/^refs\/heads\//,""),tag:String(o.ref??"").startsWith("refs/tags/")?String(o.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(o.after??""),changedPaths:Ja(o.commits??[]),deleted:o.deleted===!0||/^0{40,64}$/.test(String(o.after??""))};if(s==="pull_request")return{event:"pull_request",action:String(o.action??""),repository:c,branch:String(o.pull_request?.head?.ref??""),commitSha:String(o.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(o.number)||void 0,fork:qr(o.pull_request?.head?.repo?.full_name)!==c}}if(n==="generic_https"||n==="generic_ssh"){if(o.event!=="push"&&o.event!=="pull_request")return;return{event:o.event,action:typeof o.action==="string"?o.action:void 0,repository:qr(o.repository),ref:typeof o.ref==="string"?o.ref:void 0,branch:typeof o.branch==="string"?o.branch:void 0,tag:typeof o.tag==="string"?o.tag:void 0,commitSha:String(o.commitSha??""),changedPaths:Array.isArray(o.changedPaths)?o.changedPaths.map(String).slice(0,500):[],pullRequestNumber:Number(o.pullRequestNumber)||void 0,fork:o.fork===!0,deleted:o.deleted===!0}}return}function Wn(e,t){let r="^";for(let n=0;n<t.length;n++){let i=t[n];if(i==="*"&&t[n+1]==="*")r+=".*",n++;else if(i==="*")r+="[^/]*";else if(i==="?")r+="[^/]";else r+=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`${r}$`).test(e)}function oS(e,t){if(t.event==="pull_request")return e.pullRequestPreviews;if(!e.autoDeploy)return!1;if(t.tag)return!!e.tagRule&&Wn(t.tag,e.tagRule);return Wn(t.branch??"",e.branchRule??e.defaultBranch)}function sS(e,t){if(!t.length)return!0;return t.filter((n)=>!e.excludePaths.some((i)=>Wn(n,i))).some((n)=>!e.includePaths.length||e.includePaths.some((i)=>Wn(n,i)))}function Wl(e,t){return mt(t,e==="github"?"x-github-event":e==="gitlab"?"x-gitlab-event":e==="bitbucket"?"x-event-key":e==="gitea"?"x-gitea-event":"x-ts-cloud-event")??"unknown"}function mn(){return{accepted:!1,duplicate:!1,status:"rejected",operations:[],message:"Webhook unavailable"}}async function Gl(e){if(e.rawBody.byteLength>2097152)return mn();let t=e.sources.getWebhookByEndpointToken(e.endpointToken);if(!t||t.status==="disabled")return mn();let r=e.sources.getConnection(t.connectionId);if(!r||r.status==="disconnected"||r.status==="expired")return mn();let n=nS(r.provider,e.headers);if(!n||n.length>200)return mn();if(!rS(r.provider,e.sources.getWebhookSecret(t.id),e.headers,e.rawBody,e.now??new Date))return e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:Wl(r.provider,e.headers),signatureStatus:mt(e.headers,"x-hub-signature-256")||mt(e.headers,"x-gitlab-token")||mt(e.headers,"x-hub-signature")||mt(e.headers,"x-gitea-signature")?"invalid":"missing",status:"rejected",error:"Webhook signature verification failed"}),mn();let o;try{o=JSON.parse(new TextDecoder().decode(e.rawBody))}catch{return mn()}let s=iS(r.provider,e.headers,o);if(!s||!s.repository||!/^[a-f0-9]{7,64}$/i.test(s.commitSha))return e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:Wl(r.provider,e.headers),signatureStatus:"verified",status:"rejected",error:"Unsupported or malformed source event"}),mn();let c=e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:s.event,action:s.action,commitSha:s.commitSha,signatureStatus:"verified",status:"accepted",payloadSummary:{repository:s.repository,ref:s.ref??null,branch:s.branch??null,tag:s.tag??null,commitSha:s.commitSha,pullRequestNumber:s.pullRequestNumber??null,changedPathCount:s.changedPaths.length}});if(c.duplicate&&c.delivery.status!=="accepted")return{accepted:!0,duplicate:!0,status:"duplicate",operations:[],message:"Delivery already processed"};let u=new Hl(e.controlPlane),a=e.sources.listBindings({connectionId:r.id,status:"active"}).filter((b)=>{if(b.repositoryFullName.toLowerCase()!==s.repository.toLowerCase()||!sS(b,s.changedPaths))return!1;let C=b.resourceId?u.getDefinitionForResource(b.resourceId):void 0,T=s.event==="push"&&!!C?.branchRule&&!!s.branch&&Wn(s.branch,C.branchRule);return oS(b,s)||T});if(!a.length)return e.sources.updateDelivery(c.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:c.duplicate,status:"ignored",operations:[],message:"Verified event did not match an active deployment rule"};let p=new xe(e.controlPlane),f=new Set(["closed","merged","declined"]),y=a.flatMap((b)=>{if(s.event==="push"&&b.resourceId&&s.branch){let T=u.getDefinitionForResource(b.resourceId);if(T?.branchRule&&Wn(s.branch,T.branchRule)){let R=u.findForBranch(T.id,s.repository,s.branch);if(s.deleted){if(!T.cleanupOnClose||!R||R.status==="destroyed")return[];let G=p.enqueue({projectId:b.projectId,environmentId:b.environmentId,resourceId:b.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${R.id}:branch-delete:${n}`,correlationId:`preview:${R.id}`,input:{previewId:R.id,reason:"branch_deleted",source:{repository:s.repository,commitSha:s.commitSha,branch:s.branch}},lockKey:`preview:${R.id}`,providerKey:r.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return u.transition(R.id,"queued",{operationId:G.id}),[G]}let x=u.upsert({definitionId:T.id,sourceProvider:r.provider,repository:s.repository,branch:s.branch,commitSha:s.commitSha});if(!x.changed)return[];let L=x.created?"preview.create":"preview.update",P=p.enqueue({projectId:b.projectId,environmentId:b.environmentId,resourceId:b.resourceId,kind:L,idempotencyKey:`preview:${x.preview.id}:${s.commitSha}`,correlationId:`preview:${x.preview.id}`,input:{previewId:x.preview.id,source:{connectionId:r.id,bindingId:b.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch,monorepoRoot:b.monorepoRoot,submodules:b.submodules,cloneDepth:b.cloneDepth??null}},lockKey:`preview:${x.preview.id}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return u.transition(x.preview.id,"queued",{operationId:P.id}),[P]}}if(s.event==="pull_request"&&b.resourceId&&s.pullRequestNumber){let T=u.getDefinitionForResource(b.resourceId);if(T){let R=f.has(String(s.action??"").toLowerCase()),x=u.findForPullRequest(T.id,s.repository,s.pullRequestNumber);if(R){if(!T.cleanupOnClose||!x||x.status==="destroyed")return[];let L=p.enqueue({projectId:b.projectId,environmentId:b.environmentId,resourceId:b.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${x.id}:destroy:${n}`,correlationId:`preview:${x.id}`,input:{previewId:x.id,reason:"pull_request_closed",source:{repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,pullRequestNumber:s.pullRequestNumber}},lockKey:`preview:${x.id}`,providerKey:r.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return u.transition(x.id,"queued",{operationId:L.id}),[L]}try{let L=u.upsert({definitionId:T.id,sourceProvider:r.provider,repository:s.repository,branch:s.branch??`pr-${s.pullRequestNumber}`,pullRequestNumber:s.pullRequestNumber,fork:s.fork,commitSha:s.commitSha});if(!L.changed)return[];let P=L.created?"preview.create":"preview.update",G=p.enqueue({projectId:b.projectId,environmentId:b.environmentId,resourceId:b.resourceId,kind:P,idempotencyKey:`preview:${L.preview.id}:${s.commitSha}`,correlationId:`preview:${L.preview.id}`,input:{previewId:L.preview.id,source:{connectionId:r.id,bindingId:b.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,pullRequestNumber:s.pullRequestNumber,fork:!!s.fork,monorepoRoot:b.monorepoRoot,submodules:b.submodules,cloneDepth:b.cloneDepth??null},inheritedSecretNames:L.inheritedSecrets},lockKey:`preview:${L.preview.id}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return u.transition(L.preview.id,"queued",{operationId:G.id}),[G]}catch(L){return e.controlPlane.appendEvent({projectId:b.projectId,resourceId:b.resourceId,type:"preview.rejected",level:"warning",payload:{repository:s.repository,pullRequestNumber:s.pullRequestNumber,fork:!!s.fork,reason:L instanceof Error?L.message:String(L)}}),[]}}}let C=s.event==="pull_request"?"deploy.preview":"deploy.source";return[p.enqueue({projectId:b.projectId,environmentId:b.environmentId,resourceId:b.resourceId,kind:C,idempotencyKey:`source:${r.id}:${n}:${b.id}:${s.commitSha}`,correlationId:`source:${n}`,input:{source:{connectionId:r.id,bindingId:b.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,tag:s.tag??null,monorepoRoot:b.monorepoRoot,submodules:b.submodules,cloneDepth:b.cloneDepth??null},preview:s.event==="pull_request"?{number:s.pullRequestNumber??null,action:s.action??null}:null},lockKey:b.resourceId?`resource:${b.resourceId}`:`environment:${b.environmentId??b.projectId}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:s.event==="pull_request"?14:90}).operation]});if(!y.length)return e.sources.updateDelivery(c.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:c.duplicate,status:"ignored",operations:[],message:"Verified event required no preview lifecycle change"};return e.sources.updateDelivery(c.delivery.id,{status:"enqueued",operationId:y[0]?.id}),e.controlPlane.appendEvent({organizationId:r.organizationId,projectId:a[0]?.projectId,operationId:y[0]?.id,type:"source.webhook.enqueued",payload:{webhookId:t.id,deliveryId:c.delivery.id,repository:s.repository,commitSha:s.commitSha,operationIds:y.map((b)=>b.id)}}),{accepted:!0,duplicate:c.duplicate,status:"enqueued",operations:y,message:`${y.length} deployment operation${y.length===1?"":"s"} enqueued`}}function Hn(e,t){if(!t.endpointToken)throw Error("The webhook endpoint token is only available at creation time");let r=new URL(e);if(r.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(r.hostname))throw Error("Webhook base URL must use HTTPS");return new URL(`/api/source/webhooks/${encodeURIComponent(t.endpointToken)}`,r).href}import{chmodSync as Kl,mkdtempSync as aS,rmSync as cS,writeFileSync as Ql}from"node:fs";import{tmpdir as dS}from"node:os";import{join as ko,resolve as uS}from"node:path";function Xl(e,t){let r=e.trim();if(/\r|\n|\0/.test(r))throw Error("Git remote contains control characters");if(r.startsWith("https://")){let i=new URL(r);if(i.username||i.password||i.search||i.hash)throw Error("HTTPS Git remotes cannot contain credentials, queries, or fragments");return i.href}let n=r.startsWith("ssh://")?new URL(r).hostname:r.match(/^git@([A-Za-z0-9.-]+):/)?.[1];if(!n)throw Error("Git remote must use credential-free HTTPS or SSH");if(!t||t.host.toLowerCase()!==n.toLowerCase())throw Error("SSH Git remote requires a deploy key with a pinned key for the same host");return r}function lS(e,t,r){let n=e.replaceAll(t,"[REMOTE]").slice(0,4000);for(let i of[r?.token,r?.privateKey])if(i)n=n.replaceAll(i,"[REDACTED]");return n}function pS(e){let t={PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_OPTIONAL_LOCKS:"0"},r;if(e.credential?.token){let n=e.credential.username??"oauth2";t.GIT_CONFIG_COUNT="1",t.GIT_CONFIG_KEY_0="http.extraHeader",t.GIT_CONFIG_VALUE_0=`Authorization: Basic ${Buffer.from(`${n}:${e.credential.token}`).toString("base64")}`}if(e.deployKey){r=aS(ko(dS(),"ts-cloud-git-transport-"));let n=ko(r,"key"),i=ko(r,"known_hosts");Ql(n,e.deployKey.privateKey,{mode:384}),Ql(i,`${e.deployKey.host} ${e.deployKey.hostKey}
|
|
6
|
-
`,{mode:384}),Kl(n,384),Kl(i,384),t.GIT_SSH_COMMAND=`ssh -i ${n} -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=${i} -o GlobalKnownHostsFile=/dev/null -o BatchMode=yes`}return{env:t,cleanup:()=>{if(r)cS(r,{recursive:!0,force:!0})}}}async function fn(e,t,r){let n=pS(r),i=Bun.spawn([r.executable??"git",...e],{stdout:"pipe",stderr:"pipe",env:n.env}),o=Math.max(100,r.timeoutMs??120000),s,c=new Promise((u,a)=>{s=setTimeout(()=>{i.kill(),a(Error(`Git operation exceeded ${o}ms`))},o)});try{let u=Promise.all([i.exited,new Response(i.stdout).text(),new Response(i.stderr).text()]),[a,p,f]=await Promise.race([u,c]);if(a!==0)throw Error(lS(f||`Git exited with ${a}`,t,r.credential));return p}finally{if(s)clearTimeout(s);n.cleanup()}}function Yl(e,t){let r=new Map;for(let n of e.split(`
|
|
7
|
-
`)){let i=n.trim().match(/^([a-f0-9]{40,64})\s+(.+)$/i);if(!i||!i[2].startsWith(t)||i[2].endsWith("^{}"))continue;let o=i[2].slice(t.length);r.set(o,{name:o,commitSha:i[1]})}return[...r.values()].sort((n,i)=>n.name.localeCompare(i.name))}async function Wa(e,t={}){let r=Xl(e,t.deployKey),n=await fn(["ls-remote","--heads","--tags","--",r],r,t);return{branches:Yl(n,"refs/heads/"),tags:Yl(n,"refs/tags/")}}async function Ha(e,t={}){let r=Xl(e.remote,t.deployKey),n=uS(e.destination),i=e.ref?.trim()||e.binding.defaultBranch;if(!/^[A-Za-z0-9._/-]{1,255}$/.test(i)||i.startsWith("-")||i.includes(".."))throw Error("Git ref contains unsupported characters");let o=["clone","--no-tags","--single-branch","--branch",i],s=[...new Set(e.sparsePaths??[])];if(s.some((u)=>!u||u.startsWith("/")||u.split("/").includes("..")||/[\0\r\n]/.test(u)))throw Error("Sparse checkout paths must stay inside the repository");if(s.length)o.push("--filter=blob:none","--no-checkout");if(e.binding.cloneDepth)o.push("--depth",String(e.binding.cloneDepth));if(e.binding.submodules)o.push("--recurse-submodules","--shallow-submodules");if(o.push("--",r,n),await fn(o,r,t),s.length)await fn(["-C",n,"sparse-checkout","set","--cone","--",...s],r,t),await fn(["-C",n,"checkout","--force"],r,t);if(e.commitSha){if(!/^[a-f0-9]{40,64}$/i.test(e.commitSha))throw Error("Expected source commit must be an immutable 40-64 character SHA");await fn(["-C",n,"fetch","--no-tags","--depth","1","origin",e.commitSha],r,t),await fn(["-C",n,"checkout","--detach","--force",e.commitSha],r,t)}let c=(await fn(["-C",n,"rev-parse","HEAD"],r,t)).trim();if(!/^[a-f0-9]{40,64}$/i.test(c))throw Error("Git clone did not produce a valid commit SHA");if(e.commitSha&&c.toLowerCase()!==e.commitSha.toLowerCase())throw Error(`Git checkout resolved ${c} instead of the requested immutable commit`);return{directory:e.binding.monorepoRoot==="."?n:ko(n,e.binding.monorepoRoot),commitSha:c}}function Ni(e){return["github","gitlab","bitbucket","gitea"].includes(e)}async function Ga(e,t,r){let n=e.getConnection(t);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active source connection was not found");try{if(Ni(n.provider)){let s=await Vr(n,e.getCredential(n.id)).testConnection();return e.updateHealth(n.id,{status:s.ok?"healthy":"degraded",message:s.message,tested:!0,grantedScopes:s.scopes})}let i=r?e.getRepository(r):e.listRepositories(n.id,void 0,1)[0];if(!i)return e.updateHealth(n.id,{status:"degraded",message:"Add a repository URL before testing this generic connection.",tested:!0});let o=n.provider==="generic_ssh"?e.listBindings({connectionId:n.id}).map((s)=>s.deployKeyId).filter(Boolean).map((s)=>e.getDeployKey(s)).find(Boolean):void 0;return await Wa(i.cloneUrl,{credential:e.getCredential(n.id),deployKey:o?{...o,privateKey:e.getDeployPrivateKey(o.id)}:void 0}),e.updateHealth(n.id,{status:"healthy",message:"Git repository access is healthy.",tested:!0})}catch(i){return e.updateHealth(n.id,{status:"degraded",message:i instanceof Error?i.message:"Connection test failed",tested:!0})}}async function Ro(e,t,r={}){let n=e.getConnection(t);if(!n||!Ni(n.provider)||["disconnected","expired"].includes(n.status))throw Error("A hosted active source connection is required for repository discovery");let i=Vr(n,e.getCredential(n.id)),o=[],s;for(let c=0;c<Math.min(20,Math.max(1,r.maxPages??10));c++){let u=await i.listRepositories({cursor:s,search:r.search,limit:100});for(let a of u.repositories)o.push(e.upsertRepository({connectionId:n.id,...a}));if(s=u.nextCursor,!s)break}return e.updateHealth(n.id,{status:"healthy",message:`${o.length} repositories synchronized.`,synced:!0}),o}async function Po(e,t){let r=e.getConnection(t.connectionId);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active source connection was not found");if(Ni(r.provider)){let c=Vr(r,e.getCredential(r.id));return t.type==="tags"?c.listTags(t.repository,t):c.listBranches(t.repository,t)}let n=t.repositoryId?e.getRepository(t.repositoryId):e.listRepositories(r.id).find((c)=>c.fullName===t.repository);if(!n||n.connectionId!==r.id)throw Error("Generic repository metadata was not found");let i=t.deployKeyId?e.getDeployKey(t.deployKeyId):void 0;if(i&&i.connectionId!==r.id)throw Error("Deploy key does not belong to this connection");let o=await Wa(n.cloneUrl,{credential:e.getCredential(r.id),deployKey:i?{...i,privateKey:e.getDeployPrivateKey(i.id)}:void 0});return{refs:(t.type==="tags"?o.tags:o.branches).slice(0,Math.min(500,t.limit??100))}}async function $i(e,t,r){let n=e.getWebhook(t),i=n?e.getConnection(n.connectionId):void 0;if(!n||!i||["disconnected","expired"].includes(i.status))throw Error("Active source webhook was not found");let o=Hn(r,{...n,endpointToken:e.getWebhookEndpointToken(n.id)});if(!Ni(i.provider))return e.updateWebhookState(n.id,{status:"healthy",healthMessage:"Manual webhook endpoint is ready.",reconciled:!0});try{let s=Vr(i,e.getCredential(i.id)),c=e.getWebhookSecret(n.id),u=n.providerWebhookId?await s.updateWebhook(n.repositoryFullName,n.providerWebhookId,{url:o,secret:c,events:n.events}):await s.createWebhook(n.repositoryFullName,{url:o,secret:c,events:n.events});return e.updateWebhookState(n.id,{providerWebhookId:u.providerWebhookId,status:u.active?"healthy":"degraded",healthMessage:u.active?"Provider webhook is synchronized.":"Provider webhook exists but is inactive.",reconciled:!0})}catch(s){return e.updateWebhookState(n.id,{status:"degraded",healthMessage:s instanceof Error?s.message:"Webhook reconciliation failed",reconciled:!0})}}async function Zl(e,t){let r=e.getWebhook(t),n=r?e.getConnection(r.connectionId):void 0;if(!r||!n)throw Error("Source webhook was not found");if(Ni(n.provider)&&r.providerWebhookId&&!["disconnected","expired"].includes(n.status))await Vr(n,e.getCredential(n.id)).deleteWebhook(r.repositoryFullName,r.providerWebhookId);return e.updateWebhookState(r.id,{status:"disabled",healthMessage:"Webhook disabled."})}var xo="1.6.0";function Ka(){let e={type:"object",required:["error"],properties:{error:{type:"object",required:["code","message","requestId"],properties:{code:{type:"string"},message:{type:"string"},requestId:{type:"string",format:"uuid"},details:{}}}}},t=(n)=>({type:"object",required:["data","page","requestId"],properties:{data:{type:"array",items:n},page:{type:"object",required:["hasMore"],properties:{nextCursor:{type:"string"},hasMore:{type:"boolean"}}},requestId:{type:"string",format:"uuid"}}}),r=(n)=>({"200":{description:"A stable cursor page.",content:{"application/json":{schema:t(n)}}},default:{$ref:"#/components/responses/Error"}});return{openapi:"3.1.0",info:{title:"ts-cloud API",version:xo,description:"Additive changes are released within v1. Breaking request or response changes require a new URL version."},servers:[{url:"/"}],security:[{bearerAuth:[]}],paths:{...ep(),"/api/v1/projects":{get:{operationId:"listProjects",summary:"List accessible projects",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Project"})}},"/api/v1/projects/{projectId}/environments":{get:{operationId:"listEnvironments",summary:"List accessible project environments",parameters:[{$ref:"#/components/parameters/ProjectId"},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Environment"})}},"/api/v1/services":{get:{operationId:"listServices",summary:"List accessible services",parameters:[{name:"projectId",in:"query",required:!0,schema:{type:"string"}},{name:"environmentId",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Service"})}},"/api/v1/source/connections":{get:{operationId:"listSourceConnections",summary:"List safe Git connection metadata",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/SourceConnection"})},post:{operationId:"createSourceConnection",summary:"Create an encrypted Git connection",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["provider","name","host"],properties:{provider:{type:"string",enum:["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"]},name:{type:"string"},host:{type:"string",format:"uri"},token:{type:"string",writeOnly:!0},repositoryFullName:{type:"string"},repositoryUrl:{type:"string"}}}}}},responses:{"201":{description:"Encrypted connection created."},default:{$ref:"#/components/responses/Error"}}},delete:{operationId:"disconnectSourceConnection",summary:"Preview or safely disconnect a Git connection",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["id"],properties:{id:{type:"string"},preview:{type:"boolean"}}}}}},responses:{"200":{description:"Impact preview or disconnected connection."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/repositories":{get:{operationId:"listSourceRepositories",summary:"List or synchronize granted repositories",parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string"}},{name:"sync",in:"query",schema:{type:"boolean"}},{name:"search",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/SourceRepository"})}},"/api/v1/source/refs":{get:{operationId:"listSourceRefs",summary:"List repository branches or tags",parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string"}},{name:"repository",in:"query",required:!0,schema:{type:"string"}},{name:"repositoryId",in:"query",schema:{type:"string"}},{name:"type",in:"query",schema:{type:"string",enum:["branches","tags"]}}],responses:{"200":{description:"Provider reference page."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/bindings":{post:{operationId:"createSourceBinding",summary:"Bind a repository to an application",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/SourceBindingRequest"}}}},responses:{"201":{description:"Source binding created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/webhooks":{post:{operationId:"createSourceWebhook",summary:"Create and optionally reconcile a signed webhook",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["connectionId","repositoryFullName","baseUrl"],properties:{connectionId:{type:"string"},repositoryId:{type:"string"},repositoryFullName:{type:"string"},baseUrl:{type:"string",format:"uri"},events:{type:"array",items:{type:"string",enum:["push","pull_request"]}},reconcile:{type:"boolean"}}}}}},responses:{"201":{description:"Webhook endpoint created; endpoint is revealed once."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-detections":{post:{operationId:"detectApplication",summary:"Detect bounded application build candidates",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["files"],properties:{files:{type:"array",maxItems:1e4,items:{$ref:"#/components/schemas/DetectionFile"}}}}}}},responses:{"200":{description:"Ranked detection candidates with evidence."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-plans":{post:{operationId:"planApplication",summary:"Validate and normalize an application manifest",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["draft"],properties:{draft:{$ref:"#/components/schemas/ApplicationInput"},suppliedSecretNames:{type:"array",uniqueItems:!0,items:{type:"string"}}}}}}},responses:{"200":{description:"Validated plan, config patch, capabilities, costs, and missing secret names."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-drafts":{get:{operationId:"listApplicationDrafts",summary:"List resumable secret-free drafts",parameters:[{name:"projectId",in:"query",required:!0,schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/ApplicationDraft"})},post:{operationId:"createApplicationDraft",summary:"Create a resumable application draft",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/ApplicationDraftCreateRequest"}}}},responses:{"201":{description:"Draft created."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateApplicationDraft",summary:"Optimistically update a draft",requestBody:{required:!0,content:{"application/json":{schema:{allOf:[{$ref:"#/components/schemas/ApplicationDraftCreateRequest"},{type:"object",required:["id","version","step"],properties:{id:{type:"string"},version:{type:"integer",minimum:1}}}]}}}},responses:{"200":{description:"Updated draft."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/applications":{post:{operationId:"createApplication",summary:"Confirm and queue an application plan",parameters:[{name:"Idempotency-Key",in:"header",required:!0,schema:{type:"string",minLength:8,maxLength:128}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["draftId","version","confirmEnvironment"],properties:{draftId:{type:"string"},version:{type:"integer",minimum:1},confirmEnvironment:{type:"string",description:"Exact target environment slug."}}}}}},responses:{"202":{description:"Application operation queued; identical requests replay safely."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-artifacts":{post:{operationId:"uploadApplicationArtifact",summary:"Inspect and store a bounded ZIP or TAR source artifact",parameters:[{name:"X-Project-Id",in:"header",required:!0,schema:{type:"string"}},{name:"X-Artifact-Filename",in:"header",required:!0,schema:{type:"string"}}],requestBody:{required:!0,content:{"application/octet-stream":{schema:{type:"string",format:"binary",maxLength:104857600}}}},responses:{"201":{description:"Deduplicated artifact metadata; archive contents are never executed."},"413":{$ref:"#/components/responses/Error"},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/registry-connections":{get:{operationId:"listRegistryConnections",summary:"List safe private-registry metadata",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/RegistryConnection"})},post:{operationId:"createRegistryConnection",summary:"Create an encrypted private-registry connection",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/RegistryConnectionRequest"}}}},responses:{"201":{description:"Encrypted registry connection created."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateRegistryConnection",summary:"Test access or rotate write-only credentials",requestBody:{required:!0,content:{"application/json":{schema:{allOf:[{$ref:"#/components/schemas/RegistryConnectionRequest"},{type:"object",required:["id","action"],properties:{id:{type:"string"},action:{type:"string",enum:["test","rotate"]},image:{type:"string"}}}]}}}},responses:{"200":{description:"Safe connection health metadata."},default:{$ref:"#/components/responses/Error"}}},delete:{operationId:"disconnectRegistryConnection",summary:"Disconnect and erase registry credentials",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"}}}}}},responses:{"200":{description:"Credentials erased and connection disconnected."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue":{get:{operationId:"listQueue",summary:"List authorized durable operations and blocking metadata",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{name:"state",in:"query",schema:{type:"string",enum:["queued","running","succeeded","failed","cancelled","timed_out"]}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/QueueOperation"})}},"/api/v1/preview-definitions":{get:{operationId:"listPreviewDefinitions",summary:"List preview policies",responses:r({type:"object"})},post:{operationId:"createPreviewDefinition",summary:"Configure bounded preview policy",responses:{"200":{description:"Preview definition created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews":{get:{operationId:"listPreviews",summary:"List authorized persistent previews",responses:r({type:"object"})},post:{operationId:"createPreview",summary:"Create or update one immutable preview identity",responses:{"200":{description:"Preview deployment queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/destroy":{post:{operationId:"destroyPreview",summary:"Confirm tagged preview teardown",responses:{"200":{description:"Teardown queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/extend":{post:{operationId:"extendPreview",summary:"Extend preview TTL",responses:{"200":{description:"Expiry extended."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/rebuild":{post:{operationId:"rebuildPreview",summary:"Rebuild the exact recorded commit",responses:{"200":{description:"Rebuild queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/cleanup":{post:{operationId:"cleanupPreviews",summary:"Dry-run or queue TTL/keep-count teardown",responses:{"200":{description:"Cleanup plan or operations."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-templates":{get:{operationId:"listComposeTemplates",summary:"List pinned verified application templates",responses:r({type:"object"})}},"/api/v1/compose-applications":{get:{operationId:"listComposeApplications",summary:"List authorized multi-service applications",responses:r({type:"object"})},post:{operationId:"createComposeApplication",summary:"Import Compose or materialize a template",responses:{"200":{description:"Editable normalized application."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/preview":{post:{operationId:"previewComposeApplication",summary:"Parse and diagnose Compose without mutation",responses:{"200":{description:"Normalized preview and actionable diagnostics."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/{applicationId}/services":{get:{operationId:"listComposeServices",summary:"Inspect per-service desired and observed state",responses:{"200":{description:"Service topology and status."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/{applicationId}/{action}":{post:{operationId:"operateComposeApplication",summary:"Deploy, redeploy, start, stop, scale, or delete through the durable queue",responses:{"200":{description:"Scoped operation queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/release-artifacts":{post:{operationId:"createReleaseArtifact",summary:"Register a verified content-addressed artifact",responses:{"200":{description:"Artifact identity registered."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases":{get:{operationId:"listReleases",summary:"List unified authorized release history",responses:r({type:"object"})},post:{operationId:"createRelease",summary:"Create an immutable release from an existing artifact",responses:{"200":{description:"Release record created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/capabilities":{get:{operationId:"getReleaseCapabilities",summary:"Explain supported strategies, capacity, cost, and rollback",responses:{"200":{description:"Provider-aware strategy capabilities."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/{releaseId}":{get:{operationId:"getRelease",summary:"Inspect provenance, approvals, health, and transitions",responses:{"200":{description:"Release detail."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/{releaseId}/{action}":{post:{operationId:"operateRelease",summary:"Promote, approve, activate, roll back, report health, or pin",responses:{"200":{description:"Release lifecycle updated."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue/settings":{get:{operationId:"getQueueSettings",summary:"Get effective concurrency limits",responses:{"200":{description:"Queue concurrency settings."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateQueueSettings",summary:"Confirm and audit production concurrency changes",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["confirm","concurrency"],properties:{confirm:{const:"update queue limits"},concurrency:{$ref:"#/components/schemas/QueueConcurrency"}}}}}},responses:{"200":{description:"Updated effective limits."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue/history":{delete:{operationId:"clearQueueHistory",summary:"Clear terminal jobs whose retention has elapsed",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["confirm"],properties:{confirm:{const:"clear completed"},before:{type:"string",format:"date-time"},projectId:{type:"string"}}}}}},responses:{"200":{description:"Eligible history cleared with an audit event."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/logs":{get:{operationId:"listOperationLogs",summary:"Resume ordered sanitized operation logs from a cursor",parameters:[{$ref:"#/components/parameters/OperationId"},{name:"after",in:"query",schema:{type:"integer",minimum:0}},{$ref:"#/components/parameters/Limit"}],responses:{"200":{description:"Ordered log chunks and next cursor."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/logs/stream":{get:{operationId:"streamOperationLogs",summary:"Stream authorized operation logs with Last-Event-ID resume",parameters:[{$ref:"#/components/parameters/OperationId"},{name:"Last-Event-ID",in:"header",schema:{type:"integer",minimum:0}}],responses:{"200":{description:"Server-sent log and completion events.",content:{"text/event-stream":{schema:{type:"string"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/cancel":{post:{operationId:"cancelOperation",summary:"Cancel queued work or request cooperative running cancellation",parameters:[{$ref:"#/components/parameters/OperationId"}],requestBody:{content:{"application/json":{schema:{type:"object"}}}},responses:{"200":{description:"Cancellation state recorded."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/retry":{post:{operationId:"retryOperation",summary:"Retry an allow-listed failure class within the attempt limit",parameters:[{$ref:"#/components/parameters/OperationId"}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["errorClass"],properties:{errorClass:{type:"string"},delayMs:{type:"integer",minimum:0}}}}}},responses:{"200":{description:"Retry queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/deployments":{post:{operationId:"createDeployment",summary:"Queue a deployment",parameters:[{name:"Idempotency-Key",in:"header",required:!0,schema:{type:"string",minLength:8,maxLength:128}}],requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/DeploymentRequest"}}}},responses:{"202":{description:"Queued operation.",content:{"application/json":{schema:{$ref:"#/components/schemas/OperationResponse"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations":{get:{operationId:"listOperations",summary:"List scoped operations",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Operation"})}},"/api/v1/events":{get:{operationId:"listEvents",summary:"List scoped audit events",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{name:"after",in:"query",schema:{type:"integer",minimum:0}},{$ref:"#/components/parameters/Limit"}],responses:r({$ref:"#/components/schemas/Event"})}},"/api/v1/events/stream":{get:{operationId:"streamEvents",summary:"Stream scoped audit events",responses:{"200":{description:"Authenticated server-sent event stream.",content:{"text/event-stream":{schema:{type:"string"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/openapi.json":{get:{operationId:"getOpenApi",summary:"Get the OpenAPI contract",security:[],responses:{"200":{description:"OpenAPI 3.1 contract."}}}}},components:{securitySchemes:{bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"tsc_v1"}},parameters:{Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50}},Cursor:{name:"cursor",in:"query",schema:{type:"string"}},ProjectId:{name:"projectId",in:"path",required:!0,schema:{type:"string"}},OperationId:{name:"operationId",in:"path",required:!0,schema:{type:"string"}}},responses:{Error:{description:"Stable error envelope.",content:{"application/json":{schema:e}}}},schemas:{Project:{type:"object",required:["id","slug","name"],properties:{id:{type:"string"},slug:{type:"string"},name:{type:"string"},description:{type:"string"}}},Environment:{type:"object",required:["id","projectId","slug","name","kind"],properties:{id:{type:"string"},projectId:{type:"string"},slug:{type:"string"},name:{type:"string"},kind:{type:"string"},region:{type:"string"}}},Service:{type:"object",required:["id","projectId","kind","slug","name"],properties:{id:{type:"string"},projectId:{type:"string"},environmentId:{type:"string"},kind:{type:"string"},slug:{type:"string"},name:{type:"string"},metadata:{type:"object",additionalProperties:!0}}},SourceConnection:{type:"object",required:["id","provider","name","host","status","credentialConfigured"],properties:{id:{type:"string"},provider:{type:"string"},name:{type:"string"},host:{type:"string"},status:{type:"string"},credentialConfigured:{type:"boolean"},credentialFingerprint:{type:"string"},grantedScopes:{type:"array",items:{type:"string"}}}},SourceRepository:{type:"object",required:["id","connectionId","fullName","cloneUrl","defaultBranch"],properties:{id:{type:"string"},connectionId:{type:"string"},fullName:{type:"string"},cloneUrl:{type:"string"},defaultBranch:{type:"string"},visibility:{type:"string"},archived:{type:"boolean"}}},SourceBindingRequest:{type:"object",additionalProperties:!1,required:["projectId","connectionId","repositoryFullName"],properties:{projectId:{type:"string"},environmentId:{type:"string"},resourceId:{type:"string"},connectionId:{type:"string"},repositoryId:{type:"string"},repositoryFullName:{type:"string"},defaultBranch:{type:"string"},branchRule:{type:"string"},tagRule:{type:"string"},monorepoRoot:{type:"string"},includePaths:{type:"array",items:{type:"string"}},excludePaths:{type:"array",items:{type:"string"}},submodules:{type:"boolean"},cloneDepth:{type:"integer",minimum:1},deployKeyId:{type:"string"},autoDeploy:{type:"boolean"},pullRequestPreviews:{type:"boolean"}}},DetectionFile:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string"},size:{type:"integer",minimum:0},content:{type:"string",maxLength:262144}}},ApplicationInput:{type:"object",additionalProperties:!1,required:["schemaVersion","name","slug","projectId","environmentId","source","build","runtime"],properties:{schemaVersion:{const:1},name:{type:"string"},slug:{type:"string"},projectId:{type:"string"},environmentId:{type:"string"},source:{type:"object",required:["kind"],properties:{kind:{type:"string",enum:["git","local","artifact","image"]}},additionalProperties:!0},build:{type:"object",required:["kind"],properties:{kind:{type:"string",enum:["dockerfile","buildpack","static","server","serverless","prebuilt_image"]},secretNames:{type:"array",uniqueItems:!0,items:{type:"string"}}},additionalProperties:!0},runtime:{type:"object",required:["architecture","target"],properties:{architecture:{type:"string",enum:["x86_64","arm64"]},target:{type:"string",enum:["server","serverless","container"]},port:{type:"integer",minimum:1,maximum:65535},healthCheck:{type:"object",additionalProperties:!0}},additionalProperties:!0},environment:{type:"object",additionalProperties:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["secretRef"],properties:{secretRef:{type:"string"}}}]}},requiredSecretNames:{type:"array",uniqueItems:!0,items:{type:"string"}},domain:{type:"object",properties:{hostname:{type:"string"},path:{type:"string"},tls:{type:"boolean"}}}}},ApplicationDraftCreateRequest:{type:"object",additionalProperties:!1,required:["projectId","draft"],properties:{projectId:{type:"string"},name:{type:"string"},draft:{$ref:"#/components/schemas/ApplicationInput"},step:{type:"string",enum:["source","build","runtime","environment","domain","review"]},suppliedSecretNames:{type:"array",uniqueItems:!0,description:"Names only; values must use the secrets boundary.",items:{type:"string"}}}},ApplicationDraft:{type:"object",required:["id","projectId","input","step","status","version"],properties:{id:{type:"string"},projectId:{type:"string"},input:{$ref:"#/components/schemas/ApplicationInput"},step:{type:"string"},suppliedSecretNames:{type:"array",items:{type:"string"}},status:{type:"string",enum:["draft","ready","applied"]},version:{type:"integer"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}}},RegistryConnectionRequest:{type:"object",properties:{provider:{type:"string",enum:["docker_hub","ghcr","ecr","gcr","generic"]},name:{type:"string"},host:{type:"string"},username:{type:"string",writeOnly:!0},password:{type:"string",writeOnly:!0},token:{type:"string",writeOnly:!0},credentialExpiresAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"}}},RegistryConnection:{type:"object",required:["id","provider","name","host","credentialConfigured","status","version"],properties:{id:{type:"string"},provider:{type:"string"},name:{type:"string"},host:{type:"string"},credentialConfigured:{type:"boolean"},credentialFingerprint:{type:"string"},credentialExpiresAt:{type:"string",format:"date-time"},status:{type:"string",enum:["pending","healthy","degraded","expired","disconnected"]},healthMessage:{type:"string"},lastTestedAt:{type:"string",format:"date-time"},version:{type:"integer"}}},QueueConcurrency:{type:"object",additionalProperties:!1,properties:{project:{type:"integer",minimum:1,maximum:100},environment:{type:"integer",minimum:1,maximum:100},provider:{type:"integer",minimum:1,maximum:100},builds:{type:"integer",minimum:1,maximum:100}}},QueueOperation:{allOf:[{$ref:"#/components/schemas/Operation"},{type:"object",required:["queue"],properties:{queue:{type:"object",required:["maxAttempts","availableAt","timeoutSeconds","retryClasses","resumePolicy","cancellationMode","retentionUntil"],properties:{lockKey:{type:"string"},providerKey:{type:"string"},buildSlot:{type:"boolean"},maxAttempts:{type:"integer"},availableAt:{type:"string",format:"date-time"},timeoutSeconds:{type:"integer"},heartbeatAt:{type:"string",format:"date-time"},currentStep:{type:"string"},blockedReason:{type:"string"},retryClasses:{type:"array",items:{type:"string"}},resumePolicy:{type:"string",enum:["fail","requeue"]},cancellationMode:{type:"string",enum:["cooperative","provider_non_cancellable"]},retentionUntil:{type:"string",format:"date-time"}}},approximatePosition:{type:"object",properties:{ahead:{type:"integer"},precision:{const:"bounded"}}}}}]},DeploymentRequest:{type:"object",additionalProperties:!1,required:["projectId","environmentId"],properties:{projectId:{type:"string"},environmentId:{type:"string"},serviceId:{type:"string"},action:{type:"string",enum:["deploy","rollback"],default:"deploy"},revision:{type:"string"}}},Operation:{type:"object",required:["id","state","kind","correlationId","createdAt"],properties:{id:{type:"string"},state:{type:"string"},kind:{type:"string"},correlationId:{type:"string"},createdAt:{type:"string",format:"date-time"}}},OperationResponse:{type:"object",required:["operation","idempotentReplay","requestId"],properties:{operation:{$ref:"#/components/schemas/Operation"},idempotentReplay:{type:"boolean"},requestId:{type:"string",format:"uuid"}}},Event:{type:"object",required:["id","sequence","type","level","correlationId","createdAt"],properties:{id:{type:"string"},sequence:{type:"integer"},type:{type:"string"},level:{type:"string"},correlationId:{type:"string"},payload:{},createdAt:{type:"string",format:"date-time"}}}}}}}function mS(e){return Buffer.from(JSON.stringify(e)).toString("base64url")}function fS(e){if(!e)return;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t&&typeof t==="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ft(e,t,r,n=["createdAt","id"]){let i=Math.min(100,Math.max(1,Number(t.searchParams.get("limit"))||50)),o=fS(t.searchParams.get("cursor"));if(t.searchParams.has("cursor")&&!o)throw new X("invalid_cursor","The pagination cursor is invalid.",400);let s=0;if(o){let p=e.findIndex((f)=>n.every((y)=>f[y]===o[y]));if(p<0)throw new X("invalid_cursor","The pagination cursor is no longer available.",400);s=p+1}let c=e.slice(s,s+i),u=s+i<e.length,a=c.at(-1);return{data:c,page:{hasMore:u,nextCursor:u&&a?mS(Object.fromEntries(n.map((p)=>[p,a[p]]))):void 0},requestId:r}}function Ya(e){let t=new Qa(e.controlPlane,e.identities),r=new xe(e.controlPlane),n=new _o(e.controlPlane),i=new Oo(e.controlPlane),o=new ln(e.controlPlane),s=e.spend?.store??new tp(e.controlPlane,{now:e.now}),c={store:s,service:e.spend?.service??new rp(s)},u=new Map,a=e.now??(()=>new Date),p=e.rateLimit??120,f=(b,C,T,R={})=>new Response(JSON.stringify(b),{status:C,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store","x-request-id":T,"x-api-version":xo,...R}}),y=(b,C,T,R,x,L)=>f({error:{code:b,message:C,requestId:R,details:x}},T,R,L);return async(b,C)=>{let T=new URL(b.url);if(!T.pathname.startsWith("/api/v1"))return;let R=crypto.randomUUID();if(T.pathname==="/api/v1/openapi.json"&&b.method==="GET")return f(Ka(),200,R,{"cache-control":"public, max-age=300"});let x=b.headers.get("authorization")??"",L=x.startsWith("Bearer ")?x.slice(7).trim():"",P=L?e.identities.verifyToken(L,C):void 0;if(!P)return y("unauthorized","A valid bearer token is required.",401,R,void 0,{"www-authenticate":'Bearer realm="ts-cloud", error="invalid_token"'});let G=u.get(P.token.id),ae=a().getTime(),Z=!G||ae-G.start>=60000?{start:ae,count:0}:G;Z.count+=1,u.set(P.token.id,Z);let Le=Math.max(0,p-Z.count),ue={"x-ratelimit-limit":String(p),"x-ratelimit-remaining":String(Le),"x-ratelimit-reset":String(Math.ceil((Z.start+60000)/1000))};if(Z.count>p)return y("rate_limited","API rate limit exceeded.",429,R,void 0,{...ue,"retry-after":String(Math.max(1,Math.ceil((Z.start+60000-ae)/1000)))});try{let W,ie=async()=>{let E=await b.text();if(E.length>1048576)throw new X("payload_too_large","Request body exceeds 1 MB.",413);try{return JSON.parse(E)}catch{throw new X("invalid_json","Request body must be valid JSON.",400)}},Ce=/^\/api\/v1\/projects\/([^/]+)\/environments$/.exec(T.pathname),Yt=/^\/api\/v1\/operations\/([^/]+)\/logs(?:\/(stream))?$/.exec(T.pathname),Nr=/^\/api\/v1\/operations\/([^/]+)\/(cancel|retry)$/.exec(T.pathname),jt=/^\/api\/v1\/previews\/([^/]+)\/(destroy|extend|rebuild)$/.exec(T.pathname),Xt=/^\/api\/v1\/compose-applications\/([^/]+)\/(deploy|redeploy|start|stop|scale|delete)$/.exec(T.pathname),Zt=/^\/api\/v1\/compose-applications\/([^/]+)\/services$/.exec(T.pathname),er=/^\/api\/v1\/releases\/([^/]+)\/(promote|approve|activate|rollback|health|pin)$/.exec(T.pathname);if(b.method==="GET"&&T.pathname==="/api/v1/projects")W=ft(t.listProjects(P),T,R);else if(b.method==="GET"&&Ce)W=ft(t.listEnvironments(P,decodeURIComponent(Ce[1])),T,R);else if(b.method==="GET"&&T.pathname==="/api/v1/services"){let E=T.searchParams.get("projectId");if(!E)throw new X("validation_error","projectId is required.",422);W=ft(t.listServices(P,E,T.searchParams.get("environmentId")??void 0),T,R)}else if(b.method==="GET"&&T.pathname==="/api/v1/operations")W=ft(t.listOperations(P,T.searchParams.get("projectId")??void 0),T,R);else if(b.method==="GET"&&T.pathname==="/api/v1/previews"){let E=T.searchParams.get("projectId")??void 0,N=n.previews.listInstances({projectId:E}).filter((V)=>{try{return t.authorize(P,"deployments:read",{type:"resource",id:V.resourceId}),!0}catch{return!1}}).map((V)=>({...V}));W=ft(N,T,R)}else if(b.method==="GET"&&T.pathname==="/api/v1/compose-templates")W=ft(Do().map((E)=>({...E})),T,R,["id","version"]);else if(b.method==="GET"&&T.pathname==="/api/v1/releases/capabilities"){let E=String(T.searchParams.get("kind")??"");W={capabilities:Di({kind:E,hasHealthGate:T.searchParams.get("health")==="true",replicas:Number(T.searchParams.get("replicas"))||1}),requestId:R}}else if(b.method==="GET"&&T.pathname==="/api/v1/releases"){let E=T.searchParams.get("projectId");if(!E)throw new X("validation_error","projectId is required.",422);t.authorize(P,"project:read",{type:"project",id:E});let N=o.releases.list({projectId:E,environmentId:T.searchParams.get("environmentId")??void 0,resourceId:T.searchParams.get("resourceId")??void 0}).filter((V)=>{try{return t.authorize(P,"deployments:read",{type:"resource",id:V.resourceId}),!0}catch{return!1}}).map((V)=>({...V,artifact:o.releases.getArtifact(V.artifactId),transitions:o.releases.transitions(V.id),approvals:o.releases.approvals(V.id)}));W=ft(N,T,R)}else if(b.method==="POST"&&T.pathname==="/api/v1/release-artifacts"){let E=await ie();t.authorize(P,"applications:manage",{type:"organization"}),W={artifact:o.releases.registerArtifact({organizationId:P.serviceAccount.organizationId,digest:String(E.digest??""),kind:String(E.kind??""),uri:String(E.uri??""),size:Number(E.size),mediaType:typeof E.mediaType==="string"?E.mediaType:void 0,provenance:E.provenance,attestation:E.attestation}),requestId:R}}else if(b.method==="POST"&&T.pathname==="/api/v1/releases"){let E=await ie(),N=String(E.resourceId??"");t.authorize(P,"applications:manage",{type:"resource",id:N}),W={release:o.releases.create({organizationId:P.serviceAccount.organizationId,projectId:String(E.projectId??""),environmentId:String(E.environmentId??""),resourceId:N,artifactId:String(E.artifactId??""),kind:String(E.kind??""),sourceSha:typeof E.sourceSha==="string"?E.sourceSha:void 0,config:E.config??{},manifest:E.manifest??{},provenance:E.provenance,strategy:String(E.strategy??"atomic"),healthGate:E.healthGate,hooks:E.hooks,drainSeconds:Number(E.drainSeconds)||void 0,graceSeconds:Number(E.graceSeconds)||void 0,automaticRollback:E.automaticRollback!==!1,actorId:P.actor.id,trigger:typeof E.trigger==="string"?E.trigger:"api",approvalRequired:E.approvalRequired===!0,replicas:Number(E.replicas)||void 0}),requestId:R}}else if(b.method==="GET"&&/^\/api\/v1\/releases\/[^/]+$/.test(T.pathname)){let E=decodeURIComponent(T.pathname.split("/").at(-1)),N=o.releases.get(E);if(!N)throw new X("not_found","Release was not found.",404);t.authorize(P,"deployments:read",{type:"resource",id:N.resourceId}),W={release:N,artifact:o.releases.getArtifact(N.artifactId),transitions:o.releases.transitions(E),approvals:o.releases.approvals(E),requestId:R}}else if(b.method==="POST"&&er){let E=o.releases.get(decodeURIComponent(er[1]));if(!E)throw new X("not_found","Release was not found.",404);let N=await ie(),V=er[2];if(V==="promote"){let H=String(N.targetResourceId??"");t.authorize(P,"deployments:create",{type:"resource",id:H}),W={release:o.releases.promote(E.id,{targetEnvironmentId:String(N.targetEnvironmentId??""),targetResourceId:H,config:N.config??{},strategy:N.strategy,healthGate:N.healthGate,actorId:P.actor.id,approvalRequired:N.approvalRequired===!0}),requestId:R}}else if(V==="approve")t.authorize(P,"deployments:create",{type:"resource",id:E.resourceId}),W={release:o.releases.approve(E.id,{actorId:P.actor.id,decision:N.decision==="rejected"?"rejected":"approved",comment:typeof N.comment==="string"?N.comment:void 0}),requestId:R};else if(V==="activate")t.authorize(P,"deployments:create",{type:"resource",id:E.resourceId}),W={operation:t.operation(o.enqueueActivation(E,{actorId:P.actor.id})),requestId:R};else if(V==="rollback")t.authorize(P,"deployments:create",{type:"resource",id:E.resourceId}),W={operation:t.operation(o.enqueueRollback(E,{actorId:P.actor.id,targetReleaseId:typeof N.targetReleaseId==="string"?N.targetReleaseId:void 0})),requestId:R};else if(V==="health"){t.authorize(P,"deployments:create",{type:"resource",id:E.resourceId});let H=o.completeHealthGate(E.id,{healthy:N.healthy===!0,operationId:typeof N.operationId==="string"?N.operationId:void 0,health:N.health,message:typeof N.message==="string"?N.message:void 0});W={release:H.release,rollbackOperation:H.rollbackOperation?t.operation(H.rollbackOperation):void 0,requestId:R}}else t.authorize(P,"deployments:create",{type:"resource",id:E.resourceId}),W={release:o.releases.pin(E.id,N.pinned!==!1,typeof N.reason==="string"?N.reason:void 0),requestId:R}}else if(b.method==="GET"&&T.pathname==="/api/v1/compose-applications"){let E=T.searchParams.get("projectId");if(!E)throw new X("validation_error","projectId is required.",422);t.authorize(P,"project:read",{type:"project",id:E});let N=i.applications.list({projectId:E,environmentId:T.searchParams.get("environmentId")??void 0}).filter((V)=>{try{return t.authorize(P,"deployments:read",{type:"resource",id:V.resourceId}),!0}catch{return!1}}).map((V)=>({...V,services:i.applications.services(V.id)}));W=ft(N,T,R)}else if(b.method==="POST"&&T.pathname==="/api/v1/compose-applications/preview"){let E=await ie(),N=String(E.projectId??"");t.authorize(P,"project:read",{type:"project",id:N}),W={result:i.applications.preview(String(E.source??""),{name:String(E.name??""),slug:typeof E.slug==="string"?E.slug:void 0,projectId:N,environmentId:String(E.environmentId??"")}),requestId:R}}else if(b.method==="POST"&&T.pathname==="/api/v1/compose-applications"){let E=await ie(),N=String(E.projectId??"");t.authorize(P,"applications:manage",{type:"environment",id:String(E.environmentId??"")});let V={name:String(E.name??""),slug:typeof E.slug==="string"?E.slug:void 0,projectId:N,environmentId:String(E.environmentId??""),createdByActorId:P.actor.id},H=typeof E.templateId==="string"?i.applications.fromTemplate(E.templateId,E.inputs&&typeof E.inputs==="object"&&!Array.isArray(E.inputs)?E.inputs:{},{...V,version:typeof E.templateVersion==="string"?E.templateVersion:void 0}):i.applications.import(String(E.source??""),V);W={application:H.application,diagnostics:H.parsed.diagnostics,requestId:R}}else if(b.method==="GET"&&Zt){let E=i.applications.get(decodeURIComponent(Zt[1]));if(!E)throw new X("not_found","Compose application was not found.",404);t.authorize(P,"deployments:read",{type:"resource",id:E.resourceId}),W={application:E,services:i.applications.services(E.id),requestId:R}}else if(b.method==="POST"&&Xt){let E=i.applications.get(decodeURIComponent(Xt[1]));if(!E)throw new X("not_found","Compose application was not found.",404);let N=Xt[2],V=await ie();t.authorize(P,N==="delete"||N==="stop"?"deployments:cancel":"deployments:create",{type:"resource",id:E.resourceId}),W={operation:t.operation(i.enqueue(E,N,{actorId:P.actor.id,service:typeof V.service==="string"?V.service:void 0,replicas:Number.isFinite(Number(V.replicas))?Number(V.replicas):void 0,removeVolumes:V.removeVolumes===!0,confirmation:typeof V.confirm==="string"?V.confirm:void 0})),requestId:R}}else if(b.method==="GET"&&T.pathname==="/api/v1/preview-definitions"){let E=T.searchParams.get("projectId");if(!E)throw new X("validation_error","projectId is required.",422);t.authorize(P,"project:read",{type:"project",id:E}),W=ft(n.previews.listDefinitions(E).map((N)=>({...N})),T,R)}else if(b.method==="POST"&&T.pathname==="/api/v1/preview-definitions"){let E=await ie();t.authorize(P,"config:write",{type:"resource",id:String(E.resourceId??"")}),W={definition:n.previews.createDefinition({...E,projectId:String(E.projectId??""),resourceId:String(E.resourceId??""),baseEnvironmentId:String(E.baseEnvironmentId??""),domainPattern:String(E.domainPattern??""),createdByActorId:P.actor.id}),requestId:R}}else if(b.method==="POST"&&T.pathname==="/api/v1/previews"){let E=await ie(),N=n.previews.getDefinition(String(E.definitionId??""));if(!N)throw new X("not_found","Preview definition was not found.",404);t.authorize(P,"deployments:create",{type:"resource",id:N.resourceId});let V=n.previews.upsert({definitionId:N.id,sourceProvider:"api",repository:typeof E.repository==="string"?E.repository:"api",branch:String(E.branch??""),pullRequestNumber:Number(E.pullRequestNumber)||void 0,fork:E.fork===!0,commitSha:String(E.commitSha??""),createdByActorId:P.actor.id});W={preview:V.preview,operation:t.operation(n.enqueueDeploy(V.preview,{created:V.created,actorId:P.actor.id})),requestId:R}}else if(b.method==="POST"&&jt){let E=n.previews.getInstance(decodeURIComponent(jt[1]));if(!E)throw new X("not_found","Preview was not found.",404);let N=await ie(),V=jt[2];if(V==="destroy"){if(t.authorize(P,"deployments:cancel",{type:"resource",id:E.resourceId}),N.confirm!==E.name)throw new X("confirmation_required",`Type ${E.name} to confirm preview teardown.`,409);W={operation:t.operation(n.enqueueDestroy(E,"api",P.actor.id)),requestId:R}}else if(V==="extend")t.authorize(P,"deployments:create",{type:"resource",id:E.resourceId}),W={preview:n.previews.extend(E.id,Number(N.hours)),requestId:R};else t.authorize(P,"deployments:create",{type:"resource",id:E.resourceId}),W={operation:t.operation(n.enqueueDeploy(E,{actorId:P.actor.id,reason:"manual_rebuild"})),requestId:R}}else if(b.method==="POST"&&T.pathname==="/api/v1/previews/cleanup"){t.authorize(P,"automation:manage",{type:"organization"});let E=await ie();if(!E.dryRun&&E.confirm!=="cleanup previews")throw new X("confirmation_required","Type cleanup previews to confirm preview cleanup.",409);W={...n.cleanup({dryRun:E.dryRun===!0,maxAgeHours:Number(E.maxAgeHours)||void 0,keepCount:Number(E.keepCount)||void 0,actorId:P.actor.id}),requestId:R}}else if(b.method==="GET"&&T.pathname==="/api/v1/queue"){let E=T.searchParams.get("projectId")??void 0,N=T.searchParams.get("state"),V=r.list({projectId:E,state:["queued","running","succeeded","failed","cancelled","timed_out"].includes(N)?N:void 0,limit:500}).filter((H)=>{let ke=H.operation.resourceId?{type:"resource",id:H.operation.resourceId}:H.operation.environmentId?{type:"environment",id:H.operation.environmentId}:H.operation.projectId?{type:"project",id:H.operation.projectId}:{type:"organization"};try{return t.authorize(P,"deployments:read",ke),!0}catch{return!1}}).map((H)=>({...t.operation(H.operation),queue:H.job,approximatePosition:H.approximatePosition}));W=ft(V,T,R)}else if(b.method==="GET"&&T.pathname==="/api/v1/queue/settings")t.authorize(P,"deployments:read",P.token.scope),W={concurrency:r.limits,requestId:R};else if(b.method==="PATCH"&&T.pathname==="/api/v1/queue/settings"){t.authorize(P,"automation:manage",{type:"organization"});let E=await ie();if(E.confirm!=="update queue limits")throw new X("confirmation_required","Type update queue limits to confirm production concurrency changes.",409);W={concurrency:r.configureConcurrency(E.concurrency??{},{organizationId:P.serviceAccount.organizationId,actorId:P.actor.id}),requestId:R}}else if(b.method==="DELETE"&&T.pathname==="/api/v1/queue/history"){t.authorize(P,"automation:manage",{type:"organization"});let E=await ie();if(E.confirm!=="clear completed")throw new X("confirmation_required","Type clear completed to confirm queue retention cleanup.",409);W={deleted:r.clearCompleted({before:typeof E.before==="string"?E.before:void 0,actorId:P.actor.id,projectId:typeof E.projectId==="string"?E.projectId:void 0}),requestId:R}}else if(b.method==="GET"&&Yt){let E=e.controlPlane.getOperation(decodeURIComponent(Yt[1]));if(!E)throw new X("not_found","Operation was not found.",404);let N=E.resourceId?{type:"resource",id:E.resourceId}:E.environmentId?{type:"environment",id:E.environmentId}:E.projectId?{type:"project",id:E.projectId}:{type:"organization"};t.authorize(P,"deployments:read",N);let V=b.headers.get("last-event-id")?.trim(),H=Number(V||T.searchParams.get("after")||0);if(Yt[2]==="stream"){let Be=new TextEncoder,U=H,ge,ce=!1,ee=new ReadableStream({start(ot){let Bn=()=>{if(ce)return;if(!e.identities.verifyToken(L,C)){if(ce=!0,ge)clearInterval(ge);ot.close();return}let tr=r.logs(E.id,{after:U,limit:500});for(let Re of tr)U=Re.sequence,ot.enqueue(Be.encode(`id: ${Re.sequence}
|
|
8
|
-
event: log
|
|
9
|
-
data: ${JSON.stringify(Re)}
|
|
10
|
-
|
|
11
|
-
`));let Ee=e.controlPlane.getOperation(E.id);if(Ee&&["succeeded","failed","cancelled","timed_out"].includes(Ee.state)&&!r.logs(E.id,{after:U,limit:1}).length){if(ce=!0,ge)clearInterval(ge);ot.enqueue(Be.encode(`event: complete
|
|
12
|
-
data: ${JSON.stringify({state:Ee.state,cursor:U})}
|
|
13
|
-
|
|
14
|
-
`)),ot.close()}};if(Bn(),!ce)ge=setInterval(Bn,500);b.signal.addEventListener("abort",()=>{if(ce=!0,ge)clearInterval(ge);try{ot.close()}catch{}},{once:!0})},cancel(){if(ce=!0,ge)clearInterval(ge)}});return new Response(ee,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no","x-request-id":R,...ue}})}let ke=r.logs(E.id,{after:H,limit:Number(T.searchParams.get("limit"))||void 0});W={data:ke,cursor:ke.at(-1)?.sequence??H,hasMore:ke.length>=Math.min(1000,Math.max(1,Number(T.searchParams.get("limit"))||200)),requestId:R}}else if(b.method==="POST"&&Nr){let E=e.controlPlane.getOperation(decodeURIComponent(Nr[1]));if(!E)throw new X("not_found","Operation was not found.",404);let N=E.resourceId?{type:"resource",id:E.resourceId}:E.environmentId?{type:"environment",id:E.environmentId}:E.projectId?{type:"project",id:E.projectId}:{type:"organization"},V=await ie();if(Nr[2]==="cancel")t.authorize(P,"deployments:cancel",N),W={operation:t.operation(r.requestCancellation(E.id,P.actor.id)),requestId:R};else t.authorize(P,"deployments:create",N),W={operation:t.operation(r.retry(E.id,String(V.errorClass??"manual"),{delayMs:Number(V.delayMs)||0,actorId:P.actor.id})),requestId:R}}else if(b.method==="GET"&&T.pathname==="/api/v1/source/connections"){if(!e.sources)throw new X("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:read",P.token.scope),W=ft(e.sources.listConnections(P.serviceAccount.organizationId),T,R,["createdAt","id"])}else if(b.method==="GET"&&T.pathname==="/api/v1/source/repositories"){if(!e.sources)throw new X("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:read",P.token.scope);let E=e.sources.getConnection(T.searchParams.get("connectionId")??"");if(!E||E.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Source connection was not found.",404);if(T.searchParams.get("sync")==="true")t.authorize(P,"sources:manage",{type:"organization"}),await Ro(e.sources,E.id,{search:T.searchParams.get("search")??void 0});W=ft(e.sources.listRepositories(E.id,T.searchParams.get("search")??void 0),T,R,["fullName","id"])}else if(b.method==="GET"&&T.pathname==="/api/v1/source/refs"){if(!e.sources)throw new X("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:read",P.token.scope);let E=T.searchParams.get("connectionId")??"",N=e.sources.getConnection(E);if(!N||N.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Source connection was not found.",404);W=await Po(e.sources,{connectionId:E,repository:T.searchParams.get("repository")??"",repositoryId:T.searchParams.get("repositoryId")??void 0,type:T.searchParams.get("type")==="tags"?"tags":"branches",cursor:T.searchParams.get("cursor")??void 0,deployKeyId:T.searchParams.get("deployKeyId")??void 0})}else if(b.method==="POST"&&T.pathname==="/api/v1/application-detections"){t.authorize(P,"applications:manage",P.token.scope);let E=await ie();if(!Array.isArray(E.files)||E.files.length>1e4)throw new X("validation_error","files must contain at most 10,000 entries.",422);W={candidates:qn(E.files.map((N)=>({path:String(N.path??""),size:Number(N.size??0),content:typeof N.content==="string"?N.content.slice(0,262144):void 0}))),requestId:R}}else if(b.method==="POST"&&T.pathname==="/api/v1/application-plans"){t.authorize(P,"applications:manage",P.token.scope);let E=await ie();W={plan:Ft(E.draft,Array.isArray(E.suppliedSecretNames)?E.suppliedSecretNames.map(String):[]),requestId:R}}else if(b.method==="GET"&&T.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);let E=T.searchParams.get("projectId")??"";t.authorize(P,"applications:read",{type:"project",id:E}),W=ft(e.applications.drafts.list(E),T,R,["updatedAt","id"])}else if(b.method==="POST"&&T.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);let E=await ie(),N=String(E.projectId??E.draft?.projectId??"");t.authorize(P,"applications:manage",{type:"project",id:N});let V=e.controlPlane.getProject(N);if(!V||V.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Project was not found.",404);let H=e.applications.drafts.create({organizationId:V.organizationId,projectId:N,name:String(E.name??E.draft?.name??"Application draft"),draft:{...E.draft,projectId:N},step:E.step,suppliedSecretNames:Array.isArray(E.suppliedSecretNames)?E.suppliedSecretNames.map(String):[],actorId:P.actor.id});return f({draft:H,requestId:R},201,R,ue)}else if(b.method==="PATCH"&&T.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);let E=await ie(),N=e.applications.drafts.get(String(E.id??""));if(!N)throw new X("not_found","Application draft was not found.",404);t.authorize(P,"applications:manage",{type:"project",id:N.projectId}),W={draft:e.applications.drafts.update(N.id,Number(E.version),{draft:{...E.draft,projectId:N.projectId},step:E.step,suppliedSecretNames:Array.isArray(E.suppliedSecretNames)?E.suppliedSecretNames.map(String):void 0,actorId:P.actor.id}),requestId:R}}else if(b.method==="POST"&&T.pathname==="/api/v1/applications"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);let E=b.headers.get("idempotency-key")??"";if(!E)throw new X("idempotency_required","Idempotency-Key is required for application creation.",428);if(!/^[A-Za-z0-9._:-]{8,128}$/.test(E))throw new X("validation_error","Idempotency-Key must contain 8-128 safe characters.",422);let N=await ie(),V=e.applications.drafts.get(String(N.draftId??""));if(!V)throw new X("not_found","Application draft was not found.",404);t.authorize(P,"applications:manage",{type:"project",id:V.projectId});let H=gS("sha256").update(`POST
|
|
15
|
-
/api/v1/applications
|
|
16
|
-
${JSON.stringify(N)}`).digest("hex"),ke=e.identities.getIdempotency(P.token.id,E);if(ke){if(ke.requestHash!==H)throw new X("idempotency_conflict","Idempotency-Key was already used for another request.",409);let U=ke.operationId?e.controlPlane.getOperation(ke.operationId):void 0,ge=U?.resourceId?e.controlPlane.getResource(U.resourceId):void 0;if(!U||!ge)throw new X("idempotency_unavailable","The original application operation is no longer available.",409);return f({resource:ge,operation:t.operation(U),plan:Ft(V.input,V.suppliedSecretNames),idempotentReplay:!0,requestId:R},202,R,{...ue,"idempotent-replayed":"true"})}let Be=Eo({controlPlane:e.controlPlane,drafts:e.applications.drafts,draftId:V.id,expectedVersion:Number(N.version),confirmEnvironment:String(N.confirmEnvironment??""),actorId:P.actor.id});return e.identities.saveIdempotency({tokenId:P.token.id,key:E,requestHash:H,operationId:Be.operation.id,responseStatus:202,responseBody:{draftId:V.id}}),f({resource:Be.resource,operation:t.operation(Be.operation),plan:Be.plan,idempotentReplay:!1,requestId:R},202,R,ue)}else if(b.method==="GET"&&T.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:read",P.token.scope),W=ft(e.applications.registries.list(P.serviceAccount.organizationId),T,R,["createdAt","id"])}else if(b.method==="POST"&&T.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:manage",{type:"organization"});let E=await ie(),N=e.applications.registries.create({organizationId:P.serviceAccount.organizationId,provider:E.provider,name:String(E.name??"Container registry"),host:String(E.host??""),credential:E.token||E.password?{username:typeof E.username==="string"?E.username:void 0,password:typeof E.password==="string"?E.password:void 0,token:typeof E.token==="string"?E.token:void 0}:void 0,credentialExpiresAt:typeof E.credentialExpiresAt==="string"?E.credentialExpiresAt:void 0,actorId:P.actor.id});return f({registry:N,requestId:R},201,R,ue)}else if(b.method==="PATCH"&&T.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:manage",{type:"organization"});let E=await ie(),N=e.applications.registries.get(String(E.id??""));if(!N||N.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Registry connection was not found.",404);if(E.action==="test")W={registry:await e.applications.registries.test(N.id,{image:typeof E.image==="string"?E.image:void 0}),requestId:R};else if(E.action==="rotate")W={registry:e.applications.registries.rotate(N.id,{username:E.username,password:E.password,token:E.token},{expiresAt:E.expiresAt,actorId:P.actor.id}),requestId:R};else throw new X("validation_error","action must be test or rotate.",422)}else if(b.method==="DELETE"&&T.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new X("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:manage",{type:"organization"});let E=await ie(),N=e.applications.registries.get(String(E.id??""));if(!N||N.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Registry connection was not found.",404);W={registry:e.applications.registries.disconnect(N.id,P.actor.id),requestId:R}}else if(b.method==="POST"&&T.pathname==="/api/v1/application-artifacts"){if(!e.applications?.artifacts)throw new X("not_found","Application artifact storage is unavailable.",404);let E=b.headers.get("x-project-id")??"";t.authorize(P,"applications:manage",{type:"project",id:E});let N=e.controlPlane.getProject(E);if(!N||N.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Project was not found.",404);if(Number(b.headers.get("content-length")??0)>104857600)throw new X("payload_too_large","Artifact exceeds 100 MB.",413);let H=e.applications.artifacts.create({organizationId:N.organizationId,projectId:E,filename:b.headers.get("x-artifact-filename")??"application.zip",bytes:new Uint8Array(await b.arrayBuffer()),actorId:P.actor.id});return f({artifact:H,requestId:R},201,R,ue)}else if(b.method==="POST"&&T.pathname==="/api/v1/source/connections"){if(!e.sources)throw new X("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:manage",{type:"organization"});let E=await ie(),N=String(E.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(N))throw new X("validation_error","A supported provider is required.",422);let V=N==="github"&&(E.privateKey||E.appId)?{appId:typeof E.appId==="string"?E.appId:void 0,installationId:typeof E.installationId==="string"?E.installationId:void 0,privateKey:typeof E.privateKey==="string"?E.privateKey:void 0}:N!=="generic_ssh"&&E.token?{token:String(E.token),username:typeof E.username==="string"?E.username:void 0}:void 0,H,ke,Be;return e.controlPlane.database.transaction(()=>{if(H=e.sources.createConnection({organizationId:P.serviceAccount.organizationId,provider:N,name:String(E.name??N),host:String(E.host??""),owner:typeof E.owner==="string"?E.owner:void 0,authKind:E.authKind,credential:V,createdByActorId:P.actor.id}),typeof E.repositoryUrl==="string"&&typeof E.repositoryFullName==="string")ke=e.sources.upsertRepository({connectionId:H.id,providerRepositoryId:`manual:${E.repositoryFullName}`,fullName:E.repositoryFullName,cloneUrl:E.repositoryUrl,defaultBranch:String(E.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"api"}});if(N==="generic_ssh")Be=e.sources.createDeployKey({connectionId:H.id,name:String(E.deployKeyName??"Repository deploy key"),publicKey:String(E.publicKey??""),privateKey:String(E.deployPrivateKey??""),host:String(E.sshHost??""),hostKey:String(E.hostKey??""),actorId:P.actor.id})})(),f({connection:H,repository:ke,deployKey:Be,requestId:R},201,R,ue)}else if(b.method==="POST"&&T.pathname==="/api/v1/source/bindings"){if(!e.sources)throw new X("not_found","Source integrations are unavailable.",404);let E=await ie(),N=String(E.projectId??"");t.authorize(P,"sources:manage",{type:"project",id:N});let V=e.sources.getConnection(String(E.connectionId??""));if(!V||V.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Source connection was not found.",404);let H=e.sources.createBinding({projectId:N,environmentId:typeof E.environmentId==="string"?E.environmentId:void 0,resourceId:typeof E.resourceId==="string"?E.resourceId:void 0,connectionId:V.id,repositoryId:typeof E.repositoryId==="string"?E.repositoryId:void 0,repositoryFullName:String(E.repositoryFullName??""),defaultBranch:String(E.defaultBranch??"main"),branchRule:typeof E.branchRule==="string"?E.branchRule:void 0,tagRule:typeof E.tagRule==="string"?E.tagRule:void 0,monorepoRoot:String(E.monorepoRoot??"."),includePaths:Array.isArray(E.includePaths)?E.includePaths.map(String):[],excludePaths:Array.isArray(E.excludePaths)?E.excludePaths.map(String):[],submodules:E.submodules===!0,cloneDepth:typeof E.cloneDepth==="number"?E.cloneDepth:void 0,deployKeyId:typeof E.deployKeyId==="string"&&E.deployKeyId?E.deployKeyId:void 0,autoDeploy:E.autoDeploy!==!1,pullRequestPreviews:E.pullRequestPreviews!==!1,actorId:P.actor.id});return f({binding:H,requestId:R},201,R,ue)}else if(b.method==="POST"&&T.pathname==="/api/v1/source/webhooks"){if(!e.sources)throw new X("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:manage",{type:"organization"});let E=await ie(),N=e.sources.getConnection(String(E.connectionId??""));if(!N||N.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Source connection was not found.",404);let V=typeof E.baseUrl==="string"?E.baseUrl:void 0;if(!V)throw new X("validation_error","baseUrl is required.",422);let H=e.sources.createWebhook({connectionId:N.id,repositoryId:typeof E.repositoryId==="string"?E.repositoryId:void 0,repositoryFullName:String(E.repositoryFullName??""),events:Array.isArray(E.events)?E.events.map(String):void 0}),ke=Hn(V,H.webhook),Be=E.reconcile===!1?H.webhook:await $i(e.sources,H.webhook.id,V);return f({webhook:Be,endpoint:ke,endpointRevealOnce:!0,requestId:R},201,R,ue)}else if(b.method==="DELETE"&&T.pathname==="/api/v1/source/connections"){if(!e.sources)throw new X("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:manage",{type:"organization"});let E=await ie(),N=e.sources.getConnection(String(E.id??""));if(!N||N.organizationId!==P.serviceAccount.organizationId)throw new X("not_found","Source connection was not found.",404);let V=e.sources.listBindings({connectionId:N.id,status:"active"});if(E.preview===!0)return f({preview:!0,affectedBindings:V,requestId:R},200,R,ue);return f({...e.sources.disconnectConnection(N.id,P.actor.id),requestId:R},200,R,ue)}else if(b.method==="GET"&&(T.pathname==="/api/v1/events"||T.pathname==="/api/v1/events/stream")){let E=t.listEvents(P,T.searchParams.get("projectId")??void 0,Number(T.searchParams.get("after"))||void 0);if(T.pathname.endsWith("/stream")){let N=new TextEncoder,V=E.reduce((U,ge)=>Math.max(U,Number(ge.sequence)),Number(T.searchParams.get("after"))||0),H,ke=!1,Be=new ReadableStream({start(U){let ge=(ce)=>U.enqueue(N.encode(`id: ${ce.sequence}
|
|
17
|
-
event: ${ce.type}
|
|
18
|
-
data: ${JSON.stringify(ce)}
|
|
19
|
-
|
|
20
|
-
`));if(E.length)E.forEach(ge);else U.enqueue(N.encode(`: connected
|
|
21
|
-
|
|
22
|
-
`));H=setInterval(()=>{if(ke)return;let ce=e.identities.verifyToken(L,C);if(!ce){if(ke=!0,H)clearInterval(H);U.close();return}try{let ee=t.listEvents(ce,T.searchParams.get("projectId")??void 0,V);for(let ot of ee)ge(ot),V=Math.max(V,Number(ot.sequence));if(!ee.length)U.enqueue(N.encode(`: heartbeat ${Date.now()}
|
|
23
|
-
|
|
24
|
-
`))}catch{if(ke=!0,H)clearInterval(H);U.close()}},1000),b.signal.addEventListener("abort",()=>{if(ke=!0,H)clearInterval(H);try{U.close()}catch{}},{once:!0})},cancel(){if(ke=!0,H)clearInterval(H)}});return new Response(Be,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no","x-request-id":R,...ue}})}W=ft(E,T,R,["sequence","id"])}else if(b.method==="POST"&&T.pathname==="/api/v1/deployments"){let E=b.headers.get("idempotency-key")??"";if(!E)throw new X("idempotency_required","Idempotency-Key is required for deployment requests.",428);let N=await b.text();if(N.length>1048576)throw new X("payload_too_large","Request body exceeds 1 MB.",413);let V;try{V=JSON.parse(N)}catch{throw new X("invalid_json","Request body must be valid JSON.",400)}if(!V||typeof V.projectId!=="string"||typeof V.environmentId!=="string"||V.action!==void 0&&!["deploy","rollback"].includes(V.action))throw new X("validation_error","projectId, environmentId, and a valid action are required.",422);let H=t.createDeployment(P,V,E);return f({operation:H.operation,idempotentReplay:H.replay,requestId:R},202,R,{...ue,...H.replay?{"idempotent-replayed":"true"}:{}})}else{let E=await np({...c,authorization:t,now:a},P,{method:b.method,url:T,body:ie});if(E===void 0)throw new X("not_found","API resource was not found.",404);W=E}return f(W,200,R,ue)}catch(W){if(W instanceof X)return y(W.code,W.message,W.status,R,W.details,ue);if(T.pathname.startsWith("/api/v1/source/")||T.pathname.startsWith("/api/v1/application")||T.pathname.startsWith("/api/v1/compose-")||T.pathname==="/api/v1/registry-connections")return y("validation_error",W instanceof Error?W.message:"Integration request could not be completed.",422,R,void 0,ue);return y("internal_error","The API request could not be completed.",500,R,void 0,ue)}}}import{createCipheriv as bS,createDecipheriv as SS,createHash as up,randomBytes as mr}from"node:crypto";import{createHmac as hS,timingSafeEqual as yS}from"node:crypto";var Xa="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function No(e){let t=0,r=0,n="";for(let i of e){r=r<<8|i,t+=8;while(t>=5)n+=Xa[r>>>t-5&31],t-=5}if(t>0)n+=Xa[r<<5-t&31];return n}function ip(e){let t=e.toUpperCase().replace(/[^A-Z2-7]/g,""),r=0,n=0,i=[];for(let o of t){let s=Xa.indexOf(o);if(s<0)throw Error("Invalid base32 secret");if(n=n<<5|s,r+=5,r>=8)i.push(n>>>r-8&255),r-=8}return Buffer.from(i)}function op(e,t,r=6){let n=Buffer.alloc(8);n.writeBigUInt64BE(BigInt(t));let i=hS("sha1",ip(e)).update(n).digest(),o=i[i.length-1]&15,s=(i[o]&127)<<24|(i[o+1]&255)<<16|(i[o+2]&255)<<8|i[o+3]&255;return String(s%10**r).padStart(r,"0")}function $o(e,t,r=Date.now(),n=1){let i=t.replace(/[\s-]/g,"");if(!/^\d{6}$/.test(i))return;let o=Buffer.from(i),s=Math.floor(r/1000/30);for(let c=-n;c<=n;c++){if(s+c<0)continue;let u=Buffer.from(op(e,s+c));if(o.length===u.length&&yS(o,u))return s+c}return}function Za(e){let t=e.issuer?.trim()||"ts-cloud",r=`${t}:${e.account}`;return`otpauth://totp/${encodeURIComponent(r)}?secret=${encodeURIComponent(e.secret)}&issuer=${encodeURIComponent(t)}&algorithm=SHA1&digits=6&period=30`}var lp=1800000,Jr=43200000,pp=3600000,gp=300000,mp=600000;function At(e){return typeof e==="string"?e:void 0}function fp(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function vS(e){let t=e.trim();if(!/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(t))throw Error("Username must be 2-32 characters: letters, numbers, dot, dash or underscore");return t}function ec(e){if(e===void 0||!e.trim())return;let t=e.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid email address is required");return t}function wS(e){let t=e.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(t))throw Error("OIDC provider slug must be 2-48 lowercase letters, numbers or dashes");return t}function IS(e){let t=new URL(e.trim());if(t.search||t.hash||t.username||t.password)throw Error("OIDC issuer cannot contain credentials, a query, or a fragment");if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["127.0.0.1","::1","localhost"].includes(t.hostname)))throw Error("OIDC issuer must use HTTPS");return t.href.replace(/\/$/,"")}function CS(e){let t=[...new Set(e.map((r)=>r.trim().toLowerCase()).filter(Boolean))];if(t.length===0)throw Error("At least one explicit OIDC email domain is required");if(t.some((r)=>!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(r)||!r.includes(".")||r.includes("..")))throw Error("OIDC email domains must be explicit DNS names without wildcards");return t}function ES(e){let t=[...new Set(["openid",...e??["email","profile"]].map((r)=>r.trim()).filter(Boolean))];if(t.some((r)=>!/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(r)))throw Error("OIDC scopes contain unsupported characters");return t}function Ut(e){return up("sha256").update(e).digest("hex")}function Mi(e){return{id:String(e.id),actorId:String(e.actor_id),username:String(e.username),email:At(e.email),emailVerifiedAt:At(e.email_verified_at),passwordHash:String(e.password_hash),credentialVersion:Number(e.credential_version),requiresPasswordUpgrade:Number(e.requires_password_upgrade)===1,disabledAt:At(e.disabled_at),lastLoginAt:At(e.last_login_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function sp(e,t){let r=At(e.consumed_at),n=String(e.expires_at);return{id:String(e.id),identityId:String(e.identity_id),type:String(e.type),metadata:fp(e.metadata),expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":n<=t?"expired":"pending"}}function tc(e,t){let r=At(e.revoked_at),n=String(e.idle_expires_at),i=String(e.absolute_expires_at);return{id:String(e.id),identityId:String(e.identity_id),credentialVersion:Number(e.credential_version),authMethod:String(e.auth_method),userAgent:At(e.user_agent),networkHint:At(e.network_hint),createdAt:String(e.created_at),lastUsedAt:String(e.last_used_at),idleExpiresAt:n,absoluteExpiresAt:i,recentAuthAt:String(e.recent_auth_at),mfaAt:At(e.mfa_at),revokedAt:r,state:r?"revoked":n<=t||i<=t?"expired":"active"}}function ap(e){let t=At(e.verified_at),r=At(e.disabled_at);return{id:String(e.id),identityId:String(e.identity_id),type:"totp",label:String(e.label),createdAt:String(e.created_at),verifiedAt:t,disabledAt:r,state:r?"disabled":t?"active":"pending"}}function rc(e,t){let r=At(e.consumed_at),n=String(e.expires_at),i=Number(e.attempts);return{id:String(e.id),identityId:String(e.identity_id),purpose:String(e.purpose),attempts:i,expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":i>=5?"locked":n<=t?"expired":"pending"}}function cp(e){let t=fp(e);return Array.isArray(t)?t.filter((r)=>typeof r==="string"):[]}function Mo(e){return{id:String(e.id),organizationId:String(e.organization_id),slug:String(e.slug),name:String(e.name),issuer:String(e.issuer),clientId:String(e.client_id),hasClientSecret:typeof e.client_secret_ciphertext==="string"&&e.client_secret_ciphertext.length>0,scopes:cp(e.scopes),allowedDomains:cp(e.allowed_domains),defaultRole:String(e.default_role),enabled:Number(e.enabled)===1,enforceSso:Number(e.enforce_sso)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function dp(e,t){let r=At(e.consumed_at),n=String(e.expires_at);return{id:String(e.id),providerId:String(e.provider_id),redirectUri:String(e.redirect_uri),returnPath:String(e.return_path),expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":n<=t?"expired":"pending"}}function TS(e){return{id:String(e.id),providerId:String(e.provider_id),identityId:String(e.identity_id),subject:String(e.subject),email:String(e.email),linkedAt:String(e.linked_at),lastLoginAt:String(e.last_login_at)}}class Lo{controlPlane;nowFn;idFn;encryptionKey;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID()),this.encryptionKey=t.encryptionKey?up("sha256").update(t.encryptionKey).digest():void 0}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}encrypt(e){if(!this.encryptionKey)throw Error("Authentication encryption key is not configured");let t=mr(12),r=bS("aes-256-gcm",this.encryptionKey,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){if(!this.encryptionKey)throw Error("Authentication encryption key is not configured");let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted authentication value is unavailable");let o=SS("aes-256-gcm",this.encryptionKey,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}createIdentity(e){if(!this.controlPlane.getActor(e.actorId))throw Error("Authentication actor was not found");let t=vS(e.username),r=ec(e.email),n=e.id??this.idFn(),i=this.now();return this.run(`INSERT INTO auth_identities (id, actor_id, username, email, email_verified_at, password_hash, requires_password_upgrade, created_at, updated_at)
|
|
25
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.actorId,t,r??null,e.emailVerified&&r?i:null,e.passwordHash,e.requiresPasswordUpgrade?1:0,i,i]),this.getIdentity(n)}getIdentity(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE id = ?").get(e);return t?Mi(t):void 0}getIdentityByActor(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE actor_id = ?").get(e);return t?Mi(t):void 0}getIdentityByUsername(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE username = ? COLLATE NOCASE").get(e.trim());return t?Mi(t):void 0}getIdentityByEmail(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE email = ? COLLATE NOCASE").get(e.trim().toLowerCase());return t?Mi(t):void 0}listIdentities(){return this.controlPlane.database.query("SELECT * FROM auth_identities ORDER BY username COLLATE NOCASE").all().map(Mi)}updatePassword(e,t,r={}){if(!this.getIdentity(e))throw Error("Authentication identity was not found");let i=this.now();return this.controlPlane.transaction(()=>{if(this.run(`UPDATE auth_identities SET password_hash = ?, credential_version = credential_version + 1,
|
|
26
|
-
requires_password_upgrade = ?, updated_at = ? WHERE id = ?`,[t,r.requiresUpgrade?1:0,i,e]),r.revokeSessions!==!1)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[i,e])}),this.getIdentity(e)}rehashPassword(e,t){let r=this.now();this.run("UPDATE auth_identities SET password_hash = ?, requires_password_upgrade = 0, updated_at = ? WHERE id = ?",[t,r,e]);let n=this.getIdentity(e);if(!n)throw Error("Authentication identity was not found");return n}setVerifiedEmail(e,t){let r=ec(t),n=this.now();this.run("UPDATE auth_identities SET email = ?, email_verified_at = ?, updated_at = ? WHERE id = ?",[r,n,n,e]);let i=this.getIdentity(e);if(!i)throw Error("Authentication identity was not found");return i}recordLogin(e){let t=this.now();this.run("UPDATE auth_identities SET last_login_at = ?, updated_at = ? WHERE id = ?",[t,t,e]);let r=this.getIdentity(e);if(!r)throw Error("Authentication identity was not found");return r}setDisabled(e,t){let r=this.now();this.controlPlane.transaction(()=>{if(this.run("UPDATE auth_identities SET disabled_at = ?, credential_version = credential_version + 1, updated_at = ? WHERE id = ?",[t?r:null,r,e]),t)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[r,e])});let n=this.getIdentity(e);if(!n)throw Error("Authentication identity was not found");return n}createActionToken(e,t,r={}){if(!this.getIdentity(e))throw Error("Authentication identity was not found");let n=mr(32).toString("base64url"),i=this.idFn(),o=this.now(),s=new Date(this.nowFn().getTime()+Math.min(86400000,Math.max(60000,r.ttlMs??pp))).toISOString();return this.run("INSERT INTO auth_action_tokens (id, identity_id, type, token_hash, metadata, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i,e,t,Ut(n),JSON.stringify(r.metadata??{}),s,o]),{actionToken:this.getActionToken(i),token:n}}getActionToken(e){let t=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE id = ?").get(e);return t?sp(t,this.now()):void 0}consumeActionToken(e,t){return this.controlPlane.transaction(()=>{let r=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE token_hash = ? AND type = ?").get(Ut(e),t);if(!r)throw Error("Action token is invalid");let n=sp(r,this.now());if(n.state!=="pending")throw Error(`Action token is ${n.state}`);if(this.controlPlane.database.run("UPDATE auth_action_tokens SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ?",[this.now(),n.id,this.now()]).changes!==1)throw Error("Action token is no longer available");return this.getActionToken(n.id)})}revokeActionTokens(e,t){return this.controlPlane.database.run("UPDATE auth_action_tokens SET consumed_at = ? WHERE identity_id = ? AND type = ? AND consumed_at IS NULL",[this.now(),e,t]).changes}createSession(e){let t=this.getIdentity(e.identityId);if(!t||t.disabledAt)throw Error("Authentication identity is unavailable");let r=this.idFn(),n=mr(32).toString("base64url"),i=`v2.${r}.${n}`,o=this.now(),s=Math.min(86400000,Math.max(60000,e.idleTtlMs??lp)),c=Math.min(2592000000,Math.max(s,e.absoluteTtlMs??Jr));return this.run(`INSERT INTO auth_sessions (id, identity_id, token_hash, credential_version, auth_method, user_agent, network_hint,
|
|
27
|
-
created_at, last_used_at, idle_expires_at, absolute_expires_at, recent_auth_at, mfa_at)
|
|
28
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,t.id,Ut(i),t.credentialVersion,e.authMethod??"local",e.userAgent?.slice(0,256)??null,e.networkHint?.slice(0,128)??null,o,o,new Date(this.nowFn().getTime()+s).toISOString(),new Date(this.nowFn().getTime()+c).toISOString(),e.recentAuthAt??o,e.mfaAt??null]),{session:this.getSession(r),token:i}}getSession(e){let t=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ?").get(e);return t?tc(t,this.now()):void 0}verifySessionToken(e){let t=/^v2\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(e);if(!t)return;let r=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ? AND token_hash = ?").get(t[1],Ut(e));if(!r)return;let n=tc(r,this.now()),i=this.getIdentity(n.identityId);if(!i||i.disabledAt||n.state!=="active"||n.credentialVersion!==i.credentialVersion)return;let o=this.now(),s=new Date(r.idle_expires_at).getTime()-new Date(r.last_used_at).getTime();return this.run("UPDATE auth_sessions SET last_used_at = ?, idle_expires_at = ? WHERE id = ?",[o,new Date(Math.min(this.nowFn().getTime()+s,new Date(n.absoluteExpiresAt).getTime())).toISOString(),n.id]),{identity:i,session:this.getSession(n.id)}}listSessions(e,t={}){let r=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE identity_id = ? ORDER BY last_used_at DESC").all(e).map((n)=>tc(n,this.now()));return t.includeInactive?r:r.filter((n)=>n.state==="active")}revokeSession(e,t){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE id = ? AND identity_id = ? AND revoked_at IS NULL",[this.now(),t,e]).changes===1}revokeOtherSessions(e,t){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND id != ? AND revoked_at IS NULL",[this.now(),e,t]).changes}getMfaFactor(e){let t=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(e);return t?ap(t):void 0}beginTotpEnrollment(e,t={}){let r=this.getIdentity(e);if(!r)throw Error("Authentication identity was not found");let n=this.getMfaFactor(e);if(n?.state==="active")throw Error("MFA is already enabled");let i=No(mr(20)),o=t.label?.trim().slice(0,80)||r.email||r.username,s=n?.id??this.idFn(),c=this.now();return this.controlPlane.transaction(()=>{if(n)this.run("UPDATE auth_mfa_factors SET label = ?, secret_ciphertext = ?, created_at = ?, verified_at = NULL, disabled_at = NULL WHERE id = ?",[o,this.encrypt(i),c,s]);else this.run("INSERT INTO auth_mfa_factors (id, identity_id, label, secret_ciphertext, created_at) VALUES (?, ?, ?, ?, ?)",[s,e,o,this.encrypt(i),c]);this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e])}),{factor:this.getMfaFactor(e),secret:i,uri:Za({secret:i,account:o,issuer:t.issuer})}}verifyTotpEnrollment(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(e);if(!r||ap(r).state!=="pending")throw Error("MFA enrollment is not pending");let n=$o(this.decrypt(String(r.secret_ciphertext)),t,this.nowFn().getTime());if(n===void 0)throw Error("Authenticator code is invalid");let i=Array.from({length:10},()=>{let s=No(mr(8)).slice(0,12);return`${s.slice(0,4)}-${s.slice(4,8)}-${s.slice(8)}`}),o=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET verified_at = ?, disabled_at = NULL, last_used_step = ? WHERE identity_id = ?",[o,n,e]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e]);for(let s of i)this.run("INSERT INTO auth_recovery_codes (id, identity_id, code_hash, created_at) VALUES (?, ?, ?, ?)",[this.idFn(),e,Ut(`${e}:${s.replace(/-/g,"").toUpperCase()}`),o])}),{factor:this.getMfaFactor(e),recoveryCodes:i}}verifyMfaCode(e,t,r={}){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ? AND verified_at IS NOT NULL AND disabled_at IS NULL").get(e);if(!n)return{valid:!1};let i=$o(this.decrypt(String(n.secret_ciphertext)),t,this.nowFn().getTime());if(i!==void 0){if(this.controlPlane.database.run("UPDATE auth_mfa_factors SET last_used_step = ? WHERE identity_id = ? AND (last_used_step IS NULL OR last_used_step < ?)",[i,e,i]).changes===1)return{valid:!0,method:"totp"}}let o=t.replace(/[-\s]/g,"").toUpperCase();if(!/^[A-Z2-7]{12}$/.test(o))return{valid:!1};let s=Ut(`${e}:${o}`),c=this.controlPlane.database.query("SELECT * FROM auth_recovery_codes WHERE identity_id = ? AND code_hash = ? AND consumed_at IS NULL").get(e,s);if(!c)return{valid:!1};if(r.consumeRecovery!==!1){if(this.controlPlane.database.run("UPDATE auth_recovery_codes SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL",[this.now(),String(c.id)]).changes!==1)return{valid:!1}}return{valid:!0,method:"recovery"}}remainingRecoveryCodes(e){return Number(this.controlPlane.database.query("SELECT COUNT(*) AS count FROM auth_recovery_codes WHERE identity_id = ? AND consumed_at IS NULL").get(e)?.count??0)}disableMfa(e){let t=this.now();this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET disabled_at = ? WHERE identity_id = ? AND disabled_at IS NULL",[t,e]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e]),this.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE identity_id = ? AND consumed_at IS NULL",[t,e])})}createMfaChallenge(e,t){if(this.getMfaFactor(e)?.state!=="active")throw Error("MFA is not enabled");let r=mr(32).toString("base64url"),n=this.idFn(),i=this.now(),o=new Date(this.nowFn().getTime()+gp).toISOString();return this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE identity_id = ? AND purpose = ? AND consumed_at IS NULL",[i,e,t]),this.run("INSERT INTO auth_mfa_challenges (id, identity_id, purpose, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?)",[n,e,t,Ut(r),o,i])}),{challenge:this.getMfaChallenge(n),token:r}}getMfaChallenge(e){let t=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE id = ?").get(e);return t?rc(t,this.now()):void 0}inspectMfaChallengeToken(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Ut(e),t);return r?rc(r,this.now()):void 0}completeMfaChallenge(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Ut(e),r);if(!n)throw Error("MFA challenge is invalid");let i=rc(n,this.now());if(i.state!=="pending")throw Error(`MFA challenge is ${i.state}`);let o=this.verifyMfaCode(i.identityId,t);if(!o.valid||!o.method)throw this.run("UPDATE auth_mfa_challenges SET attempts = attempts + 1 WHERE id = ?",[i.id]),Error("Authenticator or recovery code is invalid");if(this.controlPlane.database.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND attempts < 5 AND expires_at > ?",[this.now(),i.id,this.now()]).changes!==1)throw Error("MFA challenge is no longer available");return{identity:this.getIdentity(i.identityId),challenge:this.getMfaChallenge(i.id),method:o.method}}markSessionStepUp(e,t=!1){let r=this.now();this.run("UPDATE auth_sessions SET recent_auth_at = ?, mfa_at = CASE WHEN ? = 1 THEN ? ELSE mfa_at END WHERE id = ? AND revoked_at IS NULL",[r,t?1:0,r,e]);let n=this.getSession(e);if(!n)throw Error("Authentication session was not found");return n}isRecentlyAuthenticated(e,t=600000){return this.nowFn().getTime()-new Date(e.recentAuthAt).getTime()<=t}upsertOidcProvider(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("OIDC provider organization was not found");let t=wS(e.slug),r=e.name.trim().slice(0,80);if(!r)throw Error("OIDC provider name is required");let n=IS(e.issuer),i=e.clientId.trim();if(!i||i.length>512)throw Error("OIDC client ID is required");let o=ES(e.scopes),s=CS(e.allowedDomains),c=e.id?this.getOidcProvider(e.id):this.getOidcProviderBySlug(t),u=this.now();if(c){if(c.organizationId!==e.organizationId)throw Error("OIDC provider belongs to another organization");return this.run(`UPDATE auth_oidc_providers SET slug = ?, name = ?, issuer = ?, client_id = ?,
|
|
29
|
-
client_secret_ciphertext = COALESCE(?, client_secret_ciphertext), scopes = ?, allowed_domains = ?,
|
|
30
|
-
default_role = ?, enabled = ?, enforce_sso = ?, updated_at = ? WHERE id = ?`,[t,r,n,i,e.clientSecret?this.encrypt(e.clientSecret):null,JSON.stringify(o),JSON.stringify(s),e.defaultRole??c.defaultRole,e.enabled??c.enabled?1:0,e.enforceSso??c.enforceSso?1:0,u,c.id]),this.getOidcProvider(c.id)}if(!e.clientSecret)throw Error("OIDC client secret is required for a new provider");let a=e.id??this.idFn();return this.run(`INSERT INTO auth_oidc_providers (id, organization_id, slug, name, issuer, client_id,
|
|
31
|
-
client_secret_ciphertext, scopes, allowed_domains, default_role, enabled, enforce_sso, created_at, updated_at)
|
|
32
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,t,r,n,i,this.encrypt(e.clientSecret),JSON.stringify(o),JSON.stringify(s),e.defaultRole??"viewer",e.enabled===!1?0:1,e.enforceSso?1:0,u,u]),this.getOidcProvider(a)}getOidcProvider(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(e);return t?Mo(t):void 0}getOidcProviderBySlug(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE slug = ? COLLATE NOCASE").get(e.trim());return t?Mo(t):void 0}listOidcProviders(e,t={}){return(e?this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(e):this.controlPlane.database.query("SELECT * FROM auth_oidc_providers ORDER BY name COLLATE NOCASE").all()).map(Mo).filter((n)=>t.includeDisabled||n.enabled)}setOidcProviderEnabled(e,t){let r=this.now();if(this.controlPlane.database.run("UPDATE auth_oidc_providers SET enabled = ?, enforce_sso = CASE WHEN ? = 0 THEN 0 ELSE enforce_sso END, updated_at = ? WHERE id = ?",[t?1:0,t?1:0,r,e]).changes!==1)throw Error("OIDC provider was not found");if(!t)this.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE provider_id = ? AND consumed_at IS NULL",[r,e]);return this.getOidcProvider(e)}getOidcProviderCredentials(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(e);if(!t||typeof t.client_secret_ciphertext!=="string")throw Error("OIDC provider credentials are unavailable");return{provider:Mo(t),clientSecret:this.decrypt(t.client_secret_ciphertext)}}beginOidcTransaction(e,t,r){if(!this.getOidcProvider(e)?.enabled)throw Error("OIDC provider is unavailable");let i=this.idFn(),o=mr(32).toString("base64url"),s=mr(32).toString("base64url"),c=mr(64).toString("base64url"),u=this.now(),a=new Date(this.nowFn().getTime()+mp).toISOString();return this.run(`INSERT INTO auth_oidc_transactions (id, provider_id, state_hash, nonce_ciphertext, verifier_ciphertext,
|
|
33
|
-
redirect_uri, return_path, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e,Ut(o),this.encrypt(s),this.encrypt(c),t,r,a,u]),{transaction:this.getOidcTransaction(i),state:o,nonce:s,verifier:c}}getOidcTransaction(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE id = ?").get(e);return t?dp(t,this.now()):void 0}consumeOidcTransaction(e,t){return this.controlPlane.transaction(()=>{let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE provider_id = ? AND state_hash = ?").get(e,Ut(t));if(!r)throw Error("OIDC transaction is invalid");let n=dp(r,this.now());if(n.state!=="pending")throw Error(`OIDC transaction is ${n.state}`);if(this.controlPlane.database.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ?",[this.now(),n.id,this.now()]).changes!==1)throw Error("OIDC transaction is no longer available");return{transaction:this.getOidcTransaction(n.id),nonce:this.decrypt(String(r.nonce_ciphertext)),verifier:this.decrypt(String(r.verifier_ciphertext))}})}getOidcSubject(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_subjects WHERE provider_id = ? AND subject = ?").get(e,t);return r?TS(r):void 0}linkOidcSubject(e,t,r,n){let i=this.getOidcProvider(e),o=this.getIdentity(t);if(!i||!o)throw Error("OIDC provider or identity was not found");let s=ec(n);if(!r.trim()||r.length>512)throw Error("OIDC subject is invalid");let c=this.getOidcSubject(e,r);if(c&&c.identityId!==t)throw Error("OIDC subject is already linked to another identity");let u=this.now();if(c)return this.run("UPDATE auth_oidc_subjects SET email = ?, last_login_at = ? WHERE id = ?",[s,u,c.id]),this.getOidcSubject(e,r);let a=this.idFn();return this.run("INSERT INTO auth_oidc_subjects (id, provider_id, identity_id, subject, email, linked_at, last_login_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,e,t,r,s,u,u]),this.getOidcSubject(e,r)}purgeExpired(){let e=this.now(),t=this.controlPlane.database.run("DELETE FROM auth_action_tokens WHERE expires_at < ? OR consumed_at IS NOT NULL",[e]).changes,r=this.controlPlane.database.run("DELETE FROM auth_sessions WHERE revoked_at IS NOT NULL OR idle_expires_at < ? OR absolute_expires_at < ?",[e,e]).changes;return this.controlPlane.database.run("DELETE FROM auth_mfa_challenges WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),this.controlPlane.database.run("DELETE FROM auth_oidc_transactions WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),{actionTokens:t,sessions:r}}}async function Li(e,t){let r=e.notifications?.email?.from;if(!r)return!1;try{let{EmailClient:n}=await import("./chunk-43xj5cny.js");return await new n({region:e.project.region,defaultFrom:r}).send(t),!0}catch{return!1}}import{randomBytes as AS}from"node:crypto";import{chmodSync as kS,existsSync as RS,mkdirSync as PS,readFileSync as xS,writeFileSync as DS}from"node:fs";import{dirname as OS}from"node:path";function Wr(e){let t=process.env.TS_CLOUD_AUTH_ENCRYPTION_KEY?.trim();if(t)return t;let r=at(e,"auth-encryption-key");try{if(RS(r)){let i=xS(r,"utf8").trim();if(i)return i}}catch{}let n=AS(32).toString("base64url");try{PS(OS(r),{recursive:!0,mode:448}),DS(r,`${n}
|
|
34
|
-
`,{mode:384}),kS(r,384)}catch{}return n}import{constants as hp,createHash as nc,createPublicKey as _S,createVerify as NS,timingSafeEqual as $S}from"node:crypto";var bp=new Set(["RS256","PS256","ES256"]),yp=60;function jo(e,t){let r=new URL(e),n=["127.0.0.1","::1","localhost"].includes(r.hostname);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n))throw Error(`${t} must use HTTPS`);if(r.username||r.password||r.hash)throw Error(`${t} contains unsupported URL components`);return r}function ic(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`${t} is invalid`);return e}async function oc(e,t){if(!e.ok)throw Error(`${t} failed with HTTP ${e.status}`);if(!(e.headers.get("content-type")??"").toLowerCase().includes("application/json"))throw Error(`${t} returned an unsupported content type`);if(Number(e.headers.get("content-length")??0)>1048576)throw Error(`${t} response is too large`);let i=await e.text();if(i.length>1048576)throw Error(`${t} response is too large`);try{return ic(JSON.parse(i),t)}catch(o){if(o instanceof Error&&o.message===`${t} is invalid`)throw o;throw Error(`${t} returned invalid JSON`)}}function MS(e,t){let r=nc("sha256").update(e).digest(),n=nc("sha256").update(t).digest();return $S(r,n)}function Sp(e){if(!e)return"/";let t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||/[\r\n]/.test(t))return"/";try{let r=new URL(t,"https://local.invalid");return r.origin==="https://local.invalid"?`${r.pathname}${r.search}${r.hash}`:"/"}catch{return"/"}}async function sc(e,t=fetch){let r=jo(e.issuer,"OIDC issuer"),n=new URL(`${r.pathname.replace(/\/$/,"")}/.well-known/openid-configuration`,r.origin),i=await oc(await t(n,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC discovery");if(i.issuer!==e.issuer)throw Error("OIDC discovery issuer does not match the configured issuer");for(let s of["authorization_endpoint","token_endpoint","jwks_uri"]){if(typeof i[s]!=="string")throw Error(`OIDC discovery is missing ${s}`);jo(i[s],`OIDC ${s}`)}if(Array.isArray(i.response_types_supported)&&!i.response_types_supported.includes("code"))throw Error("OIDC provider does not support authorization code flow");if(Array.isArray(i.code_challenge_methods_supported)&&!i.code_challenge_methods_supported.includes("S256"))throw Error("OIDC provider does not support PKCE S256");let o=Array.isArray(i.id_token_signing_alg_values_supported)?i.id_token_signing_alg_values_supported.filter((s)=>typeof s==="string"):[];if(o.length>0&&!o.some((s)=>bp.has(s)))throw Error("OIDC provider does not offer a supported ID-token signing algorithm");return i}async function ac(e,t,r,n,i=fetch){let o=e.getOidcProviderBySlug(t);if(!o?.enabled)throw Error("OIDC provider is unavailable");let s=jo(r,"Application origin").origin,c=await sc(o,i),u=`${s}/auth/oidc/${encodeURIComponent(o.slug)}/callback`,a=e.beginOidcTransaction(o.id,u,Sp(n)),p=new URL(c.authorization_endpoint);return p.searchParams.set("response_type","code"),p.searchParams.set("client_id",o.clientId),p.searchParams.set("redirect_uri",u),p.searchParams.set("scope",o.scopes.join(" ")),p.searchParams.set("state",a.state),p.searchParams.set("nonce",a.nonce),p.searchParams.set("code_challenge",nc("sha256").update(a.verifier).digest("base64url")),p.searchParams.set("code_challenge_method","S256"),{authorizationUrl:p.href,expiresAt:a.transaction.expiresAt}}function LS(e){if(e.length>32768)throw Error("OIDC ID token is too large");let t=e.split(".");if(t.length!==3||t.some((r)=>!r))throw Error("OIDC ID token is malformed");try{return{header:ic(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")),"OIDC ID-token header"),claims:ic(JSON.parse(Buffer.from(t[1],"base64url").toString("utf8")),"OIDC ID-token claims"),signingInput:`${t[0]}.${t[1]}`,signature:Buffer.from(t[2],"base64url")}}catch(r){if(r instanceof Error&&r.message.startsWith("OIDC"))throw r;throw Error("OIDC ID token is malformed")}}async function BS(e,t,r){let n=LS(e),i=typeof n.header.alg==="string"?n.header.alg:"",o=typeof n.header.kid==="string"?n.header.kid:"";if(!bp.has(i)||!o)throw Error("OIDC ID token uses an unsupported signing key");if(t.id_token_signing_alg_values_supported&&!t.id_token_signing_alg_values_supported.includes(i))throw Error("OIDC ID-token algorithm was not advertised by the provider");let s=await oc(await r(t.jwks_uri,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC signing-key request");if(!Array.isArray(s.keys))throw Error("OIDC signing-key response is invalid");let c=s.keys.find((f)=>{if(!f||typeof f!=="object"||Array.isArray(f))return!1;let y=f;return y.kid===o&&(!y.alg||y.alg===i)&&(!y.use||y.use==="sig")});if(!c)throw Error("OIDC ID-token signing key was not found");let u=_S({key:c,format:"jwk"}),a=NS("SHA256").update(n.signingInput).end();if(!(i==="PS256"?a.verify({key:u,padding:hp.RSA_PKCS1_PSS_PADDING,saltLength:32},n.signature):i==="ES256"?a.verify({key:u,dsaEncoding:"ieee-p1363"},n.signature):a.verify(u,n.signature)))throw Error("OIDC ID-token signature is invalid");return n.claims}function jS(e,t,r,n){if(e.iss!==t.issuer)throw Error("OIDC ID-token issuer is invalid");let i=typeof e.aud==="string"?[e.aud]:Array.isArray(e.aud)?e.aud.filter((u)=>typeof u==="string"):[];if(!i.includes(t.clientId))throw Error("OIDC ID-token audience is invalid");if((i.length>1||e.azp!==void 0)&&e.azp!==t.clientId)throw Error("OIDC ID-token authorized party is invalid");let o=Math.floor(n.getTime()/1000);if(typeof e.exp!=="number"||e.exp<o-yp)throw Error("OIDC ID token is expired");if(typeof e.iat!=="number"||e.iat>o+yp)throw Error("OIDC ID-token issued-at time is invalid");if(typeof e.nonce!=="string"||!MS(e.nonce,r))throw Error("OIDC ID-token nonce is invalid");if(typeof e.sub!=="string"||!e.sub||e.sub.length>512)throw Error("OIDC ID-token subject is invalid");if(e.email_verified!==!0||typeof e.email!=="string")throw Error("OIDC provider did not return a verified email address");let s=e.email.trim().toLowerCase();if(s.length>254||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))throw Error("OIDC provider returned an invalid email address");let c=s.split("@")[1];if(!c||!t.allowedDomains.includes(c))throw Error("OIDC email domain is not allowed for this organization");return{provider:t,subject:e.sub,email:s,name:typeof e.name==="string"?e.name.slice(0,120):void 0,claims:e}}async function cc(e,t,r=fetch){let n=e.getOidcProviderBySlug(t.providerSlug);if(!n?.enabled)throw Error("OIDC provider is unavailable");if(!t.state||t.state.length>512||!t.code||t.code.length>4096)throw Error("OIDC callback is incomplete");let i=jo(t.origin,"Application origin").origin,o=e.consumeOidcTransaction(n.id,t.state),s=`${i}/auth/oidc/${encodeURIComponent(n.slug)}/callback`;if(o.transaction.redirectUri!==s)throw Error("OIDC callback redirect URI does not match the original request");let{clientSecret:c}=e.getOidcProviderCredentials(n.id),u=await sc(n,r),a=new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:o.transaction.redirectUri,code_verifier:o.verifier}),p={accept:"application/json","content-type":"application/x-www-form-urlencoded"},f=u.token_endpoint_auth_methods_supported??["client_secret_basic"];if(f.includes("client_secret_basic")){let C=(R)=>new URLSearchParams({value:R}).toString().slice(6),T=`${C(n.clientId)}:${C(c)}`;p.authorization=`Basic ${Buffer.from(T).toString("base64")}`}else if(f.includes("client_secret_post"))a.set("client_id",n.clientId),a.set("client_secret",c);else throw Error("OIDC provider does not support a configured client authentication method");let y=await oc(await r(u.token_endpoint,{method:"POST",headers:p,body:a,redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC token exchange");if(typeof y.id_token!=="string")throw Error("OIDC token response did not include an ID token");let b=await BS(y.id_token,u,r);return{identity:jS(b,n,o.nonce,t.now??new Date),returnPath:o.transaction.returnPath}}import{createHash as FS,randomBytes as US}from"node:crypto";var wp=new Set(Fo),Ip=7776000000,Cp=31536000000,Ep=86400000;function fr(e){return typeof e==="string"?e:void 0}function vp(e){return FS("sha256").update(e).digest("hex")}function zS(e){try{let t=JSON.parse(String(e));return Array.isArray(t)?t.filter((r)=>typeof r==="string"&&wp.has(r)):[]}catch{return[]}}function VS(e){let t=String(e.scope_type);return t==="organization"?{type:t}:{type:t,id:String(e.scope_id)}}function dc(e){let t=fr(e.disabled_at);return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),slug:String(e.slug),name:String(e.name),description:fr(e.description),createdByActorId:fr(e.created_by_actor_id),disabledAt:t,createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:t?"disabled":"active"}}function uc(e,t){let r=fr(e.revoked_at),n=String(e.expires_at);return{id:String(e.id),serviceAccountId:String(e.service_account_id),name:String(e.name),prefix:String(e.token_prefix),capabilities:zS(e.capabilities),scope:VS(e),expiresAt:n,lastUsedAt:fr(e.last_used_at),lastNetworkHint:fr(e.last_network_hint),revokedAt:r,rotatedFromTokenId:fr(e.rotated_from_token_id),createdByActorId:fr(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:r?"revoked":n<=t?"expired":"active"}}function qS(e){let t={};try{t=JSON.parse(String(e.response_body))}catch{}return{id:String(e.id),tokenId:String(e.token_id),key:String(e.idempotency_key),requestHash:String(e.request_hash),operationId:fr(e.operation_id),responseStatus:Number(e.response_status),responseBody:t,expiresAt:String(e.expires_at),createdAt:String(e.created_at)}}class Uo{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}createServiceAccount(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("Service-account organization was not found");let t=e.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(t))throw Error("Service-account slug must be 2-48 lowercase letters, numbers or dashes");let r=e.name.trim().slice(0,100);if(!r)throw Error("Service-account name is required");let n=this.controlPlane.createActor({kind:"service_account",externalId:`service-account:${e.organizationId}:${t}`,displayName:r,metadata:{source:"api",serviceAccountSlug:t}}),i=this.idFn(),o=this.now();this.run(`INSERT INTO service_accounts (id, organization_id, actor_id, slug, name, description, created_by_actor_id, created_at, updated_at)
|
|
35
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e.organizationId,n.id,t,r,e.description?.trim().slice(0,500)||null,e.createdByActorId??null,o,o]);let s=this.controlPlane.createMembership({organizationId:e.organizationId,actorId:n.id,roleTemplate:e.roleTemplate,scope:e.scope,source:"manual",performedByActorId:e.createdByActorId}),c=e.scope??{type:"organization"};return this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.createdByActorId,type:"api.service_account.created",payload:{serviceAccountId:i,roleTemplate:e.roleTemplate,scope:{type:c.type,id:c.id??null}}}),{serviceAccount:this.getServiceAccount(i),membership:s}}getServiceAccount(e){let t=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE id = ?").get(e);return t?dc(t):void 0}getServiceAccountBySlug(e,t){let r=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? AND slug = ? COLLATE NOCASE").get(e,t.trim());return r?dc(r):void 0}listServiceAccounts(e,t={}){return this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(e).map(dc).filter((r)=>t.includeDisabled||r.state==="active")}disableServiceAccount(e,t){let r=this.getServiceAccount(e);if(!r)throw Error("Service account was not found");let n=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE service_accounts SET disabled_at = ?, updated_at = ? WHERE id = ?",[n,n,e]),this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE service_account_id = ? AND revoked_at IS NULL",[n,n,e]);let i=this.controlPlane.getMembershipForActor(r.organizationId,r.actorId);if(i?.status==="active")this.controlPlane.revokeMembership(i.id)}),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"api.service_account.disabled",payload:{serviceAccountId:e}}),this.getServiceAccount(e)}createToken(e){let t=this.getServiceAccount(e.serviceAccountId);if(!t||t.state!=="active")throw Error("Service account is unavailable");let r=this.controlPlane.getMembershipForActor(t.organizationId,t.actorId);if(!r||r.status!=="active")throw Error("Service-account membership is unavailable");let n=[...new Set(e.capabilities)];if(n.length===0||n.some((y)=>!wp.has(y)))throw Error("API token requires valid explicit capabilities");let i=e.scope??r.scope,o=this.controlPlane.resolveAuthorizationTarget(t.organizationId,i);if(!o)throw Error("API token scope was not found in this organization");for(let y of n)if(!zt({membership:r,grants:this.controlPlane.listGrants(r.id),capability:y,target:o}).allowed)throw Error(`Service-account membership does not grant ${y} at the token scope`);let s=e.expiresAt?new Date(e.expiresAt):new Date(this.nowFn().getTime()+Ip);if(!Number.isFinite(s.getTime())||s.getTime()<=this.nowFn().getTime()+60000||s.getTime()>this.nowFn().getTime()+Cp)throw Error("API token expiry must be between one minute and one year from now");let c=this.idFn(),u=US(32).toString("base64url"),a=`tsc_v1.${c}.${u}`,p=`tsc_v1.${c.slice(0,8)}`,f=this.now();return this.run(`INSERT INTO api_tokens (id, service_account_id, name, token_hash, token_prefix, capabilities, scope_type, scope_id,
|
|
36
|
-
expires_at, rotated_from_token_id, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[c,t.id,e.name.trim().slice(0,100)||"API token",vp(a),p,JSON.stringify(n.sort()),i.type,i.type==="organization"?null:i.id??null,s.toISOString(),e.rotatedFromTokenId??null,e.createdByActorId??null,f,f]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:e.createdByActorId,type:"api.token.created",payload:{serviceAccountId:t.id,tokenId:c,prefix:p,capabilities:n,scope:{type:i.type,id:i.id??null},expiresAt:s.toISOString(),rotatedFromTokenId:e.rotatedFromTokenId??null}}),{token:this.getToken(c),secret:a}}getToken(e){let t=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ?").get(e);return t?uc(t,this.now()):void 0}listTokens(e,t={}){return this.controlPlane.database.query("SELECT * FROM api_tokens WHERE service_account_id = ? ORDER BY created_at DESC").all(e).map((r)=>uc(r,this.now())).filter((r)=>t.includeInactive||r.state==="active")}verifyToken(e,t){let r=/^tsc_v1\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(e);if(!r)return;let n=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ? AND token_hash = ?").get(r[1],vp(e));if(!n)return;let i=uc(n,this.now()),o=this.getServiceAccount(i.serviceAccountId);if(!o||o.state!=="active"||i.state!=="active")return;let s=this.controlPlane.getActor(o.actorId),c=this.controlPlane.getMembershipForActor(o.organizationId,o.actorId);if(!s||s.disabledAt||!c||c.status!=="active")return;let u=this.now(),a=!i.lastUsedAt||this.nowFn().getTime()-new Date(i.lastUsedAt).getTime()>=3600000;if(this.run("UPDATE api_tokens SET last_used_at = ?, last_network_hint = ?, updated_at = ? WHERE id = ?",[u,t?.slice(0,128)??null,u,i.id]),a)this.controlPlane.appendEvent({organizationId:o.organizationId,actorId:s.id,type:"api.token.used",payload:{serviceAccountId:o.id,tokenId:i.id,prefix:i.prefix}});return{serviceAccount:o,token:this.getToken(i.id),actor:s,membership:c}}rotateToken(e,t){let r=this.getToken(e);if(!r||r.state!=="active")throw Error("Active API token was not found");let n=this.createToken({serviceAccountId:r.serviceAccountId,name:`${r.name} (rotated)`,capabilities:r.capabilities,scope:r.scope,expiresAt:r.expiresAt,createdByActorId:t,rotatedFromTokenId:r.id}),i=this.getServiceAccount(r.serviceAccountId);return this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:t,type:"api.token.rotated",payload:{serviceAccountId:r.serviceAccountId,previousTokenId:r.id,tokenId:n.token.id}}),n}revokeToken(e,t){let r=this.getToken(e);if(!r)throw Error("API token was not found");if(r.state==="active"){let n=this.now();this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE id = ?",[n,n,e]);let i=this.getServiceAccount(r.serviceAccountId);this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:t,type:"api.token.revoked",payload:{serviceAccountId:r.serviceAccountId,tokenId:e}})}return this.getToken(e)}getIdempotency(e,t){let r=this.controlPlane.database.query("SELECT * FROM api_idempotency_records WHERE token_id = ? AND idempotency_key = ? AND expires_at > ?").get(e,t,this.now());return r?qS(r):void 0}saveIdempotency(e){if(!/^[A-Za-z0-9._:-]{8,128}$/.test(e.key))throw Error("Idempotency-Key must contain 8-128 safe characters");let t=this.getIdempotency(e.tokenId,e.key);if(t){if(t.requestHash!==e.requestHash)throw Error("Idempotency-Key was already used for a different request");return t}let r=this.idFn(),n=this.now(),i=new Date(this.nowFn().getTime()+Ep).toISOString();return this.run(`INSERT INTO api_idempotency_records (id, token_id, idempotency_key, request_hash, operation_id, response_status, response_body, expires_at, created_at)
|
|
37
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.tokenId,e.key,e.requestHash,e.operationId??null,e.responseStatus,JSON.stringify(e.responseBody),i,n]),this.getIdempotency(e.tokenId,e.key)}purgeExpired(){let e=this.now(),t=this.controlPlane.database.run("DELETE FROM api_tokens WHERE (expires_at < ? OR revoked_at IS NOT NULL) AND created_at < ?",[e,new Date(this.nowFn().getTime()-2592000000).toISOString()]).changes,r=this.controlPlane.database.run("DELETE FROM api_idempotency_records WHERE expires_at < ?",[e]).changes;return{tokens:t,idempotency:r}}}class Bi{region;client;constructor(e="us-east-1",t=new pe){this.region=e;this.client=t}request(e,t){return this.client.request({service:"backup",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`CryoControllerFrontendService.${e}`},body:JSON.stringify(t)})}startBackupJob(e){return this.request("StartBackupJob",e)}describeBackupJob(e){return this.request("DescribeBackupJob",{BackupJobId:e})}startRestoreJob(e){return this.request("StartRestoreJob",e)}describeRestoreJob(e){return this.request("DescribeRestoreJob",{RestoreJobId:e})}deleteRecoveryPoint(e,t){return this.request("DeleteRecoveryPoint",{BackupVaultName:e,RecoveryPointArn:t})}}class ji{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new pe}async describeCacheClusters(e){let t={Action:"DescribeCacheClusters",Version:"2015-02-02",ShowCacheNodeInfo:"true"};if(e)t.CacheClusterId=e;let r=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{CacheClusters:this.parseCacheClusters(r)}}async describeReplicationGroups(e){let t={Action:"DescribeReplicationGroups",Version:"2015-02-02"};if(e)t.ReplicationGroupId=e;let r=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{ReplicationGroups:[]}}async createCacheCluster(e){let t={Action:"CreateCacheCluster",Version:"2015-02-02",CacheClusterId:e.cacheClusterId,Engine:e.engine,CacheNodeType:e.cacheNodeType};if(e.numCacheNodes)t.NumCacheNodes=e.numCacheNodes;if(e.engineVersion)t.EngineVersion=e.engineVersion;if(e.port)t.Port=e.port;if(e.securityGroupIds&&e.securityGroupIds.length>0)e.securityGroupIds.forEach((n,i)=>{t[`SecurityGroupIds.member.${i+1}`]=n});if(e.subnetGroupName)t.CacheSubnetGroupName=e.subnetGroupName;if(e.tags&&e.tags.length>0)e.tags.forEach((n,i)=>{t[`Tags.member.${i+1}.Key`]=n.Key,t[`Tags.member.${i+1}.Value`]=n.Value});let r=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{CacheCluster:this.parseCacheCluster(r)}}async deleteCacheCluster(e,t){let r={Action:"DeleteCacheCluster",Version:"2015-02-02",CacheClusterId:e};if(t)r.FinalSnapshotIdentifier=t;await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(r).toString()})}async rebootCacheCluster(e,t){let r={Action:"RebootCacheCluster",Version:"2015-02-02",CacheClusterId:e};t.forEach((n,i)=>{r[`CacheNodeIdsToReboot.member.${i+1}`]=n}),await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(r).toString()})}async describeCacheEngineVersions(e){let t={Action:"DescribeCacheEngineVersions",Version:"2015-02-02"};if(e)t.Engine=e;let r=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{CacheEngineVersions:[]}}async getCacheStatistics(e){let t=await this.describeCacheClusters(e);if(!t.CacheClusters||t.CacheClusters.length===0)throw Error(`Cache cluster ${e} not found`);return{cpuUtilization:0,evictions:0,hits:0,misses:0,connections:0}}parseCacheClusters(e){if(e.CacheClusterId)return[{CacheClusterId:e.CacheClusterId,CacheClusterStatus:e.CacheClusterStatus||"available",Engine:e.Engine||"redis",EngineVersion:e.EngineVersion||"7.0",CacheNodeType:e.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt(e.NumCacheNodes||"1"),CacheClusterCreateTime:e.CacheClusterCreateTime||new Date().toISOString()}];return[]}parseCacheCluster(e){return{CacheClusterId:e.CacheClusterId,CacheClusterStatus:e.CacheClusterStatus||"creating",Engine:e.Engine||"redis",EngineVersion:e.EngineVersion||"7.0",CacheNodeType:e.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt(e.NumCacheNodes||"1"),CacheClusterCreateTime:e.CacheClusterCreateTime||new Date().toISOString()}}}import{isIP as Dp}from"node:net";var JS={every_minute:"* * * * *",every_five_minutes:"*/5 * * * *",hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 0"},WS={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12},Tp={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};function Ap(e){try{return new Intl.DateTimeFormat("en",{timeZone:e}).format(new Date),e}catch{throw Error(`Unknown schedule timezone: ${e}`)}}function zo(e,t,r,n){let i=t[e.toUpperCase()]??Number(e);if(!Number.isInteger(i)||i<r||i>n)throw Error(`Schedule field value ${e} is outside ${r}-${n}.`);return i}function Gn(e,t,r,n={},i){if(e==="*"||e==="?")return;let o=new Set;for(let s of e.split(",")){let[c,u]=s.split("/"),a=u?zo(u,{},1,r-t+1):1,p,f;if(c==="*")p=t,f=r;else if(c.includes("-")){let y=c.split("-");p=zo(y[0],n,t,r),f=zo(y[1],n,t,r)}else p=zo(c,n,t,r),f=p;if(f<p)throw Error("Schedule ranges must be ascending.");for(let y=p;y<=f;y+=a)o.add(i?i(y):y===7&&r===7?0:y)}return o}function HS(e,t){let r=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"numeric",day:"numeric",weekday:"short",hour:"numeric",minute:"numeric",hourCycle:"h23"}).formatToParts(e).map((n)=>[n.type,n.value]));return{minute:Number(r.minute),hour:Number(r.hour),day:Number(r.day),month:Number(r.month),weekday:Tp[r.weekday.toUpperCase()],year:Number(r.year),key:`${r.year}-${r.month}-${r.day} ${r.hour}:${r.minute}`}}function kp(e){let r=(e.startsWith("cron(")?e.slice(5,-1).trim():e.trim()).split(/\s+/);if(r.length!==5&&r.length!==6)throw Error("Cron schedules require five standard fields or six EventBridge fields.");let[n,i,o,s,c,u]=r,a=r.length===6;return{minute:Gn(n,0,59),hour:Gn(i,0,23),day:Gn(o,1,31),month:Gn(s,1,12,WS),weekday:Gn(c,a?1:0,7,Tp,a?(p)=>p===7?6:p-1:void 0),year:u?Gn(u,1970,2199):void 0,dayWildcard:o==="*"||o==="?",weekdayWildcard:c==="*"||c==="?"}}function GS(e,t){if(!((!t.minute||t.minute.has(e.minute))&&(!t.hour||t.hour.has(e.hour))&&(!t.month||t.month.has(e.month))&&(!t.year||t.year.has(e.year))))return!1;let n=!t.day||t.day.has(e.day),i=!t.weekday||t.weekday.has(e.weekday);return t.dayWildcard?i:t.weekdayWildcard?n:n||i}function Rp(e){let t=/^rate\(\s*(\d+)\s+(minute|minutes|hour|hours|day|days)\s*\)$/i.exec(e);if(!t)return;let r=Number(t[1]);if(r<1)throw Error("Rate amount must be positive.");return r*(t[2].toLowerCase().startsWith("minute")?60000:t[2].toLowerCase().startsWith("hour")?3600000:86400000)}function Kn(e){let t=e.trim(),r=JS[t.toLowerCase()]??t;if(!r)throw Error("Schedule expression is required.");let n=Rp(r);if(n){let i=n/60000;return{original:t,normalized:`rate(${i} minutes)`,kind:"rate",description:i%1440===0?`Every ${i/1440} day(s)`:i%60===0?`Every ${i/60} hour(s)`:`Every ${i} minute(s)`}}return kp(r),{original:t,normalized:r.startsWith("cron(")?r:`cron(${r})`,kind:"cron",description:`Cron ${r.replace(/^cron\(|\)$/g,"")}`}}function hn(e,t,r=new Date,n=5){let i=Kn(e),o=Ap(t),s=Math.min(20,Math.max(1,n)),c=Rp(i.normalized);if(c)return Array.from({length:s},(b,C)=>new Date(r.getTime()+c*(C+1)).toISOString());let u=kp(i.normalized),a=[],p=new Set,f=new Date(Math.floor(r.getTime()/60000)*60000+60000),y=0;while(a.length<s&&y<1100000){let b=HS(f,o);if(GS(b,u)&&!p.has(b.key))a.push(f.toISOString()),p.add(b.key);f=new Date(f.getTime()+60000),y++}if(a.length<s)throw Error("Schedule produced no runs within the bounded preview horizon.");return a}function yn(e,t="UTC",r=new Date,n=5){let i=Kn(e),o=hn(i.normalized,t,r,n),s=i.kind==="cron"?["Server cron and EventBridge use the same wall-clock preview; provider-specific extensions are retained only when supported."]:["Rate schedules use elapsed-time intervals and are not shifted by DST."];return{...i,timezone:Ap(t),nextRuns:o,capabilities:{server:i.kind==="cron",eventbridge:!0,notes:s}}}function lc(e){let t=Kn(e.expression),r=t.normalized.slice(5,-1).trim().split(/\s+/),n=t.kind==="cron"&&r.length===5;if(e.provider==="server")return{provider:"server",supported:n,features:{timezone:!0,flexibleWindow:!1,catchUp:!1,replaceOverlap:!1},notes:[t.kind==="rate"?"Server cron requires a cron expression; use an equivalent cron schedule.":r.length!==5?"EventBridge six-field cron extensions cannot be installed as server cron.":"Cron is reconciled through a root-owned ts-cloud entry.",e.missedRunPolicy==="catch_up"?"Catch-up is handled by the control plane, not cron.":"Missed runs are skipped by cron."]};if(e.provider==="eventbridge")return{provider:"eventbridge",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!1,replaceOverlap:!1},notes:["Five-field cron is translated explicitly to EventBridge six-field syntax. Flexible windows are provider-native; overlap and catch-up remain control-plane policies."]};if(e.provider==="lambda")return{provider:"lambda",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!1,replaceOverlap:!1},notes:["The schedule invokes one immutable Lambda target."]};return{provider:"platform",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!0,replaceOverlap:!0},notes:["The durable control-plane worker enforces all configured policies."]}}function KS(e){if(e.queues===!0)return[{queue:"default",processes:e.queueConcurrency??1}];if(!Array.isArray(e.queues))return[];return e.queues.map((t)=>{if(typeof t==="string")return{queue:t,processes:e.queueConcurrency??1};let[r,n]=Object.entries(t)[0]??["default",e.queueConcurrency??1];return{queue:r,processes:n}})}function pc(e,t,r){let n=new Set,i=new Set,o=new Map(r.resources.map((f)=>[f.slug,f])),s=0,c=0;for(let[f,y]of Object.entries(t.sites??{})){let b=o.get(f);if(y.scheduler){let R=`config:site:${f}:scheduler`;n.add(R),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,resourceId:b?.id,name:`${f} scheduler`,provider:"server",expression:"* * * * *",timezone:"UTC",flexibleMinutes:0,target:{kind:"dashboard_operation",operationId:`scheduler:run:${f}`},payloadRefs:{},missedRunPolicy:"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:30},timeoutSeconds:300,enabled:!0,origin:"config",sourceKey:R,observedState:{source:"cloud.config.ts"},reconciliationStatus:"pending"}),s++}let C=y,T=Array.isArray(C.queues??C.workers)?C.queues??C.workers:[];for(let[R,x]of T.entries()){let L=typeof x==="string"?{queue:x}:x,P=String(L.queue??L.name??"default"),G=`config:site:${f}:worker:${R}:${P}`;i.add(G),e.upsertWorker({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,resourceId:b?.id,name:`${f}:${P}`,provider:"systemd",queue:P,processes:Number(L.processes)||1,timeoutSeconds:Number(L.timeout)||60,restartPolicy:"always",target:{operationId:`worker:restart:${f}`,site:f},enabled:!0,origin:"config",sourceKey:G,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),c++}}let u=t.infrastructure?.compute?.backups;if(u?.enabled)n.add("config:platform:backup"),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:"Scheduled backup",provider:"server",expression:String(u.schedule??"0 2 * * *"),timezone:String(u.timezone??"UTC"),flexibleMinutes:0,target:{kind:"dashboard_operation",operationId:"backup:run"},payloadRefs:{},missedRunPolicy:"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:60},timeoutSeconds:3600,enabled:!0,origin:"config",sourceKey:"config:platform:backup",observedState:{source:"cloud.config.ts"},reconciliationStatus:"pending"}),s++;let a=t.environments?.[r.environment.slug]?.app;if(a){if(a.scheduler!=="off"){let f=`config:serverless:${r.environment.slug}:scheduler`;n.add(f),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:`${r.environment.name} serverless scheduler`,provider:"eventbridge",expression:"rate(1 minute)",timezone:"UTC",flexibleMinutes:0,target:{kind:"serverless_scheduler",action:"schedule:run"},payloadRefs:{},missedRunPolicy:a.scheduler==="sub-minute"?"catch_up":"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:30},timeoutSeconds:a.cliTimeout??900,enabled:!0,origin:"config",sourceKey:f,observedState:{source:"cloud.config.ts",mode:a.scheduler??"on"},reconciliationStatus:"pending"}),s++}for(let{queue:f,processes:y}of KS(a)){let b=`config:serverless:${r.environment.slug}:worker:${f}`;i.add(b),e.upsertWorker({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:`${r.environment.name}:${f}`,provider:"lambda",queue:f,processes:y,timeoutSeconds:a.queueTimeout??120,restartPolicy:"on_failure",target:{function:"queue",queue:f},enabled:!0,origin:"config",sourceKey:b,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),c++}}let p=0;for(let f of e.list(r.project.id,{environmentId:r.environment.id}).filter((y)=>y.origin==="config"&&y.sourceKey&&!n.has(y.sourceKey)))e.reconcile(f.id,"drifted",{...f.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),p++;for(let f of e.listWorkers(r.project.id,r.environment.id).filter((y)=>y.origin==="config"&&y.sourceKey&&!i.has(y.sourceKey)))e.reconcileWorker(f.id,"drifted",{...f.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),p++;return{jobs:s,workers:c,drifted:p}}class gc{store;queue;constructor(e,t={}){this.store=e;this.queue=t.queue??new xe(e.controlPlane)}enqueue(e,t){let r=new Date(t.scheduledFor??this.store.now()).toISOString(),n=`${e.id}:${t.trigger==="manual"?crypto.randomUUID():r}`,i=this.store.activeExecution(e.id);if(i&&e.overlapPolicy==="forbid")return this.store.createExecution({jobId:e.id,trigger:t.trigger,scheduledFor:r,idempotencyKey:n,status:"skipped",output:{reason:"overlap_forbidden",activeExecutionId:i.id}});if(i&&e.overlapPolicy==="replace"&&i.operationId)try{this.queue.requestCancellation(i.operationId,t.actorId)}catch{}let o=this.store.createExecution({jobId:e.id,trigger:t.trigger,scheduledFor:r,idempotencyKey:n,status:"queued",output:{semantics:"at_least_once"}});if(o.operationId)return o;let s=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:t.actorId,kind:"job.execute",input:{jobId:e.id,executionId:o.id},idempotencyKey:`job-execution:${o.id}`,lockKey:e.overlapPolicy==="allow"?`job-execution:${o.id}`:`job:${e.id}`,maxAttempts:e.retryPolicy.maxAttempts,timeoutSeconds:e.timeoutSeconds,retryClasses:["job_transient"],resumePolicy:"requeue"}).operation;return this.store.attachOperation(o.id,s.id)}tick(e=this.store.now()){let t=[];for(let r of this.store.due(e.toISOString())){let n=r.nextRunAt,i=hn(r.normalizedExpression,r.timezone,e,1)[0];if(r.missedRunPolicy==="catch_up"){let o=n,s=0;while(o<=e.toISOString()&&s<10)t.push(this.enqueue(r,{trigger:o===n?"scheduled":"catch_up",scheduledFor:o})),o=hn(r.normalizedExpression,r.timezone,new Date(o),1)[0],s++}else t.push(this.enqueue(r,{trigger:"scheduled",scheduledFor:n}));this.store.markScheduled(r.id,n,i)}return t}}function Pp(e){return{"job.execute":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.store.get(String(n.jobId??"")),o=e.store.getExecution(String(n.executionId??""));if(!i||!o)throw Error("Scheduled job execution is no longer available.");e.store.transitionExecution(o.id,"running",{attempt:r.operation.attempt}),r.checkpoint("execute",`Running ${i.name} on ${i.provider}.`),r.log(`Trigger ${o.trigger}; scheduled for ${o.scheduledFor}; semantics at-least-once.`,{stream:"system"});let s=await e.executor(i,i.target,r);if(s.stdout)r.log(s.stdout,{stream:"stdout"});if(s.stderr)r.log(s.stderr,{stream:"stderr"});if(!s.ok){if(e.store.transitionExecution(o.id,r.operation.attempt>=i.retryPolicy.maxAttempts?"dead":"failed",{attempt:r.operation.attempt,error:s.stderr??"Job execution failed."}),s.retryable)throw new Vo(s.stderr??"Scheduled job failed transiently.","job_transient");throw Error(s.stderr??"Scheduled job failed.")}return e.store.transitionExecution(o.id,"succeeded",{attempt:r.operation.attempt,output:s.output??{}}),{jobId:i.id,executionId:o.id,provider:i.provider}}}}var dt=(e)=>typeof e==="string"&&e?e:void 0,xp=(e)=>Number(e)===1,bn=(e)=>{try{return JSON.parse(String(e))}catch{return{}}},Hr=(e,t,r,n)=>{let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,Math.floor(i))):t};function qo(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:dt(e.environment_id),resourceId:dt(e.resource_id),name:String(e.name),provider:String(e.provider),expression:String(e.expression),normalizedExpression:String(e.normalized_expression),timezone:String(e.timezone),startsAt:dt(e.starts_at),endsAt:dt(e.ends_at),flexibleMinutes:Number(e.flexible_minutes),target:bn(e.target),payloadRefs:bn(e.payload_refs),missedRunPolicy:String(e.missed_run_policy),overlapPolicy:String(e.overlap_policy),retryPolicy:bn(e.retry_policy),timeoutSeconds:Number(e.timeout_seconds),enabled:xp(e.enabled),origin:String(e.origin),sourceKey:dt(e.source_key),ownerActorId:dt(e.owner_actor_id),observedState:bn(e.observed_state),reconciliationStatus:String(e.reconciliation_status),nextRunAt:dt(e.next_run_at),lastScheduledFor:dt(e.last_scheduled_for),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Jo(e){return{id:String(e.id),jobId:String(e.job_id),operationId:dt(e.operation_id),trigger:String(e.trigger),scheduledFor:String(e.scheduled_for),idempotencyKey:String(e.idempotency_key),status:String(e.status),attempt:Number(e.attempt),startedAt:dt(e.started_at),finishedAt:dt(e.finished_at),output:bn(e.output),error:dt(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function mc(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:dt(e.environment_id),resourceId:dt(e.resource_id),name:String(e.name),provider:String(e.provider),queue:String(e.queue),processes:Number(e.processes),timeoutSeconds:Number(e.timeout_seconds),restartPolicy:String(e.restart_policy),target:bn(e.target),enabled:xp(e.enabled),origin:String(e.origin),sourceKey:dt(e.source_key),ownerActorId:dt(e.owner_actor_id),observedState:bn(e.observed_state),reconciliationStatus:String(e.reconciliation_status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class fc{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return this.options.now?.()??new Date}create(e){if(!e.name.trim())throw Error("Scheduled jobs require a name.");let t=yn(e.expression,e.timezone,this.now(),1),r=crypto.randomUUID(),n=this.now().toISOString(),i=e.startsAt?new Date(e.startsAt).toISOString():void 0,o=e.endsAt?new Date(e.endsAt).toISOString():void 0;if(i&&o&&i>=o)throw Error("Schedule start must be before end.");let s=t.nextRuns.find((c)=>(!i||c>=i)&&(!o||c<=o));return this.controlPlane.database.run("INSERT INTO scheduled_jobs (id,organization_id,project_id,environment_id,resource_id,name,provider,expression,normalized_expression,timezone,starts_at,ends_at,flexible_minutes,target,payload_refs,missed_run_policy,overlap_policy,retry_policy,timeout_seconds,enabled,origin,source_key,owner_actor_id,observed_state,reconciliation_status,next_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name.trim().slice(0,120),e.provider,e.expression,t.normalized,e.timezone,i??null,o??null,Hr(e.flexibleMinutes,0,0,1440),JSON.stringify(e.target),JSON.stringify(e.payloadRefs),e.missedRunPolicy,e.overlapPolicy,JSON.stringify({maxAttempts:Hr(e.retryPolicy.maxAttempts,3,1,20),backoffSeconds:Hr(e.retryPolicy.backoffSeconds,30,0,86400),deadLetterRef:e.retryPolicy.deadLetterRef}),Hr(e.timeoutSeconds,900,1,86400),e.enabled?1:0,e.origin,e.sourceKey??null,e.ownerActorId??null,JSON.stringify(e.observedState),e.reconciliationStatus,s??null,1,n,n]),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE id=?").get(e);return t?qo(t):void 0}getBySource(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE project_id=? AND environment_id IS ? AND source_key=?").get(e,t??null,r);return n?qo(n):void 0}list(e,t={}){let r=["project_id=?"],n=[e];if(t.environmentId)r.push("environment_id=?"),n.push(t.environmentId);if(t.resourceIds?.length)r.push(`resource_id IN (${t.resourceIds.map(()=>"?").join(",")})`),n.push(...t.resourceIds);if(t.enabled!=null)r.push("enabled=?"),n.push(t.enabled?1:0);return this.controlPlane.database.query(`SELECT * FROM scheduled_jobs WHERE ${r.join(" AND ")} ORDER BY next_run_at IS NULL,next_run_at,name`).all(...n).map(qo)}setEnabled(e,t){this.controlPlane.database.run("UPDATE scheduled_jobs SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now().toISOString(),e]);let r=this.get(e);if(!r)throw Error("Scheduled job was not found.");return r}updateSchedule(e,t){let r=this.get(e);if(!r)throw Error("Scheduled job was not found.");let n=t.expression??r.expression,i=t.timezone??r.timezone,o=yn(n,i,this.now(),1),s=this.now().toISOString();return this.controlPlane.database.run("UPDATE scheduled_jobs SET expression=?,normalized_expression=?,timezone=?,missed_run_policy=?,overlap_policy=?,timeout_seconds=?,next_run_at=?,reconciliation_status=?,version=version+1,updated_at=? WHERE id=?",[n,o.normalized,i,t.missedRunPolicy??r.missedRunPolicy,t.overlapPolicy??r.overlapPolicy,Hr(t.timeoutSeconds,r.timeoutSeconds,1,86400),o.nextRuns[0],"pending",s,e]),this.get(e)}remove(e){let t=this.get(e);if(!t)throw Error("Scheduled job was not found.");if(t.origin==="config")throw Error("Config-defined jobs must be removed from configuration, not destructively deleted.");this.controlPlane.database.run("DELETE FROM scheduled_jobs WHERE id=?",[e])}markScheduled(e,t,r){this.controlPlane.database.run("UPDATE scheduled_jobs SET last_scheduled_for=?,next_run_at=?,updated_at=? WHERE id=?",[t,r??null,this.now().toISOString(),e])}reconcile(e,t,r){return this.controlPlane.database.run("UPDATE scheduled_jobs SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[t,JSON.stringify(r),this.now().toISOString(),e]),this.get(e)}upsertConfigJob(e){let t=this.getBySource(e.projectId,e.environmentId,e.sourceKey);if(!t)return this.create(e);let r=yn(e.expression,e.timezone,this.now(),1),n=this.now().toISOString();if(t.resourceId===e.resourceId&&t.name===e.name&&t.provider===e.provider&&t.expression===e.expression&&t.normalizedExpression===r.normalized&&t.timezone===e.timezone&&JSON.stringify(t.target)===JSON.stringify(e.target)&&JSON.stringify(t.payloadRefs)===JSON.stringify(e.payloadRefs)&&t.missedRunPolicy===e.missedRunPolicy&&t.overlapPolicy===e.overlapPolicy&&JSON.stringify(t.retryPolicy)===JSON.stringify(e.retryPolicy)&&t.timeoutSeconds===e.timeoutSeconds&&t.enabled===e.enabled)return t;return this.controlPlane.database.run("UPDATE scheduled_jobs SET resource_id=?,name=?,provider=?,expression=?,normalized_expression=?,timezone=?,target=?,payload_refs=?,missed_run_policy=?,overlap_policy=?,retry_policy=?,timeout_seconds=?,enabled=?,observed_state=?,reconciliation_status=?,next_run_at=COALESCE(next_run_at,?),version=version+1,updated_at=? WHERE id=?",[e.resourceId??null,e.name,e.provider,e.expression,r.normalized,e.timezone,JSON.stringify(e.target),JSON.stringify(e.payloadRefs),e.missedRunPolicy,e.overlapPolicy,JSON.stringify(e.retryPolicy),e.timeoutSeconds,e.enabled?1:0,JSON.stringify(e.observedState),e.reconciliationStatus,r.nextRuns[0],n,t.id]),this.get(t.id)}due(e=this.now().toISOString()){return this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE enabled=1 AND next_run_at IS NOT NULL AND next_run_at<=? AND (starts_at IS NULL OR starts_at<=?) AND (ends_at IS NULL OR ends_at>=?) ORDER BY next_run_at LIMIT 200").all(e,e,e).map(qo)}createExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return Jo(t);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO job_executions (id,job_id,operation_id,trigger,scheduled_for,idempotency_key,status,attempt,output,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[r,e.jobId,e.operationId??null,e.trigger,e.scheduledFor,e.idempotencyKey,e.status,0,JSON.stringify(e.output),n,n]),this.getExecution(r)}getExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE id=?").get(e);return t?Jo(t):void 0}listExecutions(e,t=100){return this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? ORDER BY scheduled_for DESC,created_at DESC LIMIT ?").all(e,Math.min(1000,Math.max(1,t))).map(Jo)}activeExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? AND status IN ('queued','running') ORDER BY created_at DESC LIMIT 1").get(e);return t?Jo(t):void 0}attachOperation(e,t){return this.controlPlane.database.run("UPDATE job_executions SET operation_id=?,updated_at=? WHERE id=?",[t,this.now().toISOString(),e]),this.getExecution(e)}transitionExecution(e,t,r={}){let n=this.now().toISOString(),i=t==="running"?n:null,o=["succeeded","failed","skipped","dead"].includes(t)?n:null;return this.controlPlane.database.run("UPDATE job_executions SET status=?,attempt=COALESCE(?,attempt),started_at=COALESCE(started_at,?),finished_at=?,output=COALESCE(?,output),error=?,updated_at=? WHERE id=?",[t,r.attempt??null,i,o,r.output?JSON.stringify(r.output):null,r.error?.slice(0,2000)??null,n,e]),this.getExecution(e)}upsertWorker(e){let t=e.sourceKey?this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE project_id=? AND source_key=? AND environment_id IS ?").get(e.projectId,e.sourceKey,e.environmentId??null):void 0,r=t?mc(t):void 0,n=r?.id??crypto.randomUUID(),i=this.now().toISOString(),o=Hr(e.processes,1,0,1000),s=Hr(e.timeoutSeconds,60,1,86400);if(r&&r.resourceId===e.resourceId&&r.name===e.name.slice(0,120)&&r.provider===e.provider&&r.queue===e.queue.slice(0,200)&&r.processes===o&&r.timeoutSeconds===s&&r.restartPolicy===e.restartPolicy&&JSON.stringify(r.target)===JSON.stringify(e.target)&&r.enabled===e.enabled)return r;return this.controlPlane.database.run("INSERT INTO worker_definitions (id,organization_id,project_id,environment_id,resource_id,name,provider,queue,processes,timeout_seconds,restart_policy,target,enabled,origin,source_key,owner_actor_id,observed_state,reconciliation_status,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,resource_id=excluded.resource_id,provider=excluded.provider,queue=excluded.queue,processes=excluded.processes,timeout_seconds=excluded.timeout_seconds,restart_policy=excluded.restart_policy,target=excluded.target,enabled=excluded.enabled,observed_state=excluded.observed_state,reconciliation_status=excluded.reconciliation_status,version=worker_definitions.version+1,updated_at=excluded.updated_at",[n,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name.slice(0,120),e.provider,e.queue.slice(0,200),o,s,e.restartPolicy,JSON.stringify(e.target),e.enabled?1:0,e.origin,e.sourceKey??null,e.ownerActorId??null,JSON.stringify(e.observedState),e.reconciliationStatus,1,r?.createdAt??i,i]),this.getWorker(n)}getWorker(e){let t=this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE id=?").get(e);return t?mc(t):void 0}listWorkers(e,t){return this.controlPlane.database.query(`SELECT * FROM worker_definitions WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(mc)}setWorkerProcesses(e,t){this.controlPlane.database.run("UPDATE worker_definitions SET processes=?,reconciliation_status='pending',version=version+1,updated_at=? WHERE id=?",[Hr(t,1,0,1000),this.now().toISOString(),e]);let r=this.getWorker(e);if(!r)throw Error("Worker was not found.");return r}reconcileWorker(e,t,r){this.controlPlane.database.run("UPDATE worker_definitions SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[t,JSON.stringify(r),this.now().toISOString(),e]);let n=this.getWorker(e);if(!n)throw Error("Worker was not found.");return n}}var me=(e)=>e==null?void 0:String(e),Wo=(e)=>Number(e)===1,Gr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}};function Op(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),provider:String(e.provider),endpoint:me(e.endpoint),endpointPolicy:String(e.endpoint_policy),bucket:me(e.bucket),prefix:String(e.prefix),region:me(e.region),forcePathStyle:Wo(e.force_path_style),credentialRef:me(e.credential_ref),encryption:String(e.encryption),encryptionKeyRef:me(e.encryption_key_ref),immutability:Gr(e.immutability,{}),status:String(e.status),lastTestedAt:me(e.last_tested_at),lastSuccessAt:me(e.last_success_at),lastFailureAt:me(e.last_failure_at),lastError:me(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function hc(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:me(e.environment_id),resourceId:me(e.resource_id),dataServiceId:me(e.data_service_id),destinationId:String(e.destination_id),name:String(e.name),resourceKind:String(e.resource_kind),schedule:String(e.schedule),timezone:String(e.timezone),retention:Gr(e.retention,{}),compression:String(e.compression),encryption:String(e.encryption),includePatterns:Gr(e.include_patterns,[]),excludePatterns:Gr(e.exclude_patterns,[]),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),healthCheckId:me(e.health_check_id),enabled:Wo(e.enabled),nextRunAt:me(e.next_run_at),lastRunAt:me(e.last_run_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function yc(e){return{id:String(e.id),projectId:String(e.project_id),policyId:me(e.policy_id),destinationId:String(e.destination_id),resourceId:me(e.resource_id),dataServiceId:me(e.data_service_id),backupJobId:me(e.backup_job_id),kind:String(e.kind),pointInTime:String(e.point_in_time),uri:String(e.uri),sizeBytes:Number(e.size_bytes),checksum:String(e.checksum),manifest:Gr(e.manifest,{}),toolVersion:me(e.tool_version),engineVersion:me(e.engine_version),expiresAt:me(e.expires_at),lockedUntil:me(e.locked_until),held:Wo(e.held),pinned:Wo(e.pinned),status:String(e.status),verificationState:String(e.verification_state),verifiedAt:me(e.verified_at),durationMs:e.duration_ms==null?void 0:Number(e.duration_ms),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function bc(e){return{id:String(e.id),projectId:String(e.project_id),policyId:me(e.policy_id),recoveryPointId:me(e.recovery_point_id),operationId:me(e.operation_id),kind:String(e.kind),status:String(e.status),idempotencyKey:String(e.idempotency_key),target:Gr(e.target,{}),restoreMode:me(e.restore_mode),cancellability:String(e.cancellability),safetyBackupId:me(e.safety_backup_id),healthResult:e.health_result?Gr(e.health_result,{}):void 0,progress:Gr(e.progress,{}),error:me(e.error),startedAt:me(e.started_at),finishedAt:me(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function QS(e){let t=e.toLowerCase();if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal"))return!0;if(Dp(t)===6)return t==="::1"||t.startsWith("fe80:");if(Dp(t)!==4)return!1;let[r,n]=t.split(".").map(Number);return r===10||r===127||r===0||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function YS(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup destination names must be 2-63 lowercase letters, numbers, or dashes.");if(e.provider!=="aws_backup"&&!e.bucket)throw Error("S3 backup destinations require a bucket.");if(e.provider==="s3_compatible"&&!e.endpoint)throw Error("S3-compatible destinations require an explicit endpoint.");if(e.provider==="s3_compatible"&&!e.credentialRef)throw Error("S3-compatible destinations require a credential reference.");if(e.encryption!=="provider"&&!e.encryptionKeyRef)throw Error("Client-side encryption requires an encryption key reference.");if(e.endpoint){let t=new URL(e.endpoint);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw Error("Backup endpoints must be origin-only HTTPS URLs without credentials, paths, queries, or fragments.");if(QS(t.hostname)&&e.endpointPolicy!=="allow_private")throw Error("Private backup endpoints require endpointPolicy allow_private.")}}class Sc{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}createDestination(e){YS(e);let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_destinations (id,organization_id,project_id,name,provider,endpoint,endpoint_policy,bucket,prefix,region,force_path_style,credential_ref,encryption,encryption_key_ref,immutability,status,last_tested_at,last_success_at,last_failure_at,last_error,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.provider,e.endpoint??null,e.endpointPolicy,e.bucket??null,e.prefix,e.region??null,e.forcePathStyle?1:0,e.credentialRef??null,e.encryption,e.encryptionKeyRef??null,JSON.stringify(e.immutability),e.status,e.lastTestedAt??null,e.lastSuccessAt??null,e.lastFailureAt??null,e.lastError??null,1,r,r]),this.getDestination(t)}getDestination(e){let t=this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE id=?").get(e);return t?Op(t):void 0}listDestinations(e){return this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE project_id=? ORDER BY name").all(e).map(Op)}recordDestinationTest(e,t){let r=this.now().toISOString();return this.controlPlane.database.run("UPDATE backup_destinations SET status=?,last_tested_at=?,last_success_at=CASE WHEN ? THEN ? ELSE last_success_at END,last_failure_at=CASE WHEN ? THEN last_failure_at ELSE ? END,last_error=?,version=version+1,updated_at=? WHERE id=?",[t.ok?"healthy":"failing",r,t.ok?1:0,r,t.ok?1:0,r,t.ok?null:String(t.error??"Destination test failed.").slice(0,1000),r,e]),this.getDestination(e)}createPolicy(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup policy names must be lowercase slugs.");if(!e.resourceId&&!e.dataServiceId&&!["control_plane","infrastructure"].includes(e.resourceKind))throw Error("A backup policy requires a resource or data service target.");let t=this.getDestination(e.destinationId);if(!t||t.projectId!==e.projectId)throw Error("Backup destination was not found.");if(e.resourceKind==="control_plane"&&t.encryption==="provider")throw Error("Control-plane backups require client-side destination encryption.");if(["logical_database","volume","files","control_plane"].includes(e.resourceKind)&&t.provider==="aws_backup")throw Error(`${e.resourceKind} backups require an object-storage destination.`);if(e.resourceKind==="infrastructure"&&t.provider!=="aws_backup")throw Error("Infrastructure backups require an AWS Backup destination.");let r=Kn(e.schedule),n=hn(r.normalized,e.timezone,this.now(),1)[0],i=crypto.randomUUID(),o=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_policies (id,organization_id,project_id,environment_id,resource_id,data_service_id,destination_id,name,resource_kind,schedule,timezone,retention,compression,encryption,include_patterns,exclude_patterns,expected_rpo_minutes,expected_rto_minutes,health_check_id,enabled,next_run_at,last_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[i,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.dataServiceId??null,e.destinationId,e.name,e.resourceKind,r.normalized,e.timezone,JSON.stringify(e.retention),e.compression,e.encryption,JSON.stringify(e.includePatterns),JSON.stringify(e.excludePatterns),e.expectedRpoMinutes,e.expectedRtoMinutes,e.healthCheckId??null,e.enabled?1:0,n,e.lastRunAt??null,1,o,o]),this.getPolicy(i)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM backup_policies WHERE id=?").get(e);return t?hc(t):void 0}listPolicies(e,t){return this.controlPlane.database.query(`SELECT * FROM backup_policies WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(hc)}duePolicies(e=this.now()){return this.controlPlane.database.query("SELECT * FROM backup_policies WHERE enabled=1 AND next_run_at<=? ORDER BY next_run_at,id").all(e.toISOString()).map(hc)}advancePolicy(e,t){let r=this.getPolicy(e);if(!r)throw Error("Backup policy was not found.");let n=hn(r.schedule,r.timezone,new Date(t),1)[0];return this.controlPlane.database.run("UPDATE backup_policies SET last_run_at=?,next_run_at=?,version=version+1,updated_at=? WHERE id=?",[t,n,this.now().toISOString(),e]),this.getPolicy(e)}createJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return bc(t);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_jobs (id,project_id,policy_id,recovery_point_id,operation_id,kind,status,idempotency_key,target,restore_mode,cancellability,safety_backup_id,health_result,progress,error,started_at,finished_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.projectId,e.policyId??null,e.recoveryPointId??null,e.operationId??null,e.kind,e.status,e.idempotencyKey,JSON.stringify(e.target),e.restoreMode??null,e.cancellability,e.safetyBackupId??null,e.healthResult?JSON.stringify(e.healthResult):null,JSON.stringify(e.progress),e.error??null,e.startedAt??null,e.finishedAt??null,n,n]),this.getJob(r)}getJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE id=?").get(e);return t?bc(t):void 0}listJobs(e){return this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE project_id=? ORDER BY created_at DESC").all(e).map(bc)}updateJob(e,t){let r=this.getJob(e);if(!r)throw Error("Backup job was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE backup_jobs SET status=?,operation_id=?,recovery_point_id=?,progress=?,health_result=?,error=?,started_at=?,finished_at=?,safety_backup_id=?,updated_at=? WHERE id=?",[n.status,n.operationId??null,n.recoveryPointId??null,JSON.stringify(n.progress),n.healthResult?JSON.stringify(n.healthResult):null,n.error??null,n.startedAt??null,n.finishedAt??null,n.safetyBackupId??null,this.now().toISOString(),e]),this.getJob(e)}createRecoveryPoint(e){if(!/^sha256:[a-f0-9]{64}$/i.test(e.checksum))throw Error("Recovery points require a SHA-256 checksum.");if(typeof e.uri!=="string"||!["s3:","aws-backup:","file:"].some((n)=>e.uri.startsWith(n)))throw Error("Recovery point URI uses an unsupported destination scheme.");let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO recovery_points (id,project_id,policy_id,destination_id,resource_id,data_service_id,backup_job_id,kind,point_in_time,uri,size_bytes,checksum,manifest,tool_version,engine_version,expires_at,locked_until,held,pinned,status,verification_state,verified_at,duration_ms,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.policyId??null,e.destinationId,e.resourceId??null,e.dataServiceId??null,e.backupJobId??null,e.kind,e.pointInTime,e.uri,e.sizeBytes,e.checksum,JSON.stringify(e.manifest),e.toolVersion??null,e.engineVersion??null,e.expiresAt??null,e.lockedUntil??null,e.held?1:0,e.pinned?1:0,e.status,e.verificationState,e.verifiedAt??null,e.durationMs??null,r,r]),this.getRecoveryPoint(t)}getRecoveryPoint(e){let t=this.controlPlane.database.query("SELECT * FROM recovery_points WHERE id=?").get(e);return t?yc(t):void 0}listRecoveryPoints(e,t){return this.controlPlane.database.query(`SELECT * FROM recovery_points WHERE project_id=?${t?" AND policy_id=?":""} ORDER BY point_in_time DESC`).all(e,...t?[t]:[]).map(yc)}updateRecoveryPoint(e,t){let r=this.getRecoveryPoint(e);if(!r)throw Error("Recovery point was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE recovery_points SET status=?,verification_state=?,verified_at=?,held=?,pinned=?,manifest=?,duration_ms=?,updated_at=? WHERE id=?",[n.status,n.verificationState,n.verifiedAt??null,n.held?1:0,n.pinned?1:0,JSON.stringify(n.manifest),n.durationMs??null,this.now().toISOString(),e]),this.getRecoveryPoint(e)}retentionCandidates(e=this.now()){let t=this.controlPlane.database.query(`SELECT rp.* FROM recovery_points rp
|
|
38
|
-
WHERE rp.status='available' AND rp.held=0 AND rp.pinned=0
|
|
39
|
-
AND rp.expires_at IS NOT NULL AND rp.expires_at<=?
|
|
40
|
-
AND (rp.locked_until IS NULL OR rp.locked_until<=?)
|
|
41
|
-
AND NOT EXISTS (
|
|
42
|
-
SELECT 1 FROM backup_jobs bj WHERE bj.recovery_point_id=rp.id
|
|
43
|
-
AND bj.kind IN ('restore','drill') AND bj.status IN ('queued','running','cleanup_required')
|
|
44
|
-
)
|
|
45
|
-
ORDER BY rp.expires_at,rp.id`).all(e.toISOString(),e.toISOString()).map(yc),r=new Set;for(let n of new Set(t.map((i)=>i.projectId)))for(let i of this.listPolicies(n)){let o=this.listRecoveryPoints(i.projectId,i.id).filter((c)=>c.status==="available").sort((c,u)=>u.pointInTime.localeCompare(c.pointInTime));for(let c of o.slice(0,Math.max(0,i.retention.keepLast??0)))r.add(c.id);let s=[[i.retention.hourly,(c)=>c.toISOString().slice(0,13)],[i.retention.daily,(c)=>c.toISOString().slice(0,10)],[i.retention.weekly,(c)=>new Date(Date.UTC(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()-(c.getUTCDay()+6)%7)).toISOString().slice(0,10)],[i.retention.monthly,(c)=>c.toISOString().slice(0,7)]];for(let[c,u]of s){let a=new Set;for(let p of o){let f=u(new Date(p.pointInTime));if(a.has(f))continue;if(a.add(f),a.size<=Math.max(0,c??0))r.add(p.id)}}}return t.filter((n)=>!r.has(n.id))}coverage(e,t=this.now()){let r=new Map(this.listDestinations(e).map((n)=>[n.id,n]));return this.listPolicies(e).map((n)=>{let i=this.listRecoveryPoints(e,n.id).filter((c)=>c.status==="available"),o=i[0],s=o?(t.getTime()-new Date(o.pointInTime).getTime())/60000:Number.POSITIVE_INFINITY;return{policy:n,lastRecoveryPoint:o,missedRpo:n.enabled&&s>n.expectedRpoMinutes,unverified:i.filter((c)=>c.verificationState!=="verified").length,destinationHealthy:r.get(n.destinationId)?.status==="healthy"}})}}import{createCipheriv as XS,createDecipheriv as ZS,createHash as _p,randomBytes as Np}from"node:crypto";var vc=Buffer.from("TSCB1"),Ho=(e)=>`sha256:${_p("sha256").update(e).digest("hex")}`;function $p(e){return _p("sha256").update(e).digest()}function ev(e,t,r){let n=r?Buffer.from(r):Np(12);if(n.length!==12)throw Error("Backup encryption IV must contain 12 bytes.");let i=XS("aes-256-gcm",$p(t),n),o=Buffer.concat([i.update(e),i.final()]),s=i.getAuthTag();return Buffer.concat([vc,n,s,o])}function tv(e,t){let r=Buffer.from(e);if(!r.subarray(0,vc.length).equals(vc))throw Error("Backup does not contain a valid encrypted envelope.");let n=r.subarray(5,17),i=r.subarray(17,33),o=r.subarray(33),s=ZS("aes-256-gcm",$p(t),n);return s.setAuthTag(i),Buffer.concat([s.update(o),s.final()])}function rv(e){let t;try{t=JSON.parse(e)}catch{throw Error("Backup destination credential must be a JSON object with accessKeyId and secretAccessKey.")}if(!t.accessKeyId||!t.secretAccessKey)throw Error("Backup destination credential requires accessKeyId and secretAccessKey.");if(t.expiresAt){let r=new Date(String(t.expiresAt));if(!Number.isFinite(r.getTime()))throw Error("Backup destination credential expiresAt must be an ISO timestamp.");if(r.getTime()<=Date.now())throw Error("Backup destination credential has expired.")}return{accessKeyId:String(t.accessKeyId),secretAccessKey:String(t.secretAccessKey),sessionToken:t.sessionToken?String(t.sessionToken):void 0}}async function Mp(e,t,r=new Date){if(!e.credentialRef)return{status:"default"};try{let n=JSON.parse(await t.resolve(e.credentialRef));if(!n.accessKeyId||!n.secretAccessKey)return{status:"invalid"};if(!n.expiresAt)return{status:"static"};let i=new Date(String(n.expiresAt));if(!Number.isFinite(i.getTime()))return{status:"invalid"};let o=i.getTime()-r.getTime();return{status:o<=0?"expired":o<=604800000?"expiring":"valid",expiresAt:i.toISOString()}}catch{return{status:"invalid"}}}class wc{secrets;clientFactory;multipartThreshold;partSize;constructor(e,t=(i,o)=>new hr(i.region??"us-east-1",void 0,{endpoint:i.endpoint?new URL(i.endpoint).host:void 0,forcePathStyle:i.forcePathStyle,credentials:o}),r=8388608,n=8388608){this.secrets=e;this.clientFactory=t;this.multipartThreshold=r;this.partSize=n}async client(e){let t=e.credentialRef?rv(await this.secrets.resolve(e.credentialRef)):void 0;return this.clientFactory(e,t)}async test(e){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let t=await this.client(e),r=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}.ts-cloud-health/${crypto.randomUUID()}`;await t.putObject({bucket:e.bucket,key:r,body:"ts-cloud backup destination health check",contentType:"text/plain"});try{let n=await t.getObjectBytes(e.bucket,r);if(Buffer.from(n.body).toString()!=="ts-cloud backup destination health check")throw Error("Backup destination health object was corrupted.")}finally{await t.deleteObject(e.bucket,r)}}async upload(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=Ho(t.body),i=e.encryption!=="provider"?await this.secrets.resolve(e.encryptionKeyRef):void 0,o=i?t.resume?.encryptionIv?Buffer.from(t.resume.encryptionIv,"base64url"):Np(12):void 0,s=i?ev(t.body,i,o):Buffer.from(t.body),c=Ho(s),u=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}${t.key.replace(/^\/+/,"")}`,a=t.contentType??"application/octet-stream",p={"ts-cloud-format":"v1","ts-cloud-sha256":c.slice(7),"ts-cloud-encrypted":i?"true":"false"};if(t.resume&&t.resume.key!==u)throw Error("Multipart checkpoint does not match the requested backup key.");if(t.resume&&i&&!t.resume.encryptionIv)throw Error("Encrypted multipart checkpoint has no resumable envelope state.");if(t.resume&&i&&t.resume.plaintextChecksum!==n)throw Error("Encrypted multipart checkpoint does not match the backup payload.");if(s.length<this.multipartThreshold)await r.putObject({bucket:e.bucket,key:u,body:s,contentType:a,metadata:p});else{let f=t.resume?void 0:await r.createMultipartUpload(e.bucket,u,{contentType:a,metadata:p}),y=t.resume??{uploadId:f.UploadId,key:u,parts:[],bytesUploaded:0,encryptionIv:o?.toString("base64url"),plaintextChecksum:n},b=new Map(y.parts.map((T)=>[T.PartNumber,T])),C=Math.ceil(s.length/this.partSize);for(let T=0;T<C;T++){let R=T+1;if(!b.has(R)){let x=T*this.partSize,L=await r.uploadPart(e.bucket,u,y.uploadId,R,s.subarray(x,Math.min(s.length,x+this.partSize)));b.set(R,{PartNumber:R,ETag:L.ETag})}y.parts=[...b.values()].sort((x,L)=>x.PartNumber-L.PartNumber),y.bytesUploaded=Math.min(s.length,R*this.partSize),t.checkpoint?.(y)}await r.completeMultipartUpload(e.bucket,u,y.uploadId,y.parts)}return{uri:`s3://${e.bucket}/${u}`,key:u,sizeBytes:s.length,checksum:c,manifest:{format:"ts-cloud-backup-v1",encrypted:!!i,plaintextChecksum:n,storageChecksum:c,contentType:a}}}async download(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=await r.getObjectBytes(e.bucket,t.key),i=Buffer.from(n.body);if(Ho(i)!==t.checksum)throw Error("Backup checksum verification failed; object is corrupt.");let o=t.manifest.encrypted?tv(i,await this.secrets.resolve(e.encryptionKeyRef)):i;if(Ho(o)!==t.manifest.plaintextChecksum)throw Error("Backup plaintext checksum verification failed.");return o}async abortPartial(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).abortMultipartUpload(e.bucket,t.key,t.uploadId)}async delete(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).deleteObject(e.bucket,t)}}import{createHash as nv}from"node:crypto";var iv=(e)=>`sha256:${nv("sha256").update(e).digest("hex")}`;class Go{store;queue;now;constructor(e,t,r=()=>new Date){this.store=e;this.queue=t;this.now=r}enqueueBackup(e,t=this.now().toISOString(),r){if(!e.enabled)throw Error("Backup policy is disabled.");let n=this.store.createJob({projectId:e.projectId,policyId:e.id,kind:"backup",status:"queued",idempotencyKey:`backup:${e.id}:${t}`,target:{scheduledFor:t},cancellability:"checkpoint_only",progress:{phase:"queued"}});if(!n.operationId){let i=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r,kind:"backup.run",input:{backupJobId:n.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`backup-policy:${e.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:14400,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(n.id,{operationId:i.operation.id})}return n}enqueueDue(e=this.now()){return this.store.duePolicies(e).map((t)=>{let r=t.nextRunAt;return this.store.advancePolicy(t.id,r),this.enqueueBackup(t,r)})}enqueueVerification(e){let t=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:"verify",status:"queued",idempotencyKey:`verify:${e.id}:${e.checksum}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!t.operationId){let r=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,kind:"backup.verify",input:{backupJobId:t.id},lockKey:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:2,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(t.id,{operationId:r.operation.id})}return t}planRestore(e,t){if(e.status!=="available")throw Error("Only available recovery points can be restored.");if(e.verificationState!=="verified")throw Error("Restore requires a verified recovery point.");if(t.mode==="in_place"){if(!t.recentAuth)throw Error("In-place restore requires recent authentication.");if(t.confirm!==t.targetName)throw Error(`Type ${t.targetName} to confirm in-place restore.`);if(!t.downtimeAcknowledged)throw Error("In-place restore requires downtime acknowledgement.");let r=t.safetyBackupId?this.store.getRecoveryPoint(t.safetyBackupId):void 0;if(!r||r.id===e.id||r.status!=="available"||r.verificationState!=="verified"||r.resourceId!==e.resourceId||r.dataServiceId!==e.dataServiceId)throw Error("In-place restore requires a distinct verified safety backup for the same target.")}return{point:e,mode:t.mode,target:{...t.target,inPlace:t.mode==="in_place",restoreMode:t.mode},warnings:t.mode==="in_place"?["The target is locked against deployments and backup work.","Downtime and data replacement are expected.","Provider cancellation may stop only at a checkpoint."]:["An isolated target is created and health-validated before cleanup."]}}enqueueRestore(e,t){let r=this.planRestore(e,t),n=t.drill?"drill":"restore",i=iv(JSON.stringify({point:e.id,mode:t.mode,target:t.target,safety:t.safetyBackupId,drill:!!t.drill})),o=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:n,status:"queued",idempotencyKey:`${n}:${i}`,target:r.target,restoreMode:r.mode,cancellability:"checkpoint_only",safetyBackupId:t.safetyBackupId,progress:{phase:"queued",warnings:r.warnings}});if(!o.operationId){let s=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,actorId:t.actorId,kind:t.drill?"backup.drill":"backup.restore",input:{backupJobId:o.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:1,timeoutSeconds:14400,retryClasses:[],resumePolicy:"fail"});return this.store.updateJob(o.id,{operationId:s.operation.id})}return o}enqueueRetention(e=this.now()){return this.store.retentionCandidates(e).map((t)=>{let r=this.store.createJob({projectId:t.projectId,policyId:t.policyId,recoveryPointId:t.id,kind:"cleanup",status:"queued",idempotencyKey:`cleanup:${t.id}:${t.expiresAt}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!r.operationId){let n=this.queue.enqueue({projectId:t.projectId,resourceId:t.resourceId,kind:"backup.cleanup",input:{backupJobId:r.id},lockKey:`recovery-point:${t.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(r.id,{operationId:n.operation.id})}return r})}}function Lp(e){let t=e.now??(()=>new Date),r=new Go(e.store,e.queue,t),n=(c)=>{let u=c.recoveryPointId?e.store.getRecoveryPoint(c.recoveryPointId):void 0,a=c.policyId?e.store.getPolicy(c.policyId):u?.policyId?e.store.getPolicy(u.policyId):void 0;if(!a)throw Error("Backup policy was not found.");let p=e.store.getDestination(u?.destinationId??a.destinationId),f=e.resolveSource(a);if(!p)throw Error("Backup destination was not found.");if(!f)throw Error(`No ${a.resourceKind} backup adapter is configured.`);return{point:u,policy:a,destination:p,source:f}},i=(c)=>{let u=c.operation.input,a=e.store.getJob(String(u.backupJobId??""));if(!a)throw Error("Backup job was not found.");return e.store.updateJob(a.id,{status:"running",startedAt:a.startedAt??t().toISOString(),progress:{...a.progress,phase:"running"}}),a},o=(c,u)=>{let a=e.store.getJob(c.id)??c;e.store.updateJob(c.id,{status:"failed",finishedAt:t().toISOString(),error:u instanceof Error?u.message:String(u),progress:{...a.progress,phase:"failed"}})};return{"backup.run":async(c)=>{let u=i(c);try{let{policy:a,destination:p,source:f}=n(u),y=await f.create(a,c),b=e.resolveDestination(p),C=y.mode==="object"?await(async()=>{if(!b)throw Error("Backup destination adapter is not configured.");let L=e.store.getJob(u.id)?.progress,P=L?.multipart,G=P&&typeof P==="object"&&!Array.isArray(P)&&typeof P.uploadId==="string"&&typeof P.key==="string"&&Array.isArray(P.parts)?P:void 0;return b.upload(p,{key:y.key,body:y.body,contentType:y.contentType,resume:G,checkpoint:(ae)=>{c.checkpoint("uploading",`Uploaded ${Number(ae.bytesUploaded??0)} backup bytes.`),e.store.updateJob(u.id,{progress:{phase:"uploading",multipart:{...ae}}})}})})():{uri:y.uri,key:y.uri,sizeBytes:y.sizeBytes,checksum:y.checksum,manifest:{format:"ts-cloud-backup-v1",encrypted:!1,plaintextChecksum:y.checksum,storageChecksum:y.checksum,contentType:"application/provider-snapshot"}},T=a.retention.expireAfterDays?new Date(t().getTime()+a.retention.expireAfterDays*86400000).toISOString():void 0,R=e.store.getJob(u.id)?.startedAt,x=e.store.createRecoveryPoint({projectId:a.projectId,policyId:a.id,destinationId:p.id,resourceId:a.resourceId,dataServiceId:a.dataServiceId,backupJobId:u.id,kind:a.resourceKind,pointInTime:t().toISOString(),uri:C.uri,sizeBytes:C.sizeBytes,checksum:C.checksum,manifest:{...y.manifest,...C.manifest,storageKey:C.key},toolVersion:y.toolVersion,engineVersion:y.engineVersion,expiresAt:T,lockedUntil:p.immutability.defaultRetentionDays?new Date(t().getTime()+p.immutability.defaultRetentionDays*86400000).toISOString():void 0,held:!1,pinned:!1,status:"available",verificationState:"unverified",durationMs:Math.max(0,t().getTime()-new Date(R??t().toISOString()).getTime())});if(y.mode==="external"&&p.provider==="aws_backup")e.store.recordDestinationTest(p.id,{ok:!0});return e.store.updateJob(u.id,{status:"succeeded",recoveryPointId:x.id,finishedAt:t().toISOString(),progress:{phase:"stored",recoveryPointId:x.id}}),r.enqueueVerification(x),{backupJobId:u.id,recoveryPointId:x.id}}catch(a){let p=e.store.getJob(u.id),f=p?.progress.multipart,y=(()=>{try{return n(u)}catch{return}})();if(y?.destination.provider==="aws_backup")e.store.recordDestinationTest(y.destination.id,{ok:!1,error:a instanceof Error?a.message:String(a)});let b=!1;if(f&&typeof f==="object"&&!Array.isArray(f)&&y){let C=e.resolveDestination(y.destination);if(b=!0,C?.abortPartial)try{await C.abortPartial(y.destination,f),b=!1,e.store.updateJob(u.id,{progress:{...p.progress,partialCleanup:"aborted"}})}catch{e.store.updateJob(u.id,{progress:{...p.progress,partialCleanup:"required"}})}}if(b)e.store.updateJob(u.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:a instanceof Error?a.message:String(a),progress:{...e.store.getJob(u.id)?.progress??{},phase:"cleanup_required"}});else o(u,a);throw a}},"backup.verify":async(c)=>{let u=i(c);try{let{point:a,destination:p,source:f}=n(u);if(!a)throw Error("Recovery point was not found.");e.store.updateRecoveryPoint(a.id,{verificationState:"verifying"});let y;if(a.uri.startsWith("s3:")){let b=e.resolveDestination(p);if(!b)throw Error("Backup destination adapter is not configured.");let C=await b.download(p,{key:String(a.manifest.storageKey??""),checksum:a.checksum,manifest:a.manifest}),T=f.verify?await f.verify(a,C,c):{};y={bytes:C.length,checksum:a.checksum,...T}}else if(f.verifyExternal)y=await f.verifyExternal(a,c);else throw Error("External recovery point verification is not supported.");return e.store.updateRecoveryPoint(a.id,{verificationState:"verified",verifiedAt:t().toISOString(),manifest:{...a.manifest,verification:y}}),e.store.updateJob(u.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"verified",evidence:y}}),{backupJobId:u.id,recoveryPointId:a.id,evidence:y}}catch(a){if(u.recoveryPointId)e.store.updateRecoveryPoint(u.recoveryPointId,{verificationState:/checksum|corrupt|authentic/i.test(a instanceof Error?a.message:String(a))?"corrupt":"failed"});throw o(u,a),a}},"backup.restore":async(c)=>s(c,!1),"backup.drill":async(c)=>s(c,!0),"backup.cleanup":async(c)=>{let u=i(c);try{let{point:a,destination:p,source:f}=n(u);if(!a)throw Error("Recovery point was not found.");if(!e.store.retentionCandidates(t()).some((y)=>y.id===a.id))throw Error("Recovery point is held, pinned, locked, or in active use.");if(e.store.updateRecoveryPoint(a.id,{status:"deleting"}),a.uri.startsWith("s3:")){let y=e.resolveDestination(p);if(!y)throw Error("Destination cleanup is unavailable.");await y.delete(p,String(a.manifest.storageKey??""))}else if(f.deleteExternal)await f.deleteExternal(a,c);else throw Error("External recovery point cleanup is unavailable.");return e.store.updateRecoveryPoint(a.id,{status:"deleted"}),e.store.updateJob(u.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"deleted"}}),{backupJobId:u.id,recoveryPointId:a.id,deleted:!0}}catch(a){throw o(u,a),a}}};async function s(c,u){let a=i(c);try{let{point:p,policy:f,destination:y,source:b}=n(a);if(!p)throw Error("Recovery point was not found.");if(u&&!b.cleanup)throw Error("This backup source cannot safely clean a recovery drill target.");let C=p.uri.startsWith("s3:")?e.resolveDestination(y):void 0,T=C?await C.download(y,{key:String(p.manifest.storageKey??""),checksum:p.checksum,manifest:p.manifest}):void 0,R=await b.restore(p,T,a.target,c),x=b.validateHealth?await b.validateHealth({...a.target,...R},c):{healthy:!0,mode:"adapter"},L=e.validateHealth?await e.validateHealth(f,a.target):{healthy:!0,mode:"not_configured"},P={...x,healthy:x.healthy===!0&&L.healthy===!0,configured:L};if(P.healthy!==!0)throw Error("Restored target did not pass its configured health check.");if(u&&b.cleanup)await b.cleanup({...a.target,provider:p.manifest.provider??null},c);return e.store.updateJob(a.id,{status:"succeeded",finishedAt:t().toISOString(),healthResult:P,progress:{phase:u?"drill_cleaned":"restored",restored:R}}),{backupJobId:a.id,recoveryPointId:p.id,restored:R,health:P,cleaned:u}}catch(p){let f=(()=>{try{return n(a)}catch{return}})(),y=p instanceof Error?p.message:String(p),b=!1;if(u&&f?.source.cleanup)try{await f.source.cleanup({...a.target,provider:f.point?.manifest.provider??null},c)}catch{b=!0}if(b)e.store.updateJob(a.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:y,progress:{...a.progress,phase:"cleanup_required"}});else o(a,p);throw p}}}import{createHash as ov}from"node:crypto";var sv=(e)=>`sha256:${ov("sha256").update(e).digest("hex")}`;class Ic{dataServices;client;constructor(e,t=new Sn){this.dataServices=e;this.client=t}service(e){let t=e.dataServiceId?this.dataServices.get(e.dataServiceId):void 0;if(!t||!["aws_rds","aws_aurora"].includes(t.provider))throw Error("Managed database backup policy requires an RDS or Aurora data service.");return t}async waitForSnapshot(e,t,r){for(;;){r.throwIfCancellationRequested?.(),r.heartbeat?.();let n=e==="aws_aurora"?(await this.client.describeDBClusterSnapshots({DBClusterSnapshotIdentifier:t})).DBClusterSnapshots[0]:(await this.client.describeDBSnapshots({DBSnapshotIdentifier:t})).DBSnapshots?.[0];if(!n)throw Error("Provider snapshot was not found.");let i=n,o=String(i.Status??i.DBSnapshotStatus??"unknown");if(r.checkpoint?.("provider_snapshot",`Database snapshot ${t} is ${o}.`),o==="available")return i;if(["deleted","deleting","failed"].includes(o))throw Error(`Provider snapshot ${t} failed with state ${o}.`);await Bun.sleep(5000)}}async create(e,t){let r=this.service(e),n=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,20),i=`${r.placement.slice(0,42).replace(/-+$/,"")}-${n}`;if(r.provider==="aws_aurora")await this.client.createDBClusterSnapshot(r.placement,i);else await this.client.createDBSnapshot({DBInstanceIdentifier:r.placement,DBSnapshotIdentifier:i});await this.waitForSnapshot(r.provider,i,t);let o=`${r.provider}:${r.placement}:${i}`;return{mode:"external",uri:`aws-backup:${o}`,checksum:sv(o),sizeBytes:0,manifest:{provider:r.provider,sourceId:r.placement,snapshotId:i,plan:r.plan,engine:r.engine},engineVersion:r.engineVersion,toolVersion:"aws-rds-api-2014-10-31"}}async verifyExternal(e,t){let r=String(e.manifest.snapshotId??""),n=String(e.manifest.provider??"");if(!r)throw Error("Snapshot recovery point has no snapshot ID.");let i=await this.waitForSnapshot(n,r,t),o=String(i.Status??i.DBSnapshotStatus??"unknown");return{snapshotId:r,status:o,encrypted:i.Encrypted??i.StorageEncrypted??!0}}async restore(e,t,r,n){let i=String(r.targetId??""),o=String(e.manifest.snapshotId??""),s=String(e.manifest.provider??"");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(i))throw Error("Managed restore requires a valid distinct targetId.");if(i===e.manifest.sourceId)throw Error("Managed restore target must differ from its source.");if(s==="aws_aurora"){let c=e.manifest.engine==="postgres"?"aurora-postgresql":"aurora-mysql";await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:o,Engine:c,EngineVersion:e.engineVersion,DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Number(r.minCapacity)||0.5,MaxCapacity:Number(r.maxCapacity)||4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:String(r.plan??e.manifest.plan??"db.serverless"),Engine:c,PubliclyAccessible:!1})}else await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:i,DBSnapshotIdentifier:o,DBInstanceClass:String(r.plan??e.manifest.plan??""),PubliclyAccessible:!1,DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud-restore"}]});return{targetId:i,provider:s,status:"creating",isolated:!0}}async validateHealth(e,t){let r=String(e.targetId??""),n=String(e.provider??"");for(;;){t.throwIfCancellationRequested?.(),t.heartbeat?.();let i=n==="aws_aurora"?(await this.client.describeDBClusters({DBClusterIdentifier:r})).DBClusters?.[0]:(await this.client.describeDBInstances({DBInstanceIdentifier:r})).DBInstances?.[0];if(!i)throw Error("Restored managed database was not found.");let o=String(i.Status??i.DBInstanceStatus??"unknown");if(t.checkpoint?.("provider_restore",`Restored database ${r} is ${o}.`),o==="available")return{healthy:!0,targetId:r,provider:n,status:o};if(["deleted","deleting","failed","incompatible-restore"].includes(o))throw Error(`Restored managed database ${r} failed with state ${o}.`);await Bun.sleep(5000)}}async cleanup(e,t){let r=String(e.targetId??""),n=String(e.provider??"");if(!r)throw Error("Restore cleanup target is required.");if(n==="aws_aurora")await this.client.deleteDBInstance({DBInstanceIdentifier:`${r}-writer-1`,SkipFinalSnapshot:!0}),await this.client.modifyDBCluster({DBClusterIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(r);else await this.client.modifyDBInstance({DBInstanceIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:r,SkipFinalSnapshot:!0,DeleteAutomatedBackups:!0})}async deleteExternal(e,t){let r=String(e.manifest.snapshotId??"");if(e.manifest.provider==="aws_aurora")await this.client.deleteDBClusterSnapshot(r);else await this.client.deleteDBSnapshot(r)}}var ut=(e,t="none",r=!1)=>({supported:!0,downtime:t,destructive:r,explanation:e}),Ze=(e)=>({supported:!1,downtime:"none",destructive:!1,explanation:e});function Fi(e,t){let r=["aws_rds","aws_aurora","aws_elasticache"].includes(t),n=["server","container"].includes(t),i=["postgres","mysql","mariadb"].includes(e),o=e==="redis",s={};return s.create=t==="external"?Ze("External services can be adopted as read-only inventory."):ut(r?"Provision through the provider API.":"Provision through the owning runtime driver.","possible"),s.observe=t==="external"?Ze("External observation requires a configured provider adapter."):ut("Provider/runtime health and endpoint metadata are observable."),s.connect=ut("Connection guidance uses secret references and never returns a password by default."),s.backup=i&&(r||n)?ut(r?"Create a provider snapshot.":"Create a consistent engine-native dump.","possible"):Ze("This cache path is not a durable backup source."),s.restore=r&&i?ut("Restore creates a reviewed provider target.","required",!0):Ze("Restore requires a configured provider restore runner."),s.restart=t==="external"?Ze("External restart requires a configured provider adapter."):ut(r?"Provider restart/failover semantics apply.":"Restart the owning service unit.","required"),s.resize=t==="aws_elasticache"?Ze("ElastiCache resizing requires a replication-group migration runner."):r?ut("Provider plan/storage modification may enter a maintenance window.","possible"):n?ut("Edit host/container resources and reconcile.","required"):Ze("External resize requires a configured provider adapter."),s.version=n?Ze("Runtime version upgrades require an explicit image migration runner."):r&&t!=="aws_elasticache"?ut(i?"Major versions require compatibility preflight and backup.":"Engine upgrades require a maintenance window.","required"):Ze("External upgrades require a configured provider adapter."),s.rotate=t==="aws_elasticache"||t==="external"||n&&!i&&!o?Ze("Credential rotation is not available for this provider/engine path."):ut("Rotate through the secret backend, update the engine, then flag dependent releases."),s.expose=n?Ze("Direct container publishing is refused; use a reviewed firewall and proxy policy."):t==="aws_rds"?ut("Exposure is reconciled through security groups; public access defaults off."):Ze("Exposure changes require a provider-specific network runner."),s.delete=t==="external"?Ze("External deletion requires a configured provider adapter."):ut(r?"Final snapshot is supported where the provider allows it.":"A final engine backup is required unless explicitly retained.","required",!0),s.logs=n?ut("Read bounded service logs from the runtime."):Ze("Provider log export is not configured for this adapter."),s.slow_queries=n&&i?ut("Read bounded runtime logs after engine slow-query logging is enabled."):Ze("A slow-query log runner is not configured for this provider."),s.users=n&&i?ut("Logical users can be listed; creation requires a referenced secondary credential."):Ze("User management requires an engine connection runner."),s.databases=n&&i?ut("Logical databases can be listed, created, and confirmation-gated for deletion."):Ze("Logical database management requires an engine connection runner."),{actions:s,endpointTypes:r?["internal","external","tunnel"]:["internal","tunnel"],metrics:o?["connections","memory","evictions","hit_rate","latency"]:["connections","cpu","storage","read_latency","write_latency","iops"]}}var Qn=(e)=>e==null?void 0:String(e),Qo=(e)=>Number(e)===1,Ko=(e)=>{try{return JSON.parse(String(e))}catch{return{}}};function Bp(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Qn(e.environment_id),resourceId:Qn(e.resource_id),name:String(e.name),engine:String(e.engine),provider:String(e.provider),placement:String(e.placement),engineVersion:Qn(e.engine_version),plan:String(e.plan),storageGb:e.storage_gb==null?void 0:Number(e.storage_gb),highAvailability:Qo(e.high_availability),publicExposure:Qo(e.public_exposure),allowedCidrs:Ko(e.allowed_cidrs),desiredState:Ko(e.desired_state),observedState:Ko(e.observed_state),capabilities:Ko(e.capabilities),credentialRef:Qn(e.credential_ref),status:String(e.status),origin:String(e.origin),managementEnabled:Qo(e.management_enabled),ownerActorId:Qn(e.owner_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Cc{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}create(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Data service names must be 2-63 lowercase letters, numbers, or dashes.");if(e.publicExposure&&(!e.allowedCidrs.length||e.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");let t=crypto.randomUUID(),r=this.now().toISOString(),n=Fi(e.engine,e.provider);return this.controlPlane.database.run("INSERT INTO data_services (id,organization_id,project_id,environment_id,resource_id,name,engine,provider,placement,engine_version,plan,storage_gb,high_availability,public_exposure,allowed_cidrs,desired_state,observed_state,capabilities,credential_ref,status,origin,management_enabled,owner_actor_id,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.engine,e.provider,e.placement,e.engineVersion??null,e.plan,e.storageGb??null,e.highAvailability?1:0,e.publicExposure?1:0,JSON.stringify(e.allowedCidrs),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),JSON.stringify(n),e.credentialRef??null,e.status,e.origin,e.managementEnabled?1:0,e.ownerActorId??null,1,r,r]),this.get(t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM data_services WHERE id=?").get(e);return t?Bp(t):void 0}list(e,t){return this.controlPlane.database.query(`SELECT * FROM data_services WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(Bp)}update(e,t,r){let n=this.get(e);if(!n)throw Error("Data service was not found.");if(n.version!==t)throw Error("Data service changed; refresh before retrying.");let i={...n,...r};if(i.publicExposure&&(!i.allowedCidrs.length||i.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");if(this.controlPlane.database.run("UPDATE data_services SET plan=?,storage_gb=?,engine_version=?,high_availability=?,public_exposure=?,allowed_cidrs=?,desired_state=?,observed_state=?,status=?,management_enabled=?,credential_ref=?,version=version+1,updated_at=? WHERE id=? AND version=?",[i.plan,i.storageGb??null,i.engineVersion??null,i.highAvailability?1:0,i.publicExposure?1:0,JSON.stringify(i.allowedCidrs),JSON.stringify(i.desiredState),JSON.stringify(i.observedState),i.status,i.managementEnabled?1:0,i.credentialRef??null,this.now().toISOString(),e,t]).changes!==1)throw Error("Data service changed; refresh before retrying.");return this.get(e)}credential(e){let t=this.controlPlane.database.query("SELECT * FROM data_service_credentials WHERE service_id=? ORDER BY version DESC LIMIT 1").get(e);return t?{id:String(t.id),serviceId:String(t.service_id),username:String(t.username),secretRef:String(t.secret_ref),version:Number(t.version),createdAt:String(t.created_at),rotatedAt:Qn(t.rotated_at)}:void 0}saveCredential(e,t,r){let n=this.credential(e),i=n?.id??crypto.randomUUID(),o=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_credentials (id,service_id,username,secret_ref,version,created_at,rotated_at) VALUES (?,?,?,?,?,?,?) ON CONFLICT(service_id,username) DO UPDATE SET secret_ref=excluded.secret_ref,version=data_service_credentials.version+1,rotated_at=excluded.rotated_at",[i,e,t,r,n?.version??1,n?.createdAt??o,n?o:null]),this.credential(e)}addDependency(e){let t=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_dependencies (service_id,resource_id,secret_ref,requires_redeploy,created_at) VALUES (?,?,?,?,?) ON CONFLICT(service_id,resource_id) DO UPDATE SET secret_ref=excluded.secret_ref,requires_redeploy=excluded.requires_redeploy",[e.serviceId,e.resourceId,e.secretRef,e.requiresRedeploy?1:0,t]),{...e,createdAt:t}}dependencies(e){return this.controlPlane.database.query("SELECT * FROM data_service_dependencies WHERE service_id=? ORDER BY resource_id").all(e).map((t)=>({serviceId:String(t.service_id),resourceId:String(t.resource_id),secretRef:String(t.secret_ref),requiresRedeploy:Qo(t.requires_redeploy),createdAt:String(t.created_at)}))}removeDependency(e,t){return this.controlPlane.database.run("DELETE FROM data_service_dependencies WHERE service_id=? AND resource_id=?",[e,t]).changes===1}remove(e){this.controlPlane.database.run("DELETE FROM data_services WHERE id=?",[e])}}function jp(){let t=crypto.getRandomValues(new Uint8Array(40));return Array.from(t,(r)=>"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+="[r%69]).join("")}function Fp(e,t){return t.map((r)=>{let n=r.type==="tunnel"?"127.0.0.1":r.host,i=e.engine==="redis"?`redis-cli -h ${n} -p ${r.port}${r.tls?" --tls":""}`:e.engine==="postgres"?`psql "host=${n} port=${r.port} dbname=${r.database??"postgres"} sslmode=${r.tls?"require":"disable"}"`:e.engine==="mongodb"?`mongosh "mongodb://${n}:${r.port}/${r.database??"admin"}${r.tls?"?tls=true":""}"`:e.engine==="libsql"?`turso db shell ${r.tls?"https":"http"}://${n}:${r.port}`:`mysql --host=${n} --port=${r.port} --database=${r.database??"mysql"} --ssl-mode=${r.tls?"REQUIRED":"DISABLED"}`;return{type:r.type,command:i,secretRef:e.credentialRef}})}class Yo{store;queue;secrets;constructor(e,t,r){this.store=e;this.queue=t;this.secrets=r}async create(e){let t,r;if(e.provider!=="aws_elasticache"){let n=e.username??"app",i=jp();r=`secret://data-services/${e.projectId}/${e.name}/${n}`,await this.secrets.put(r,i),t={username:n,password:i,secretRef:r}}try{let n=this.store.create({...e,credentialRef:r,status:"planning"});if(t)this.store.saveCredential(n.id,t.username,t.secretRef);let i=this.enqueue(n,"create",{});return{service:n,credential:t,operationId:i}}catch(n){if(r)await this.secrets.remove(r);throw n}}plan(e,t,r={}){let n=e.capabilities.actions[t],i=t==="version"&&String(r.engineVersion??"").split(".")[0]!==String(e.engineVersion??"").split(".")[0];return{service:e,action:t,capability:n,changes:r,preflight:{backupRequired:["delete","restore"].includes(t)||i,compatibilityRequired:i,typedConfirmation:n.destructive?e.name:void 0,retentionChoiceRequired:t==="delete"},warnings:[...n.downtime!=="none"?[`Downtime is ${n.downtime}.`]:[],...e.origin==="adopted"&&!e.managementEnabled?["Adopted resource is read-only until management is explicitly enabled."]:[]]}}enqueue(e,t,r,n){let i=this.plan(e,t,r);if(!i.capability.supported)throw Error(i.capability.explanation);if(e.origin==="adopted"&&!e.managementEnabled&&t!=="observe")throw Error("Adopted resources remain read-only until management is explicitly enabled.");if(i.preflight.typedConfirmation&&r.confirm!==i.preflight.typedConfirmation)throw Error(`Type ${i.preflight.typedConfirmation} to confirm ${t}.`);if(i.preflight.retentionChoiceRequired&&!["final_backup","retain"].includes(String(r.retention??"")))throw Error("Deletion requires retention final_backup or retain.");if(i.preflight.compatibilityRequired&&(r.compatibilityReviewed!==!0||!r.backupId))throw Error("Major version changes require compatibilityReviewed=true and a backupId.");if(t==="restore"){let o=String(r.backupId??""),s=String(r.targetId??"");if(!o||!s)throw Error("Restore requires both backupId and targetId.");if(s===e.placement)throw Error("Restore targetId must differ from the source placement.");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(s))throw Error("Restore targetId must be 2-63 lowercase letters, numbers, or dashes.")}return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:n,kind:"data_service.action",input:{serviceId:e.id,action:t,...r},lockKey:`data-service:${e.id}`,providerKey:e.provider,maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"}).operation.id}async rotate(e,t,r){let n=this.store.credential(e.id);if(!n)throw Error("Data service credential metadata was not found.");let i=jp(),o=`${n.secretRef}/v${n.version+1}`;await this.secrets.put(o,i);try{return await t.action(e,"rotate",{username:n.username,secretRef:o},i,r),this.store.saveCredential(e.id,n.username,o),this.store.update(e.id,e.version,{credentialRef:o}),{credential:{username:n.username,password:i,secretRef:o},dependencies:this.store.dependencies(e.id).filter((s)=>s.requiresRedeploy).map((s)=>s.resourceId)}}catch(s){throw await this.secrets.remove(o),s}}}function Up(e){return{"data_service.action":async(t)=>{let r=t.operation.input,n=e.store.get(String(r.serviceId??"")),i=String(r.action??"");if(!n)throw Error("Data service was not found.");let o=e.resolveAdapter(n);if(!o||o.provider!==n.provider||!o.engines.includes(n.engine))throw Error(`No ${n.provider}/${n.engine} adapter is configured.`);if(i==="rotate"){let c=await new Yo(e.store,new xe(e.store.controlPlane),e.secrets).rotate(n,o,t);return{serviceId:n.id,action:i,username:c.credential.username,secretRef:c.credential.secretRef,dependencies:c.dependencies}}let s=n.credentialRef?await e.secrets.resolve(n.credentialRef):void 0;try{let c=i==="observe"?await o.observe(n):i==="create"?await o.apply(n,s,t):await o.action(n,i,r,s,t),u=e.store.get(n.id);return e.store.update(n.id,u.version,{observedState:c,status:i==="delete"?r.retention==="retain"?"retained":"deleting":"available"}),{serviceId:n.id,action:i,observed:c}}catch(c){let u=e.store.get(n.id);if(e.store.update(n.id,u.version,{status:"failed",observedState:{...u.observedState,error:c instanceof Error?c.message:String(c)}}),/temporar|timeout|unavailable|throttl/i.test(c instanceof Error?c.message:String(c)))throw new Vo(c instanceof Error?c.message:String(c),"provider_transient");throw c}}}}class Yn{transport;constructor(e){this.transport=e}observe(e){return this.transport.observe(e.placement)}apply(e,t){return this.transport.apply({id:e.placement,name:e.name,engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,storageGb:e.storageGb??null,highAvailability:e.highAvailability,publicExposure:e.publicExposure,allowedCidrs:e.allowedCidrs,username:e.desiredState.username??"app",desiredState:e.desiredState},t)}action(e,t,r,n,i){return this.transport.execute(e.placement,t,{engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,desiredState:e.desiredState,...r},n,i)}}class Ec extends Yn{provider="aws_rds";engines=["postgres","mysql","mariadb"]}class Tc extends Yn{provider="aws_aurora";engines=["postgres","mysql"]}class Ac extends Yn{provider="aws_elasticache";engines=["redis"]}class kc extends Yn{provider="server";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}class Rc extends Yn{provider="container";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}var es=(e,t)=>{let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)},_e=(e,t,r)=>{let n=es(e,t);return n==null?r:String(n)},Ct=(e,t)=>{let r=es(e,t);return r==null?void 0:Number(r)},Kr=(e,t)=>{let r=es(e,t);return r==null?void 0:r===!0||r==="true"},Xn=(e,t)=>{let r=es(e,t);return Array.isArray(r)?r.map(String):[]},Zo=(e,t)=>_e(t,"snapshotId")??`${e}-final-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`;function Xo(e){if(!e)throw Error("RDS instance was not found.");return{providerId:e.DBInstanceIdentifier??null,status:e.DBInstanceStatus??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,plan:e.DBInstanceClass??null,storageGb:e.AllocatedStorage??null,highAvailability:e.MultiAZ??!1,publicExposure:e.PubliclyAccessible??!1,endpoint:e.Endpoint?.Address??null,port:e.Endpoint?.Port??null,username:e.MasterUsername??null,database:e.DBName??null,encrypted:e.StorageEncrypted??!1}}class xc{client;constructor(e=new Sn){this.client=e}async observe(e){return Xo(await this.client.describeDBInstance(e))}async apply(e,t){let r=String(e.id),n=await this.client.createDBInstance({DBInstanceIdentifier:r,DBInstanceClass:String(e.plan),Engine:String(e.engine),MasterUsername:_e(e,"username","app"),MasterUserPassword:t,DBName:_e(e,"database"),AllocatedStorage:Ct(e,"storageGb"),VpcSecurityGroupIds:Xn(e,"securityGroupIds"),DBSubnetGroupName:_e(e,"subnetGroup"),BackupRetentionPeriod:Ct(e,"backupRetentionDays")??7,MultiAZ:Kr(e,"highAvailability"),EngineVersion:_e(e,"engineVersion"),PubliclyAccessible:Kr(e,"publicExposure")??!1,StorageType:_e(e,"storageType","gp3"),StorageEncrypted:!0,KmsKeyId:_e(e,"kmsKeyId"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return Xo(n.DBInstance)}async execute(e,t,r,n,i){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBInstance({DBInstanceIdentifier:e}),{status:"rebooting"};if(t==="backup"){let o=Zo(e,r);return await this.client.createDBSnapshot({DBInstanceIdentifier:e,DBSnapshotIdentifier:o}),{status:"snapshotting",snapshotId:o}}if(t==="restore"){let o=String(r.targetId),s=await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:o,DBSnapshotIdentifier:String(r.backupId),DBInstanceClass:_e(r,"plan"),DBSubnetGroupName:_e(r,"subnetGroup"),MultiAZ:Kr(r,"highAvailability"),PubliclyAccessible:!1,StorageType:_e(r,"storageType"),VpcSecurityGroupIds:Xn(r,"securityGroupIds"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{...Xo(s.DBInstance),sourceId:e,restoreTargetId:o}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let o=Zo(e,r);return await this.client.modifyDBInstance({DBInstanceIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:e,SkipFinalSnapshot:!1,FinalDBSnapshotIdentifier:o,DeleteAutomatedBackups:!1}),{status:"deleting",finalSnapshotId:o}}if(["resize","version","rotate","expose"].includes(t)){let o=await this.client.modifyDBInstance({DBInstanceIdentifier:e,DBInstanceClass:_e(r,"plan"),AllocatedStorage:Ct(r,"storageGb"),MasterUserPassword:t==="rotate"?n:void 0,EngineVersion:_e(r,"engineVersion"),MultiAZ:Kr(r,"highAvailability"),PubliclyAccessible:Kr(r,"publicExposure"),VpcSecurityGroupIds:Xn(r,"securityGroupIds"),ApplyImmediately:Kr(r,"applyImmediately")??!0});return Xo(o.DBInstance)}throw Error(`RDS action ${t} requires an engine connection runner.`)}}function Pc(e){if(!e)throw Error("Aurora cluster was not found.");return{providerId:e.DBClusterIdentifier??null,status:e.Status??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,endpoint:e.Endpoint??null,readerEndpoint:e.ReaderEndpoint??null,port:e.Port??null,username:e.MasterUsername??null,database:e.DatabaseName??null,encrypted:e.StorageEncrypted??!1,highAvailability:e.MultiAZ??!0}}class Dc{client;constructor(e=new Sn){this.client=e}async observe(e){let t=await this.client.describeDBClusters({DBClusterIdentifier:e});return Pc(t.DBClusters?.[0])}async apply(e,t){let r=String(e.id),n=String(e.engine)==="postgres"?"aurora-postgresql":"aurora-mysql";return await this.client.createDBCluster({DBClusterIdentifier:r,Engine:n,EngineVersion:_e(e,"engineVersion"),MasterUsername:_e(e,"username","app"),MasterUserPassword:t,DatabaseName:_e(e,"database"),DBSubnetGroupName:_e(e,"subnetGroup"),VpcSecurityGroupIds:Xn(e,"securityGroupIds"),BackupRetentionPeriod:Ct(e,"backupRetentionDays")??7,StorageEncrypted:!0,KmsKeyId:_e(e,"kmsKeyId"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Ct(e,"minCapacity")??0.5,MaxCapacity:Ct(e,"maxCapacity")??4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${r}-writer-1`,DBClusterIdentifier:r,DBInstanceClass:String(e.plan||"db.serverless"),Engine:n,PubliclyAccessible:Kr(e,"publicExposure")??!1}),{status:"creating",providerId:r}}async execute(e,t,r,n){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBCluster(e),{status:"rebooting"};if(t==="backup"){let i=Zo(e,r);return await this.client.createDBClusterSnapshot(e,i),{status:"snapshotting",snapshotId:i}}if(t==="restore"){let i=String(r.targetId),o=String(r.engine)==="postgres"?"aurora-postgresql":"aurora-mysql",s=await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:String(r.backupId),Engine:o,EngineVersion:_e(r,"engineVersion"),DBSubnetGroupName:_e(r,"subnetGroup"),VpcSecurityGroupIds:Xn(r,"securityGroupIds"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Ct(r,"minCapacity")??0.5,MaxCapacity:Ct(r,"maxCapacity")??4}});return await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:_e(r,"plan","db.serverless"),Engine:o,PubliclyAccessible:!1}),{...Pc(s.DBCluster),sourceId:e,restoreTargetId:i}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let i=Zo(e,r);return await this.client.modifyDBCluster({DBClusterIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(e,i),{status:"deleting",finalSnapshotId:i}}if(["resize","version","rotate"].includes(t)){let i=await this.client.modifyDBCluster({DBClusterIdentifier:e,ServerlessV2ScalingConfiguration:Ct(r,"minCapacity")==null&&Ct(r,"maxCapacity")==null?void 0:{MinCapacity:Ct(r,"minCapacity")??0.5,MaxCapacity:Ct(r,"maxCapacity")??4},EngineVersion:_e(r,"engineVersion"),MasterUserPassword:t==="rotate"?n:void 0,ApplyImmediately:Kr(r,"applyImmediately")??!0});return Pc(i.DBCluster)}throw Error(`Aurora action ${t} requires an engine connection runner.`)}}class Oc{client;constructor(e=new ji){this.client=e}async observe(e){let t=(await this.client.describeCacheClusters(e)).CacheClusters[0];if(!t)throw Error("ElastiCache cluster was not found.");let r=t.CacheNodes?.[0]?.Endpoint;return{providerId:t.CacheClusterId,status:t.CacheClusterStatus,engine:t.Engine,engineVersion:t.EngineVersion,plan:t.CacheNodeType,nodes:t.NumCacheNodes,endpoint:r?.Address??null,port:r?.Port??null}}async apply(e){let t=await this.client.createCacheCluster({cacheClusterId:String(e.id),engine:"redis",cacheNodeType:String(e.plan),numCacheNodes:Ct(e,"nodes")??1,engineVersion:_e(e,"engineVersion"),port:Ct(e,"port"),securityGroupIds:Xn(e,"securityGroupIds"),subnetGroupName:_e(e,"subnetGroup"),tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{providerId:t.CacheCluster.CacheClusterId,status:t.CacheCluster.CacheClusterStatus}}async execute(e,t,r){if(t==="observe")return this.observe(e);if(t==="restart"){let n=(await this.client.describeCacheClusters(e)).CacheClusters[0];return await this.client.rebootCacheCluster(e,n?.CacheNodes?.map((i)=>i.CacheNodeId)??["0001"]),{status:"rebooting"}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};return await this.client.deleteCacheCluster(e),{status:"deleting"}}throw Error(`ElastiCache action ${t} is not supported by this cluster mode.`)}}import{mkdir as av,writeFile as cv}from"node:fs/promises";import{join as dv}from"node:path";async function kt(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t==null?"ignore":"pipe",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).text(),o=new Response(n.stderr).text();if(t!=null)n.stdin.write(t),n.stdin.end();let[s,c,u]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker command failed (${s}): ${u.trim()||c.trim()}`);return{code:s,stdout:c,stderr:u}}class zp{async ensureNetwork(e){if((await kt(["network","inspect",e],void 0,!0)).code!==0)await kt(["network","create","--internal",e])}async seedSecret(e,t){await kt(["volume","create",e]),await kt(["run","--rm","-i","-v",`${e}:/run/target`,"alpine:3.21","sh","-c","umask 077; cat > /run/target/credential"],t)}async removeVolume(e){await kt(["volume","rm",e],void 0,!0)}async inspect(e){let t=await kt(["inspect",e],void 0,!0);if(t.code!==0)return;return JSON.parse(t.stdout)[0]}async run(e){await kt(["run",...e])}async exec(e,t,r){return(await kt(["exec","-i",e,...t],r)).stdout}async update(e,t){await kt(["update",...t,e])}async restart(e){await kt(["restart",e])}async remove(e){await kt(["rm","--force",e],void 0,!0)}async logs(e,t){let r=await kt(["logs","--tail",String(Math.min(2000,Math.max(1,t))),e],void 0,!0);return`${r.stdout}${r.stderr}`.slice(-262144)}async stats(e){let t=await kt(["stats","--no-stream","--format","{{json .}}",e],void 0,!0);if(t.code!==0||!t.stdout.trim())return{};let r=JSON.parse(t.stdout.trim());return{cpuPercent:String(r.CPUPerc??""),memoryUsage:String(r.MemUsage??""),memoryPercent:String(r.MemPerc??""),networkIo:String(r.NetIO??""),blockIo:String(r.BlockIO??""),pids:Number(r.PIDs??0)}}}var uv={postgres:{image:"postgres:17-alpine",port:5432,dataPath:"/var/lib/postgresql/data"},mysql:{image:"mysql:8.4",port:3306,dataPath:"/var/lib/mysql"},mariadb:{image:"mariadb:11.7",port:3306,dataPath:"/var/lib/mysql"},redis:{image:"redis:7.4-alpine",port:6379,dataPath:"/data"},mongodb:{image:"mongo:8.0",port:27017,dataPath:"/data/db"}};function yr(e,t="app"){let r=String(e??t);if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(r))throw Error("Database identifiers must be letters, numbers, or underscores.");return r}function vn(e){if(!/^[a-z0-9][a-z0-9_.-]{1,62}$/i.test(e))throw Error("Runtime placement must be a valid container identifier.");return`tscloud-data-${e.toLowerCase()}`}function lv(e,t){let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)}function Ui(e){return e.Config?.Labels??{}}class Zn{runtime;backupRoot;constructor(e=new zp,t=at(process.cwd(),"backups","data")){this.runtime=e;this.backupRoot=t}async observe(e){let t=vn(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=Ui(r),i=await this.runtime.stats(t),o=r.NetworkSettings?.Ports??{},s=Object.values(o).flat().find(Boolean);return{providerId:t,status:r.State?.Status??"unknown",healthy:r.State?.Health?.Status??null,engine:n["ts-cloud.engine"]??null,engineVersion:n["ts-cloud.engine-version"]??null,username:n["ts-cloud.username"]??null,database:n["ts-cloud.database"]??null,endpoint:s?.HostIp||"127.0.0.1",port:s?.HostPort?Number(s.HostPort):null,image:r.Config?.Image??null,startedAt:r.State?.StartedAt??null,metrics:i}}async apply(e,t){let r=String(e.id),n=vn(r),i=String(e.engine);if(i==="libsql")throw Error("libSQL requires an explicitly configured runtime image.");let o=uv[i];if(!o)throw Error(`Unsupported runtime data engine ${i}.`);if(!t)throw Error(`${i} requires a managed credential.`);if(e.publicExposure===!0)throw Error("Container public exposure requires an external reviewed firewall policy; direct publishing is refused.");let s=yr(e.username),c=yr(lv(e,"database")),u=`${n}-secret`,a=`${n}-data`,p=i==="redis"?`appendonly yes
|
|
46
|
-
protected-mode yes
|
|
47
|
-
requirepass ${t.replaceAll("\\","\\\\").replaceAll(`
|
|
48
|
-
`,"")}
|
|
49
|
-
`:t;await this.runtime.ensureNetwork("ts-cloud-data"),await this.runtime.seedSecret(u,p);let f=["-d","--name",n,"--restart","unless-stopped","--network","ts-cloud-data","--label","managed-by=ts-cloud","--label",`ts-cloud.engine=${i}`,"--label",`ts-cloud.engine-version=${e.engineVersion??""}`,"--label",`ts-cloud.username=${s}`,"--label",`ts-cloud.database=${c}`,"-p",`127.0.0.1:${o.port}:${o.port}`,"-v",`${a}:${o.dataPath}`,"-v",`${u}:/run/ts-cloud-secrets:ro`];if(i==="postgres")f.push("-e",`POSTGRES_USER=${s}`,"-e",`POSTGRES_DB=${c}`,"-e","POSTGRES_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mysql"||i==="mariadb")f.push("-e",`MYSQL_USER=${s}`,"-e",`MYSQL_DATABASE=${c}`,"-e","MYSQL_PASSWORD_FILE=/run/ts-cloud-secrets/credential","-e","MYSQL_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mongodb")f.push("-e",`MONGO_INITDB_ROOT_USERNAME=${s}`,"-e","MONGO_INITDB_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(f.push(o.image),i==="redis")f.push("redis-server","/run/ts-cloud-secrets/credential");return await this.runtime.run(f),{providerId:n,status:"starting",engine:i,endpoint:"127.0.0.1",port:o.port,username:s,database:c}}async exportLogicalBackup(e){let t=vn(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=Ui(r),i=n["ts-cloud.engine"],o=yr(n["ts-cloud.username"]),s=yr(n["ts-cloud.database"]),c;if(i==="postgres")c=await this.runtime.exec(t,["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec pg_dumpall --clean --if-exists -U "$POSTGRES_USER"']);else if(i==="mysql"||i==="mariadb")c=await this.runtime.exec(t,["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysqldump -u root --all-databases --single-transaction --add-drop-database --routines --events --triggers']);else throw Error(`${i} does not support engine-native SQL backups.`);return{body:new TextEncoder().encode(c),engine:i,database:s,username:o,engineVersion:n["ts-cloud.engine-version"]||void 0}}async restoreLogicalBackup(e){let t=vn(e.sourceId),r=vn(e.targetId),n=await this.runtime.inspect(t);if(!n)throw Error(`Data container ${t} was not found.`);let i=Ui(n),o=i["ts-cloud.engine"],s=yr(i["ts-cloud.username"]),c=yr(i["ts-cloud.database"]);if(!["postgres","mysql","mariadb"].includes(o))throw Error(`${o} does not support engine-native SQL restores.`);if(!e.inPlace){if(e.sourceId===e.targetId)throw Error("An isolated restore requires a distinct target identifier.");if(await this.runtime.inspect(r))throw Error(`Restore target ${r} already exists.`);await this.apply({id:e.targetId,engine:o,engineVersion:i["ts-cloud.engine-version"]??"",username:s,database:c,publicExposure:!1},e.credential)}let u=o==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d postgres']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'],a=new TextDecoder("utf-8",{fatal:!0}).decode(e.body),p;for(let f=0;f<30;f++)try{await this.runtime.exec(r,u,a);let y=o==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER" -Atc "SELECT 1"']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root -N -e "SELECT 1"'];if((await this.runtime.exec(r,y)).trim()!=="1")throw Error("Restored database health probe returned an unexpected result.");return{status:"available",providerId:r,engine:o,database:c,username:s,healthy:!0}}catch(y){if(p=y,f<29)await Bun.sleep(1000)}throw p instanceof Error?p:Error("Restored database did not become ready.")}async removeRestoredService(e){let t=vn(e);await this.runtime.remove(t),await this.runtime.removeVolume(`${t}-secret`),await this.runtime.removeVolume(`${t}-data`)}async backup(e,t){let r=await this.exportLogicalBackup(e),{engine:n,database:i,username:o}=r,s=String(t.snapshotId??`${e}-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`);if(!/^[A-Za-z0-9_.-]{2,120}$/.test(s))throw Error("Backup identifier contains unsupported characters.");await av(this.backupRoot,{recursive:!0,mode:448});let c=dv(this.backupRoot,`${s}.sql`);return await cv(c,r.body,{mode:384}),{status:"available",backupId:s,path:c,engine:n,database:i,username:o}}async execute(e,t,r,n){let i=vn(e);if(t==="observe")return this.observe(e);if(t==="backup")return this.backup(e,r);if(t==="restart")return await this.runtime.restart(i),{status:"restarting"};if(t==="logs"||t==="slow_queries")return{logs:await this.runtime.logs(i,Number(r.lines)||500)};if(t==="databases"||t==="users"){let o=await this.runtime.inspect(i);if(!o)throw Error(`Data container ${i} was not found.`);let s=Ui(o),c=s["ts-cloud.engine"],u=yr(s["ts-cloud.username"]),a=String(r.operation??"list");if(!["postgres","mysql","mariadb"].includes(c))throw Error(`${t} is available only for SQL runtime engines.`);if(t==="users"&&a!=="list")throw Error("Creating users requires a referenced secondary credential.");if(a==="list"){let p=c==="postgres"?["sh","-c",`export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER" -Atc '${t==="databases"?"SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname":"SELECT usename FROM pg_user ORDER BY usename"}'`]:["sh","-c",`export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root -N -e '${t==="databases"?"SHOW DATABASES":"SELECT User FROM mysql.user ORDER BY User"}'`],f=await this.runtime.exec(i,p);return{[t]:f.split(`
|
|
50
|
-
`).map((y)=>y.trim()).filter(Boolean)}}if(t==="databases"&&["create","delete"].includes(a)){let p=yr(r.database);if(a==="delete"&&r.confirm!==p)throw Error(`Type ${p} to confirm logical database deletion.`);let f=c==="postgres"?`${a==="create"?"CREATE":"DROP"} DATABASE "${p}";
|
|
51
|
-
`:`${a==="create"?"CREATE":"DROP"} DATABASE \`${p}\`;
|
|
52
|
-
`,y=c==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER"']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'];return await this.runtime.exec(i,y,f),{status:"available",database:p,operation:a}}throw Error(`Unsupported ${t} operation ${a}.`)}if(t==="resize"){let o=[];if(r.memoryMb)o.push("--memory",`${Number(r.memoryMb)}m`);if(r.cpus)o.push("--cpus",String(Number(r.cpus)));if(!o.length)throw Error("Resize requires memoryMb or cpus.");return await this.runtime.update(i,o),{status:"running",memoryMb:r.memoryMb??null,cpus:r.cpus??null}}if(t==="rotate"){if(!n)throw Error("Credential rotation requires a generated secret.");let o=await this.runtime.inspect(i);if(!o)throw Error(`Data container ${i} was not found.`);let s=Ui(o),c=s["ts-cloud.engine"],u=yr(s["ts-cloud.username"]),a=n.replaceAll("'","''").replaceAll(`
|
|
53
|
-
`,"");if(c==="postgres")await this.runtime.exec(i,["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER"'],`ALTER USER "${u}" PASSWORD '${a}';
|
|
54
|
-
`);else if(c==="mysql"||c==="mariadb")await this.runtime.exec(i,["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'],`ALTER USER '${u}'@'%' IDENTIFIED BY '${a}';
|
|
55
|
-
`);else if(c!=="redis")throw Error(`${c} credential rotation requires an engine runner.`);let p=c==="redis"?`appendonly yes
|
|
56
|
-
protected-mode yes
|
|
57
|
-
requirepass ${n.replaceAll("\\","\\\\").replaceAll(`
|
|
58
|
-
`,"")}
|
|
59
|
-
`:n;if(await this.runtime.seedSecret(`${i}-secret`,p),c==="redis")await this.runtime.restart(i);return{status:c==="redis"?"restarting":"running",username:u}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let o=await this.backup(e,r);return await this.runtime.remove(i),await this.runtime.removeVolume(`${i}-secret`),await this.runtime.removeVolume(`${i}-data`),{status:"deleted",finalBackupId:o.backupId??null,backupPath:o.path??null}}if(t==="expose")throw Error("Direct container exposure is refused; use a reviewed firewall and proxy policy.");throw Error(`${t} requires a configured engine lifecycle runner.`)}}import{createCipheriv as pv,createDecipheriv as gv,createHash as Vp,randomBytes as mv}from"node:crypto";class _c{controlPlane;now;key;constructor(e,t,r=()=>new Date){this.controlPlane=e;this.now=r;if(!t)throw Error("Data-service encryption key is required.");this.key=Vp("sha256").update(`ts-cloud:data-services:${t}`).digest()}encrypt(e){let t=mv(12),r=pv("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted data-service secret is unavailable.");try{let o=gv("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}catch{throw Error("Encrypted data-service secret could not be decrypted.")}}async put(e,t){if(!/^secret:\/\/data-services\/[A-Za-z0-9._/-]+$/.test(e))throw Error("Invalid data-service secret reference.");if(!t)throw Error("Data-service secret cannot be empty.");let r=this.now().toISOString();this.controlPlane.database.run("INSERT INTO data_service_secrets (reference,ciphertext,fingerprint,created_at,updated_at) VALUES (?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,updated_at=excluded.updated_at",[e,this.encrypt(t),Vp("sha256").update(t).digest("hex"),r,r])}async resolve(e){let t=this.controlPlane.database.query("SELECT ciphertext FROM data_service_secrets WHERE reference = ?").get(e);if(!t)throw Error("Data-service secret was not found.");return this.decrypt(t.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM data_service_secrets WHERE reference = ?",[e])}}import{existsSync as zi}from"node:fs";import{mkdir as rs,readdir as fv,rename as Nc,rm as ei}from"node:fs/promises";import{relative as hv,resolve as ht,sep as ns}from"node:path";function wn(e,t){if(t==="gzip")return Buffer.from(Bun.gzipSync(Uint8Array.from(e)));if(t==="zstd")return Buffer.from(Bun.zstdCompressSync(Uint8Array.from(e)));return Buffer.from(e)}function br(e,t){if(t==="gzip")return Buffer.from(Bun.gunzipSync(Uint8Array.from(e)));if(t==="zstd")return Buffer.from(Bun.zstdDecompressSync(Uint8Array.from(e)));return Buffer.from(e)}async function $c(e,t){let r=Bun.spawn(["tar",...e],{stdin:t?Buffer.from(t):void 0,stdout:"pipe",stderr:"pipe"}),[n,i,o]=await Promise.all([r.exited,new Response(r.stdout).arrayBuffer(),new Response(r.stderr).text()]);if(n!==0)throw Error(o.trim()||`tar exited with status ${n}.`);return{stdout:Buffer.from(i),stderr:o}}function yv(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!!t&&!t.startsWith("/")&&!t.split("/").includes("..")}class Jp{async create(e,t,r){return(await $c(["-C",e,"-cf","-",...r.map((i)=>`--exclude=${i}`),"--",...t])).stdout}async extract(e,t){await rs(t,{recursive:!0,mode:448}),await $c(["-C",t,"-xf","-"],e)}async inspect(e){let t=await $c(["-tf","-"],e),r=t.stdout.toString().split(`
|
|
60
|
-
`).filter(Boolean);if(r.some((n)=>!yv(n)))throw Error("Backup archive contains an unsafe path.");return{entries:r,bytes:e.byteLength}}}function qp(e,t){if(!t.trim())throw Error("File backup paths cannot be empty.");let r=ht(e,t),n=hv(e,r);if(n===".."||n.startsWith(`..${ns}`)||n==="")throw Error(`File backup path ${t} is outside the project root.`);return n}function ts(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("File restores require a safe target name.");return t}class Mc{runtime;root;restoreRoot;constructor(e,t=new Jp,r=at(e,"restores","files")){this.runtime=t;this.root=ht(e),this.restoreRoot=ht(r)}paths(e){let t=[...new Set(e.includePatterns.map((r)=>qp(this.root,r)))];if(!t.length)throw Error("File backup policies require at least one project-relative path.");for(let r of t)if(!zi(ht(this.root,r)))throw Error(`File backup path ${r} was not found.`);return t.filter((r)=>!t.some((n)=>n!==r&&r.startsWith(`${n}${ns}`)))}async create(e,t){let r=this.paths(e),n=await this.runtime.create(this.root,r,e.excludePatterns),i=await this.runtime.inspect(n),o=e.compression??"none",s=wn(n,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/files/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",manifest:{archive:"tar",compression:o,sourcePaths:r,excluded:e.excludePatterns,entries:i.entries.length},toolVersion:"system-tar"}}async restore(e,t,r,n){if(!t)throw Error("File restore requires an archive payload.");let i=br(t,String(e.manifest.compression??"none"));if(await this.runtime.inspect(i),r.restoreMode==="in_place"){let s=ht(this.restoreRoot,`.staging-${ts(r)}`),c=ht(this.restoreRoot,`.rollback-${ts(r)}`),u=Array.isArray(e.manifest.sourcePaths)?e.manifest.sourcePaths.map(String):[];if(!u.length)throw Error("File recovery point has no source path manifest.");await ei(s,{recursive:!0,force:!0}),await ei(c,{recursive:!0,force:!0}),await this.runtime.extract(i,s),await rs(c,{recursive:!0,mode:448});let a=[];try{for(let p of u){let f=ht(this.root,qp(this.root,p)),y=ht(s,p),b=ht(c,p);if(await rs(ht(b,".."),{recursive:!0}),zi(f))await Nc(f,b);await rs(ht(f,".."),{recursive:!0}),await Nc(y,f),a.push(p)}}catch(p){for(let f of a.reverse()){let y=ht(this.root,f),b=ht(c,f);if(await ei(y,{recursive:!0,force:!0}),zi(b))await Nc(b,y)}throw p}finally{await ei(s,{recursive:!0,force:!0})}return await ei(c,{recursive:!0,force:!0}),{path:this.root,restoredPaths:u,inPlace:!0}}let o=ht(this.restoreRoot,ts(r));if(zi(o))throw Error("The isolated file restore target already exists.");return await this.runtime.extract(i,o),{path:o,isolated:!0}}async verify(e,t,r){let n=br(t,String(e.manifest.compression??"none")),i=await this.runtime.inspect(n);return{archive:"tar",entries:i.entries.length,uncompressedBytes:i.bytes}}async validateHealth(e,t){let r=String(e.path??"");if(!r||!r.startsWith(`${this.restoreRoot}${ns}`)||!zi(r))throw Error("Isolated file restore target was not found.");let n=await fv(r);return{healthy:!0,path:r,topLevelEntries:n.length}}async cleanup(e,t){let r=ts(e),n=ht(this.restoreRoot,r);if(!n.startsWith(`${this.restoreRoot}${ns}`))throw Error("Refusing to clean a file restore outside the restore root.");await ei(n,{recursive:!0,force:!0})}}class Lc{services;secrets;transport;constructor(e,t,r=new Zn){this.services=e;this.secrets=t;this.transport=r}async create(e,t){if(!e.dataServiceId)throw Error("Logical database backups require a data service.");let r=this.services.get(e.dataServiceId);if(!r)throw Error("Logical database service was not found.");if(!["container","server"].includes(r.provider))throw Error("Logical database backups require an on-box data service.");let n=await this.transport.exportLogicalBackup(r.id),i=e.compression??"none",o=wn(n.body,i),s=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/databases/${r.id}/${s}.sql${i==="none"?"":i==="gzip"?".gz":".zst"}`,body:o,contentType:i==="gzip"?"application/gzip":i==="zstd"?"application/zstd":"application/sql",engineVersion:n.engineVersion,toolVersion:"engine-native",manifest:{format:"logical-sql-v1",sourceDataServiceId:r.id,engine:n.engine,database:n.database,username:n.username,compression:i}}}async restore(e,t,r,n){if(!t)throw Error("Logical database backup body is unavailable.");let i=String(e.dataServiceId??e.manifest.sourceDataServiceId??""),o=String(r.dataServiceId??r.targetId??""),s=r.inPlace===!0;if(!i||!o)throw Error("Logical database restore requires source and target identifiers.");if(s&&o!==i)throw Error("An in-place restore must target the source data service.");let c=this.services.get(i);if(!c?.credentialRef)throw Error("Logical database credential reference was not found.");let u=await this.secrets.resolve(c.credentialRef);return this.transport.restoreLogicalBackup({sourceId:i,targetId:o,body:br(t,String(e.manifest.compression??"none")),credential:u,inPlace:s})}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place database restores cannot be cleaned as drills.");let r=String(e.dataServiceId??e.targetId??"");if(!r)throw Error("Database cleanup requires a target identifier.");await this.transport.removeRestoredService(r)}}var Bc=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;async function In(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t?"pipe":"ignore",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).arrayBuffer(),o=new Response(n.stderr).text();if(t)n.stdin.write(t),n.stdin.end();let[s,c,u]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker volume command failed (${s}): ${u.trim()}`);return{code:s,stdout:Buffer.from(c),stderr:u}}class Wp{async exists(e){return(await In(["volume","inspect",e],void 0,!0)).code===0}async export(e){return(await In(["run","--rm","-v",`${e}:/source:ro`,"alpine:3.21","tar","-C","/source","-czf","-","."])).stdout}async import(e,t,r=!1){if(!await this.exists(e))await In(["volume","create",e]);try{if(r)await In(["run","--rm","-v",`${e}:/target`,"alpine:3.21","sh","-c","find /target -mindepth 1 -delete"]);await In(["run","--rm","-i","-v",`${e}:/target`,"alpine:3.21","tar","-C","/target","--no-same-owner","-xzf","-"],t)}catch(n){throw await this.remove(e),n}}async remove(e){await In(["volume","rm",e],void 0,!0)}async probe(e){let t=(await In(["run","--rm","-v",`${e}:/target:ro`,"alpine:3.21","sh","-c",`find /target -mindepth 1 -printf '%s\\n' | awk '{n+=1;b+=$1} END {print n ":" b}'`])).stdout.toString(),[r,n]=t.trim().split(":").map(Number);if(!Number.isFinite(r)||!Number.isFinite(n))throw Error("Restored volume health probe returned invalid output.");return{entries:r,bytes:n}}}class jc{runtime;constructor(e=new Wp){this.runtime=e}async create(e,t){let r=String(e.includePatterns?.[0]??e.resourceId??"");if(!Bc.test(r))throw Error("Volume backups require a valid named-volume resource identifier.");if(!await this.runtime.exists(r))throw Error(`Volume ${r} was not found.`);let n=await this.runtime.export(r),i=Buffer.from(Bun.gunzipSync(Uint8Array.from(n))),o=e.compression??"gzip",s=o==="gzip"?n:wn(i,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/volumes/${r}/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",toolVersion:"alpine-tar",manifest:{format:"docker-volume-tar-v1",archive:"tar",compression:o,sourceVolume:r}}}async restore(e,t,r,n){if(!t)throw Error("Volume backup body is unavailable.");let i=String(e.manifest.sourceVolume??e.resourceId??""),o=String(r.volumeName??r.targetId??"");if(!Bc.test(o))throw Error("Volume restore requires a valid target volume name.");if(o===i&&r.inPlace!==!0)throw Error("An isolated volume restore requires a distinct target.");let s=await this.runtime.exists(o);if(!r.inPlace&&s)throw Error(`Restore target volume ${o} already exists.`);if(r.inPlace===!0&&o!==i)throw Error("An in-place volume restore must target the source volume.");if(r.inPlace===!0&&!s)throw Error("The in-place target volume was not found.");let c=String(e.manifest.compression??"gzip"),u=c==="gzip"?Buffer.from(t):Buffer.from(Bun.gzipSync(Uint8Array.from(br(t,c))));await this.runtime.import(o,u,r.inPlace===!0);let a=await this.runtime.probe(o);return{volumeName:o,healthy:!0,...a}}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place volume restores cannot be cleaned as drills.");let r=String(e.volumeName??e.targetId??"");if(!Bc.test(r))throw Error("Volume cleanup requires a valid target volume name.");await this.runtime.remove(r)}}import{existsSync as Fc}from"node:fs";import{mkdir as bv,readFile as Hp,rm as Sv,writeFile as Gp}from"node:fs/promises";import{basename as Zp,resolve as Qr,sep as Kp}from"node:path";import{Database as vv}from"bun:sqlite";function Qp(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("Control-plane restores require a safe target name.");return t}function Yp(e){let t=JSON.parse(Buffer.from(e).toString());if(t.format!=="ts-cloud-control-plane-v1"||!t.database)throw Error("Control-plane backup archive is invalid.");if(!Array.isArray(t.config)||t.config.some((r)=>Zp(r.name)!==r.name))throw Error("Control-plane backup contains an unsafe config path.");return t}function Xp(e){let t=vv.deserialize(Uint8Array.from(e));try{let r=t.query("PRAGMA integrity_check").get()?.integrity_check??"unknown",n=t.query("SELECT count(*) AS count FROM sqlite_master WHERE type='table'").get()?.count??0;if(r!=="ok")throw Error(`Restored control-plane integrity check failed: ${r}.`);return{integrity:r,tables:n}}finally{t.close()}}class Uc{controlPlane;root;restoreRoot;constructor(e,t,r=at(t,"restores","control-plane")){this.controlPlane=e;this.root=Qr(t),this.restoreRoot=Qr(r)}async create(e,t){let r=e.includePatterns.length?e.includePatterns:["cloud.config.ts"],n=[];for(let u of r){let a=Zp(u),p=Qr(this.root,a);if(a!==u&&u!==`./${a}`)throw Error("Control-plane config paths must be project-root files.");if(Fc(p))n.push({name:a,body:(await Hp(p)).toString("base64")})}let i={format:"ts-cloud-control-plane-v1",createdAt:new Date().toISOString(),database:Buffer.from(this.controlPlane.database.serialize()).toString("base64"),config:n},o=e.compression??"none",s=wn(Buffer.from(JSON.stringify(i)),o),c=String(t.operation?.id??i.createdAt).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/control-plane/${c}.json${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/vnd.ts-cloud.control-plane+json",manifest:{format:i.format,configFiles:n.map((u)=>u.name),sensitive:!0,compression:o},toolVersion:"bun-sqlite-serialize"}}async restore(e,t,r,n){if(!t)throw Error("Control-plane restore requires an archive payload.");if(r.restoreMode==="in_place")throw Error("A live control plane can only be restored into an isolated recovery target.");let i=Yp(br(t,String(e.manifest.compression??"none"))),o=Qr(this.restoreRoot,Qp(r));if(Fc(o))throw Error("The isolated control-plane restore target already exists.");await bv(o,{recursive:!0,mode:448}),await Gp(Qr(o,"control-plane.sqlite"),Buffer.from(i.database,"base64"),{mode:384});for(let s of i.config)await Gp(Qr(o,s.name),Buffer.from(s.body,"base64"),{mode:384});return{path:o,isolated:!0,configFiles:i.config.length}}async verify(e,t,r){let n=Yp(br(t,String(e.manifest.compression??"none")));return{...Xp(Buffer.from(n.database,"base64")),configFiles:n.config.length}}async validateHealth(e,t){let r=String(e.path??""),n=Qr(r,"control-plane.sqlite");if(!r.startsWith(`${this.restoreRoot}${Kp}`)||!Fc(n))throw Error("Isolated control-plane database was not found.");return{healthy:!0,...Xp(await Hp(n))}}async cleanup(e,t){let r=Qr(this.restoreRoot,Qp(e));if(!r.startsWith(`${this.restoreRoot}${Kp}`))throw Error("Refusing to clean a control-plane restore outside the restore root.");await Sv(r,{recursive:!0,force:!0})}}import{createHash as wv}from"node:crypto";function zc(e,t){return e.find((r)=>r.startsWith(`${t}:`))?.slice(t.length+1)}function Iv(e){let t=zc(e.includePatterns,"resource")??e.includePatterns.find((i)=>i.startsWith("arn:")),r=zc(e.includePatterns,"role"),n=zc(e.includePatterns,"vault")??"Default";if(!t?.startsWith("arn:"))throw Error("Infrastructure backups require resource:<arn> in include patterns.");if(!r?.startsWith("arn:"))throw Error("Infrastructure backups require role:<iam-role-arn> in include patterns.");if(!/^[A-Za-z0-9_.-]{2,50}$/.test(n))throw Error("Infrastructure backup vault name is invalid.");return{resourceArn:t,roleArn:r,vaultName:n}}async function Cv(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeBackupJob(t),i=String(n.State??"");if(r.checkpoint("provider_backup",`AWS Backup job ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.RecoveryPointArn)return{recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??0)};if(["ABORTED","EXPIRED","FAILED"].includes(i))throw Error(`AWS Backup job ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}async function Ev(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeRestoreJob(t),i=String(n.Status??"");if(r.checkpoint("provider_restore",`AWS Backup restore ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.CreatedResourceArn)return n.CreatedResourceArn;if(["ABORTED","FAILED"].includes(i))throw Error(`AWS Backup restore ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}class Vc{client;constructor(e=new Bi){this.client=e}async create(e,t){let r=Iv(e),n=String(t.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64),i=await this.client.startBackupJob({BackupVaultName:r.vaultName,ResourceArn:r.resourceArn,IamRoleArn:r.roleArn,IdempotencyToken:n}),o=await Cv(this.client,i.BackupJobId,t),s=`sha256:${wv("sha256").update(o.recoveryPointArn).digest("hex")}`;return{mode:"external",uri:o.recoveryPointArn,checksum:s,sizeBytes:o.sizeBytes,toolVersion:"aws-backup-api",manifest:{provider:"aws_backup",resourceArn:r.resourceArn,roleArn:r.roleArn,vaultName:r.vaultName,providerBackupJobId:i.BackupJobId,recoveryPointArn:o.recoveryPointArn}}}async verifyExternal(e,t){let r=String(e.manifest.providerBackupJobId??""),n=await this.client.describeBackupJob(r);if(n.State!=="COMPLETED"||n.RecoveryPointArn!==e.uri)throw Error(`AWS Backup recovery point verification failed: ${n.StatusMessage??n.State??"unknown"}.`);return{state:n.State,recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??e.sizeBytes)}}async restore(e,t,r,n){if(r.inPlace===!0)throw Error("AWS Backup infrastructure restores must create isolated resources.");let i=String(r.roleArn??e.manifest.roleArn??""),o=r.metadata&&typeof r.metadata==="object"&&!Array.isArray(r.metadata)?Object.fromEntries(Object.entries(r.metadata).map(([u,a])=>[u,String(a)])):{};if(!i.startsWith("arn:"))throw Error("AWS Backup restore requires an IAM role ARN.");if(!Object.keys(o).length)throw Error("AWS Backup restore requires provider restore metadata.");let s=await this.client.startRestoreJob({RecoveryPointArn:e.uri,IamRoleArn:i,Metadata:o,IdempotencyToken:String(n.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64)}),c=await Ev(this.client,s.RestoreJobId,n);return{providerRestoreJobId:s.RestoreJobId,createdResourceArn:c,isolated:!0,healthy:!0}}async validateHealth(e,t){let r=String(e.createdResourceArn??"");return{healthy:r.startsWith("arn:"),createdResourceArn:r}}async deleteExternal(e,t){await this.client.deleteRecoveryPoint(String(e.manifest.vaultName??""),e.uri)}}import{existsSync as MI}from"node:fs";import{join as Am}from"node:path";import{pathToFileURL as LI}from"node:url";import{existsSync as eg,statSync as tg}from"fs";import{resolve as qi}from"path";import Tv from"process";import{existsSync as Rv,mkdirSync as gx,readdirSync as mx,readFileSync as Pv,writeFileSync as fx}from"fs";import{homedir as ti}from"os";import{dirname as bx,resolve as or}from"path";import Ms from"process";import{existsSync as rg,statSync as ng}from"fs";import{existsSync as dd,mkdirSync as xv,readdirSync as Dv,writeFileSync as Ov}from"fs";import{homedir as ri}from"os";import{dirname as ig,resolve as bt}from"path";import En from"process";import{join as _v,relative as Nv,resolve as og}from"path";import Cs from"process";import{existsSync as Jg,mkdirSync as Rx,readdirSync as Px,writeFileSync as xx}from"fs";import{homedir as qc}from"os";import{dirname as _x,resolve as yt}from"path";import Wi from"process";import{join as $v,relative as Mv,resolve as sg}from"path";import Es from"process";import{existsSync as Wg,mkdirSync as Bx,readdirSync as jx,writeFileSync as Fx}from"fs";import{dirname as zx,resolve as Ts}from"path";import ud from"process";import{Buffer as Yr}from"buffer";import{createCipheriv as Lv,createDecipheriv as Bv,randomBytes as Jc}from"crypto";import{closeSync as Wc,createReadStream as ag,createWriteStream as jv,existsSync as Hc,fsyncSync as cg,openSync as dg,writeFileSync as Fv}from"fs";import{access as Uv,constants as ug,mkdir as zv,readdir as is,rename as lg,stat as ni,unlink as os,writeFile as Gc}from"fs/promises";import{join as ii}from"path";import et from"process";import{pipeline as Vv}from"stream/promises";import{createGzip as pg}from"zlib";import oi from"process";import wr from"process";import{Buffer as Sr}from"buffer";import{createCipheriv as qv,createDecipheriv as Jv,randomBytes as Kc}from"crypto";import{closeSync as Qc,createReadStream as gg,createWriteStream as Wv,existsSync as ss,fsyncSync as mg,openSync as fg,writeFileSync as Hv}from"fs";import{access as Gv,constants as hg,mkdir as Kv,readdir as as,rename as yg,stat as si,unlink as cs,writeFile as Yc}from"fs/promises";import{isAbsolute as Qv,join as ai,resolve as Yv}from"path";import fe from"process";import{pipeline as Xv}from"stream/promises";import{createGzip as bg}from"zlib";import ci from"process";import Ir from"process";import ds from"process";import{existsSync as us}from"fs";import{resolve as Xc}from"path";import{existsSync as Zv}from"fs";import{existsSync as ew,readdirSync as tw}from"fs";import{extname as Zc,resolve as Sg}from"path";import rw from"process";import{join as nw,relative as iw,resolve as vg}from"path";import As from"process";import{Buffer as vr}from"buffer";import{createCipheriv as ow,createDecipheriv as sw,randomBytes as ed}from"crypto";import{closeSync as td,createReadStream as wg,createWriteStream as aw,existsSync as ls,fsyncSync as Ig,openSync as Cg,writeFileSync as cw}from"fs";import{access as dw,constants as Eg,mkdir as uw,readdir as ps,rename as Tg,stat as di,unlink as gs,writeFile as rd}from"fs/promises";import{isAbsolute as lw,join as ui,resolve as pw}from"path";import he from"process";import{pipeline as gw}from"stream/promises";import{createGzip as Ag}from"zlib";import li from"process";import Cr from"process";import fs from"process";import{existsSync as hs}from"fs";import{resolve as Fg}from"path";import{existsSync as _I}from"fs";class Ug{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!eg(e))return!0;return tg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=eg(r)?tg(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class zg{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Is=new Ug,wd=new zg;var Vg=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function qg(e={}){let{name:t="",alias:r}=e,n=["config",".config"];if(t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let i=r===void 0?[]:Array.isArray(r)?r:[r];for(let o of i){if(!o)continue;if(n.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)n.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(n.filter(Boolean)))}function Av(e){return qg(e).flatMap((r)=>Vg.map((n)=>qi(e.directory,`${r}${n}`)))}function kv(e={}){let t=qi(e.cwd||Tv.cwd());return Array.from(new Set([t,qi(t,"config"),qi(t,".config"),e.configDir?qi(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var mw=Object.defineProperty,fw=(e)=>e;function hw(e,t){this[e]=fw.bind(null,t)}var yw=(e,t)=>{for(var r in t)mw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:hw.bind(t,r)})},bw=(e,t)=>()=>(e&&(t=e(e=0)),t),Hg={};yw(Hg,{withErrorRecovery:()=>Qg,tryLoadConfig:()=>Uw,loadConfigWithResult:()=>jw,loadConfig:()=>tm,isRetryableError:()=>_w,isConfigNotFoundError:()=>Ow,isBunfigError:()=>Yg,globalPerformanceMonitor:()=>Ki,globalCache:()=>pi,getEnvOrDefault:()=>Nw,generateConfigTypes:()=>zw,defaultGeneratedDir:()=>dm,defaultConfigDir:()=>cm,deepMergeWithArrayStrategy:()=>Ad,deepMerge:()=>Xg,createLibraryConfig:()=>Vw,config:()=>Fw,bunfigPlugin:()=>qw,applyEnvVarsToConfig:()=>Ji,TypeGenerationError:()=>yd,SchemaValidationError:()=>Gi,PluginError:()=>Sd,PerformanceMonitor:()=>Cd,FileSystemError:()=>hd,ErrorFactory:()=>Xr,EnvVarError:()=>Os,EnvProcessor:()=>Ls,ConfigValidator:()=>kd,ConfigValidationError:()=>md,ConfigNotFoundError:()=>Ds,ConfigMergeError:()=>fd,ConfigLoader:()=>Rd,ConfigLoadError:()=>Hi,ConfigFileLoader:()=>Bs,ConfigCache:()=>Id,CacheUtils:()=>nm,BunfigError:()=>Rt,BrowserConfigError:()=>bd,ArrayMergeStrategies:()=>sm});class Id{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!rg(e))return!0;return ng(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=rg(r)?ng(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Cd{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Sw(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function vw(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function ww(e){return e.getStats().size*2}function Ed(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&De(t[0])&&"id"in t[0]&&t[0].id===3&&De(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(De(t)&&De(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(De(e)&&"arr"in e&&Array.isArray(e.arr)&&De(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&De(t[0])&&De(e[0])){let n=[...t];for(let i of e)if(De(i)&&"name"in i){if(!n.find((s)=>De(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(De(i)&&"path"in i){if(!n.find((s)=>De(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((o)=>ks(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!De(t)||!De(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(De(i)&&De(r[n]))r[n]=Ed(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&De(i[0])&&De(r[n][0])){let o=[...i];for(let s of r[n])if(De(s)&&"name"in s){if(!o.find((u)=>De(u)&&("name"in u)&&u.name===s.name))o.push(s)}else if(De(s)&&"path"in s){if(!o.find((u)=>De(u)&&("path"in u)&&u.path===s.path))o.push(s)}else if(!o.some((c)=>ks(c,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function ks(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ks(e[r],t[r]))return!1;return!0}if(De(e)&&De(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ks(e[i],t[i]))return!1}return!0}return!1}function De(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Iw(e,t){if(!Wg(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Ed(t,n)}catch{return null}}catch{return null}}async function Cw({name:e="",cwd:t,defaultConfig:r}){let n=t||ud.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let c of i){let u=Ts(n,`${s}${c}`),a=await Iw(u,r);if(a!==null)return a}try{let s=Ts(n,"package.json");if(Wg(s)){let u=(await import(s))[e];if(u&&typeof u==="object"&&!Array.isArray(u))try{return Ed(r,u)}catch{}}}catch{}return r}function Ew(e,t={}){let r=Es.cwd();while(r.includes("storage"))r=sg(r,"..");let n=sg(r,e||"");if(t?.relative)return Mv(Es.cwd(),n);return n}async function Tw(){try{let e=await Cw({name:"clarity",defaultConfig:bs,cwd:Es.cwd(),endpoint:"",headers:{}});return{...bs,...e}}catch{return bs}}function Me(){if(wr.env.NODE_ENV==="test"||wr.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Aw(){if(wr.env.NODE_ENV==="test"||wr.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof wr<"u"){let e=wr.type;if(e==="renderer"||e==="worker")return!1;return!!(wr.versions&&(wr.versions.node||wr.versions.bun))}return!1}class Gg{async format(e){let t=await Aw(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:oi.pid,hostname:t(),environment:oi.env.NODE_ENV||"development",platform:oi.platform,version:oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:oi.env.NODE_ENV||oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Rs{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...pd},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Gg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??et.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ss,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ss};return{...Ss,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:pd.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await Uv(this.config.logDirectory,ug.F_OK|ug.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await zv(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let u=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Yr.from(e);try{if(!Hc(this.currentLogFile))await Gc(this.currentLogFile,"",{mode:420});if(i=dg(this.currentLogFile,"a",420),Fv(i,u,{flag:"a"}),cg(i),i!==void 0)Wc(i),i=void 0;if((await ni(this.currentLogFile)).size===0){if(await Gc(this.currentLogFile,u,{flag:"w",mode:420}),(await ni(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let p=a;if(p.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(p.code)){if(o<s-1){let f=typeof p.message==="string"?p.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,f);let y=c*2**o;await new Promise((b)=>setTimeout(b,y)),o++;continue}}if(p?.code&&["ENOSPC","EDQUOT"].includes(p.code))throw Error(`Disk quota exceeded or no space left on device: ${p.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",p),p}finally{if(i!==void 0)try{Wc(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(u){if(o===s-1){let p=u,f=typeof p.message==="string"?p.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),u}o++;let a=c*2**(o-1);await new Promise((p)=>setTimeout(p,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ii(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ii(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ii(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Me())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Jc(16).toString("hex")}generateKey(){return Jc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Jc(16),n=Lv("aes-256-gcm",t,r),i=Yr.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:Yr.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=pg(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Yr.from(Yr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Me())return;let e=await ni(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await is(this.config.logDirectory),o=i.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,a)=>{let p=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-p}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await ni(r).catch(()=>null))try{if(await lg(r,c),t.compress)try{let u=`${c}.gz`;await this.compressLogFile(c,u),await os(c)}catch(u){console.error("Error compressing rotated file:",u)}if(o.length===0&&!i.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await Gc(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await ni(r).catch(()=>null))await lg(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await is(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await os(ii(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ag(e),n=jv(t),i=pg();await Vv(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Hc(this.currentLogFile))try{let e=dg(this.currentLogFile,"r+");cg(e),Wc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Me()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await is(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await os(ii(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ae.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(b)=>b.replace(this.ANSI_PATTERN,"");if(!this.fancy){let b=[];if(s)b.push(t);if(o==="warning")b.push("WARN");else if(o==="error")b.push("ERROR");else if(r)b.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)b.push(n.replace(/[[\]]/g,""));return b.push(i),b.join(" ")}let u=et.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${Ae.cyan(i)}`;if(!s)return a.trim();let p=c(a).trim().length,f=c(t).length,y=Math.max(1,u-2-p-f);return`${a.trim()}${" ".repeat(y)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!Me()){let a=im[e],p=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:a,tag:p,message:Ae.gray(s),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:a,tag:p,message:s,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:a,tag:p,message:Ae.green(s),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:a,tag:p,message:s,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:a,tag:p,message:s,level:e}),console.error(f),c){let y=c.split(`
|
|
61
|
-
`);for(let b of y)if(b.trim()&&!b.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Ae.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!Me()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
|
|
62
|
-
`;if(c)u+=`${c}
|
|
63
|
-
`;u=u.replace(this.ANSI_PATTERN,""),await this.writeToFile(u)}time(e){let t=performance.now();if(this.fancy&&!Me()){let r=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Ae.blue("◐"),tag:r,message:`${Ae.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,c=this.formatConsoleTimestamp(s),a=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
64
|
-
`,a=a.replace(this.ANSI_PATTERN,""),this.fancy&&!Me()){let p=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:Ae.green("✓"),tag:p,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Me())console.error(a.trim());await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Rs(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Me())throw Error("createReadStream is not supported in browser environments");if(!Hc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ag(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Yr.isBuffer(e)?e:Yr.from(e,"base64"),i=n.slice(0,16),o=n.slice(-16),s=n.slice(16,-16),c=Bv("aes-256-gcm",r,i);return c.setAuthTag(o),Yr.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Me()}isServerMode(){return!Me()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!Me()){let o=e.split(`
|
|
65
|
-
`),s=Math.max(...o.map((p)=>p.length))+2,c=`┌${"─".repeat(s)}┐`,u=`└${"─".repeat(s)}┘`,a=o.map((p)=>{let f=" ".repeat(s-p.length-2);return`│ ${p}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Ae.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ae.cyan(c)})),a.forEach((p)=>console.error(this.formatConsoleMessage({timestamp:r,message:Ae.cyan(p),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Ae.cyan(u),showTimestamp:!1}))}else if(!Me())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
66
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Me())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ae.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();et.stdin.removeListener("data",r);try{if(typeof et.stdin.setRawMode==="function")et.stdin.setRawMode(!1)}catch{}et.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof et.stdin.setRawMode==="function")et.stdin.setRawMode(!0)}catch{}et.stdin.resume(),et.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,c=0;if(r=e.replace(s,(u,a)=>{if(a==="%")return"%";if(c>=t.length)return u;let p=t[c++];switch(a){case"s":return String(p);case"d":case"i":return Number(p).toString();case"j":case"o":return JSON.stringify(p,null,2);default:return u}}),c<t.length)r+=` ${t.slice(c).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}if(this.fancy&&!Me()){let s=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"",c=Ae.blue("◐");console.error(`${c} ${s} ${Ae.cyan(r)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
67
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(o)}progress(e,t=""){if(!this.enabled||!this.fancy||Me()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Me())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,s)),c!==void 0)this.activeProgressBar.message=c;let u=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,u)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Me())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Me())return;et.stdout.write(`${"\r".padEnd(et.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Me()||!et.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=Ae.green("━".repeat(n)),s=Ae.gray("━".repeat(i)),c=`[${o}${s}]`,u=`${r}%`.padStart(4),a=e.message?` ${e.message}`:"",p=t||r===100?Ae.green("✓"):Ae.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${Ae.gray(this.formatTag(this.name))}`:"",y=`\r${p}${f} ${c} ${u}${a}`,b=et.stdout.columns||80,C=" ".repeat(Math.max(0,b-y.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${y}${C}`,et.stdout.write(e.lastRenderedLine),t)et.stdout.write(`
|
|
68
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Me()||!et.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Me()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await is(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=ii(this.config.logDirectory,n);if(e.before)try{if((await ni(o)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${o}:`,s);continue}r.push(o)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await os(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ys(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&we(t[0])&&"id"in t[0]&&t[0].id===3&&we(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(we(t)&&we(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(we(e)&&"arr"in e&&Array.isArray(e.arr)&&we(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&we(t[0])&&we(e[0])){let n=[...t];for(let i of e)if(we(i)&&"name"in i){if(!n.find((s)=>we(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(we(i)&&"path"in i){if(!n.find((s)=>we(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((o)=>Ps(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!we(t)||!we(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(we(i)&&we(r[n]))r[n]=ys(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&we(i[0])&&we(r[n][0])){let o=[...i];for(let s of r[n])if(we(s)&&"name"in s){if(!o.find((u)=>we(u)&&("name"in u)&&u.name===s.name))o.push(s)}else if(we(s)&&"path"in s){if(!o.find((u)=>we(u)&&("path"in u)&&u.path===s.path))o.push(s)}else if(!o.some((c)=>Ps(c,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function Td(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ys(e,t);if(Array.isArray(e))return r==="replace"?t:ys(e,t);if(!we(t)||!we(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let o=t[i],s=n[i];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(r==="replace")n[i]=o;else n[i]=ys(s,o);else if(we(o)&&we(s))n[i]=Td(s,o,r);else n[i]=o}return n}function Ps(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ps(e[r],t[r]))return!1;return!0}if(we(e)&&we(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ps(e[i],t[i]))return!1}return!0}return!1}function we(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ms(e,t,r="replace"){if(!Jg(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Td(t,i,r)}catch{return null}}catch{return null}}function kw(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function o(s,c=[]){let u={...s};for(let[a,p]of Object.entries(s)){let f=[...c,a],y=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),b=`${n}_${f.map(y).join("_")}`,C=`${n}_${f.map((T)=>T.toUpperCase()).join("_")}`;if(r)rt.info(`Checking environment variable ${b} for config ${e}.${f.join(".")}`);if(typeof p==="object"&&p!==null&&!Array.isArray(p))u[a]=o(p,f);else{let T=Wi.env[b]||Wi.env[C];if(T!==void 0){if(r)rt.info(`Using environment variable ${T?b:C} for config ${e}.${f.join(".")}`);if(typeof p==="number")u[a]=Number(T);else if(typeof p==="boolean")u[a]=T.toLowerCase()==="true";else if(Array.isArray(p))try{let R=JSON.parse(T);if(Array.isArray(R))u[a]=R;else u[a]=T.split(",").map((x)=>x.trim())}catch{u[a]=T.split(",").map((R)=>R.trim())}else u[a]=T}}}return u}return o(i)}async function Rw({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:o=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let u=s&&typeof i==="object"&&i!==null&&!Array.isArray(i)?kw(e,i,o):i,a=r||Wi.cwd(),p=[".ts",".js",".mjs",".cjs",".json"];if(o)rt.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${a}`);let f=[e,`.${e}`].filter(Boolean),y=[`${e}.config`,`.${e}.config`].filter(Boolean),b=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],T=Array.from(new Set([a,yt(a,"config"),yt(a,".config"),n?yt(a,n):void 0].filter(Boolean)));for(let R of T){if(o)rt.info(`Searching for configuration in: ${R}`);let L=[yt(a,"config"),yt(a,".config")].concat(n?[yt(a,n)]:[]).includes(R)?[...f,...y,...b,...C]:[...y,...f,...C,...b];for(let P of L)for(let G of p){let ae=yt(R,`${P}${G}`),Z=await ms(ae,u,c);if(Z!==null){if(o)rt.success(`Configuration loaded from: ${ae}`);return Z}}}if(e){let R=yt(qc(),".config",e),x=["config",`${e}.config`];if(t)x.push(`${t}.config`);if(o)rt.info(`Checking user config directory: ${R}`);for(let L of x)for(let P of p){let G=yt(R,`${L}${P}`),ae=await ms(G,u,c);if(ae!==null){if(o)rt.success(`Configuration loaded from user config directory: ${G}`);return ae}}}if(e){let R=yt(qc(),".config"),x=[`.${e}.config`];if(t)x.push(`.${t}.config`);if(o)rt.info(`Checking user config directory for dotfile configs: ${R}`);for(let L of x)for(let P of p){let G=yt(R,`${L}${P}`),ae=await ms(G,u,c);if(ae!==null){if(o)rt.success(`Configuration loaded from user config directory dotfile: ${G}`);return ae}}}if(e){let R=qc(),x=[`.${e}.config`,`.${e}`];if(t)x.push(`.${t}.config`),x.push(`.${t}`);if(o)rt.info(`Checking user home directory for dotfile configs: ${R}`);for(let L of x)for(let P of p){let G=yt(R,`${L}${P}`),ae=await ms(G,u,c);if(ae!==null){if(o)rt.success(`Configuration loaded from user home directory: ${G}`);return ae}}}try{let R=yt(a,"package.json");if(Jg(R)){let x=await import(R),L=x[e];if(!L&&t){if(L=x[t],L&&o)rt.success(`Using alias "${t}" configuration from package.json`)}if(L&&typeof L==="object"&&!Array.isArray(L))try{if(o)rt.success(`Configuration loaded from package.json: ${L===x[e]?e:t}`);return Td(u,L,c)}catch(P){if(o)rt.warn("Failed to merge package.json config:",P)}}}catch(R){if(o)rt.warn("Failed to load package.json:",R)}if(o)rt.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return u}function Pw(e,t={}){let r=Cs.cwd();while(r.includes("storage"))r=og(r,"..");let n=og(r,e||"");if(t?.relative)return Nv(Cs.cwd(),n);return n}async function xw(){try{let e=await Rw({name:"clarity",alias:"logging",defaultConfig:vs,cwd:Cs.cwd()});return{...vs,...e||{}}}catch{return vs}}function qe(){if(Ir.env.NODE_ENV==="test"||Ir.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Dw(){if(Ir.env.NODE_ENV==="test"||Ir.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ir<"u"){let e=Ir.type;if(e==="renderer"||e==="worker")return!1;return!!(Ir.versions&&(Ir.versions.node||Ir.versions.bun))}return!1}class Kg{async format(e){let t=await Dw(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ci.pid,hostname:t(),environment:ci.env.NODE_ENV||"development",platform:ci.platform,version:ci.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ci.env.NODE_ENV||ci.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xs{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...gd},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Kg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??fe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ws,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ws};return{...ws,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:gd.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!qe()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await Gv(this.config.logDirectory,hg.F_OK|hg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await Kv(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let u=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Sr.from(e);try{if(!ss(this.currentLogFile))await Yc(this.currentLogFile,"",{mode:420});if(i=fg(this.currentLogFile,"a",420),Hv(i,u,{flag:"a"}),mg(i),i!==void 0)Qc(i),i=void 0;if((await si(this.currentLogFile)).size===0){if(await Yc(this.currentLogFile,u,{flag:"w",mode:420}),(await si(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let p=a;if(p.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(p.code)){if(o<s-1){let f=typeof p.message==="string"?p.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,f);let y=c*2**o;await new Promise((b)=>setTimeout(b,y)),o++;continue}}if(p?.code&&["ENOSPC","EDQUOT"].includes(p.code))throw Error(`Disk quota exceeded or no space left on device: ${p.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",p),p}finally{if(i!==void 0)try{Qc(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(u){if(o===s-1){let p=u,f=typeof p.message==="string"?p.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),u}o++;let a=c*2**(o-1);await new Promise((p)=>setTimeout(p,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ai(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ai(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ai(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(qe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Kc(16).toString("hex")}generateKey(){return Kc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Kc(16),n=qv("aes-256-gcm",t,r),i=Sr.isBuffer(e)?e:Sr.from(e,"utf8"),o=n.update(i),s=n.final(),c=o.length+s.length,u=n.getAuthTag(),a=Sr.allocUnsafe(16+c+16);return r.copy(a,0),o.copy(a,16),s.copy(a,16+o.length),u.copy(a,16+c),{encrypted:a,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=bg(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Sr.from(Sr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(qe())return;if(!this.shouldWriteToFile())return;let e=await si(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await as(this.config.logDirectory),o=i.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,a)=>{let p=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-p}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await si(r).catch(()=>null))try{if(await yg(r,c),t.compress)try{let u=`${c}.gz`;await this.compressLogFile(c,u),await cs(c)}catch(u){console.error("Error compressing rotated file:",u)}if(o.length===0&&!i.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await Yc(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await si(r).catch(()=>null))await yg(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await as(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await cs(ai(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=gg(e),n=Wv(t),i=bg();await Xv(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ss(this.currentLogFile))try{let e=fg(this.currentLogFile,"r+");mg(e),Qc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!qe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await as(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await cs(ai(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?be.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||qe())return!1;let e=typeof fe.env.NO_COLOR<"u",t=fe.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof fe.stderr<"u"&&fe.stderr.isTTY||typeof fe.stdout<"u"&&fe.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(b)=>b.replace(this.ANSI_PATTERN,"");if(!this.fancy){let b=[];if(s)b.push(t);if(o==="warning")b.push("WARN");else if(o==="error")b.push("ERROR");else if(r)b.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)b.push(n.replace(/[[\]]/g,""));return b.push(i),b.join(" ")}let u=fe.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${be.cyan(i)}`;if(!s)return a.trim();let p=c(a).trim().length,f=c(t).length,y=Math.max(1,u-2-p-f);return`${a.trim()}${" ".repeat(y)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=be.underline(be.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,u="\x1B]8;;",a="\x1B\\";return`\x1B]8;;${c}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>be.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>be.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>be.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>be.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>be.strikethrough(n)),t}supportsHyperlinks(){if(qe())return!1;let e=fe.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=fe.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Qv(t)||t.startsWith("./")||t.startsWith("../"))t=Yv(t);else return null;return ss(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);let{consoleText:u,fileText:a}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":om[e],y=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",b;switch(e){case"debug":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:be.gray(u),level:e}),console.error(b);break;case"info":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:u,level:e}),console.warn(b);break;case"success":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:be.green(u),level:e}),console.error(b);break;case"warning":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:u,level:e}),console.warn(b);break;case"error":if(b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:u,level:e}),console.error(b),c){let C=c.split(`
|
|
69
|
-
`);for(let T of C)if(T.trim()&&!T.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:be.gray(` ${T}`),level:e,showTimestamp:!1}))}break}}else if(!qe()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(e))return;let p=`${o} ${this.environment}.${e.toUpperCase()}: ${a}
|
|
70
|
-
`;if(c)p+=`${c}
|
|
71
|
-
`;if(p=p.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(p)}progress(e,t=""){let r={update:(c,u)=>{},finish:(c)=>{},interrupt:(c,u)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!qe()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,u)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),u!==void 0)this.activeProgressBar.message=u;if(this.shouldStyleConsole()&&!qe()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,u="info")=>{if(!qe()&&fe.stdout.isTTY)fe.stdout.write(`
|
|
72
|
-
`);if(this[u==="warning"?"warn":u](c),this.activeProgressBar&&this.shouldStyleConsole()&&!qe()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":be.blue("◐"),tag:r,message:`${be.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,c=this.formatConsoleTimestamp(s),a=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
73
|
-
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let p=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":be.green("✓"),tag:p,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!qe())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new xs(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(qe())throw Error("createReadStream is not supported in browser environments");if(!ss(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return gg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Sr.isBuffer(e)?e:Sr.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Jv("aes-256-gcm",r,i);c.setAuthTag(o);let u=c.update(s),a=c.final(),p=u.length+a.length,f=Sr.allocUnsafe(p);return u.copy(f,0),a.copy(f,u.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return qe()}isServerMode(){return!qe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
74
|
-
`),u=Math.max(...c.map((y)=>y.length))+2,a=`┌${"─".repeat(u)}┐`,p=`└${"─".repeat(u)}┘`,f=c.map((y)=>this.formatConsoleMessage({timestamp:r,message:be.cyan(y),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:be.cyan(a),showTimestamp:!1})),f.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:be.cyan(p),showTimestamp:!1}))}else if(!qe())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
75
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(qe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${be.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();fe.stdin.removeListener("data",r);try{if(typeof fe.stdin.setRawMode==="function")fe.stdin.setRawMode(!1)}catch{}fe.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof fe.stdin.setRawMode==="function")fe.stdin.setRawMode(!0)}catch{}fe.stdin.resume(),fe.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let u=/%([sdijfo%])/g,a=0;if(r=e.replace(u,(p,f)=>{if(f==="%")return"%";if(a>=t.length)return p;let y=t[a++];switch(f){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return p}}),a<t.length)r+=` ${t.slice(a).map((p)=>typeof p==="object"?JSON.stringify(p,null,2):String(p)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${be.blue("◐")} `;console.error(`${a}${u} ${be.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
76
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!fe.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=be.green("━".repeat(n)),s=be.gray("━".repeat(i)),c=`[${o}${s}]`,u=`${r}%`.padStart(4),a=e.message?` ${e.message}`:"",p=this.options.showIcons===!1?"":t||r===100?be.green("✓"):be.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${be.gray(this.formatTag(this.name))}`:"",y=`\r${p}${f} ${c} ${u}${a}`,b=fe.stdout.columns||80,C=" ".repeat(Math.max(0,b-y.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${y}${C}`,fe.stdout.write(e.lastRenderedLine),t)fe.stdout.write(`
|
|
77
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||qe()||!fe.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(qe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await as(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=ai(this.config.logDirectory,n);if(e.before)try{if((await si(o)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${o}:`,s);continue}r.push(o)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await cs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Qg(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(u){if(s=u instanceof Error?u:Error(String(u)),c===r||!i(s))break;if(n>0)await new Promise((a)=>setTimeout(a,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Yg(e){return e instanceof Rt}function Ow(e){return e instanceof Ds}function _w(e){if(Yg(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Ls{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:c=!1,trackPerformance:u=!0}=r,a=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let p=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],p,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(u)return Ki.track("applyEnvironmentVariables",a,{configName:e});return a()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=s.map((p)=>this.formatEnvKey(p,n.useCamelCase)),u=`${r}_${c.join("_")}`,a=n.useBackwardCompatibility?`${r}_${s.map((p)=>p.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let p=ds.env[u]||(a?ds.env[a]:void 0);if(p!==void 0){if(n.verbose){let f=ds.env[u]?u:a}try{e[i]=this.parseEnvironmentValue(p,typeof o,u,n.customParsers,n.configName)}catch(f){if(f instanceof Os)throw f;throw Xr.envVar(u,p,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw Xr.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ds.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=`${r}_${s.map((u)=>this.formatEnvKey(u,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:c,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
78
|
-
|
|
79
|
-
`;for(let n of e)r+=`${n.key}
|
|
80
|
-
`,r+=` Type: ${n.type}
|
|
81
|
-
`,r+=` Description: ${n.description}
|
|
82
|
-
`,r+=` Example: ${n.example}
|
|
83
|
-
|
|
84
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
85
|
-
|
|
86
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
87
|
-
`,r+=`|----------|------|-------------|----------|
|
|
88
|
-
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
89
|
-
`;return r}}function Nw(e,t){let r=rm("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Xg(e,t,r={}){return Zg(e,t,r,new WeakMap)}function Zg(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return em(e,t,i,n);if(!Nt(t)||!Nt(e))return t;return Bw(e,t,r,n)}function em(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return $w(e,t);case"smart":return Mw(e,t,n);default:return t}return t}function $w(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>ld(i,n)))r.push(n);return r}function Mw(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Nt(t[0])&&Nt(e[0]))return Lw(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Lw(e,t,r){let n=[...t];for(let i of e){if(!Nt(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in i){if(n.find((a)=>Nt(a)&&(c in a)&&a[c]===i[c])){s=!0;break}}if(!s)n.push(i)}return n}function Bw(e,t,r,n){let i=t;if(Nt(i)&&n.has(i))return n.get(i);let o={...e};if(Nt(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let c=i[s],u=o[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if(Nt(c)&&Nt(u))o[s]=Zg(u,c,r,n);else if(Array.isArray(c)||Array.isArray(u))o[s]=em(u,c,r.arrayMergeMode||"smart",n);else o[s]=c}return o}function Ad(e,t,r="replace"){return Xg(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ld(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ld(e[r],t[r]))return!1;return!0}if(Nt(e)&&Nt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ld(e[i],t[i]))return!1}return!0}return!1}function Nt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Bs{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1}=r;if(i){let a=pi.getWithFileCheck("file",e);if(a){if(c)console.log(`Configuration loaded from cache: ${e}`);return a}}let u=async()=>{if(!us(e))return null;try{let a=`?t=${Date.now()}`,p=await import(e+a),f=p.default||p,y="default"in p,b=Object.keys(p).length>0;if(!y&&!b)throw new Hi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Hi(e,Error("Configuration must export a valid object"),"unknown");let R={config:Ad(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)pi.setWithFileCheck("file",R,e,o);return R}catch(a){throw a instanceof Error?Xr.configLoad(e,a):Xr.configLoad(e,Error(String(a)))}};if(s)return Ki.track("loadFromPath",u,{path:e});return u()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push(Xc(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Qg(async()=>us(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!us(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let c=Xc(e,`${o}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=Xc(e,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!us(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class kd{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:u=!1}=r,a=async()=>{let p=[],f=[],y={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:c,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,y);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],y);else return this.validateWithJSONSchema(e,t,y)}catch(b){return p.push({path:"",message:`Validation failed: ${b}`,rule:"system"}),{isValid:!1,errors:p,warnings:f}}};if(c)return await Ki.track("validateConfiguration",a);return a()}async validateWithSchemaFile(e,t,r){try{if(!Zv(t))throw new Gi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Gi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,u]of Object.entries(t.properties))if(c in s){let a=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],u,a,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(s))if(!c.has(u))i.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:am},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Rd{fileLoader=new Bs;envProcessor=new Ls;validator=new kd;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let u=this.checkCache(s.name||"",s);if(u)return u}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(u){let a=s.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(a)throw u;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let p=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),f=!p&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),y=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(a&&(y||p))throw u;if(f&&(!a||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!a)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(i||o)await this.validateConfiguration(c.config,i,o,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)qt.warn(`Slow configuration loading detected: ${u.duration}ms for ${s.name}`);c.metrics=u}return c}catch(c){let u=Date.now()-t;throw qt.error(`Configuration loading failed after ${u}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:s,defaultConfig:c,checkEnv:u=!0,arrayStrategy:a="replace",verbose:p=!1}=e,f=o||En.cwd(),y=[],b=await this.loadLocalConfiguration(n,i,f,s,c,a,p,u,r);if(b)return y.push(...this.getLocalSearchPaths(n,i,f,s)),this.finalizeResult(b,y,u,n,p);let C=await this.loadHomeConfiguration(n,i,c,a,p,u);if(C)return y.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,y,u,n,p);let T=await this.loadPackageJsonConfiguration(n,i,f,c,a,p,u);if(T)return y.push(bt(f,"package.json")),this.finalizeResult(T,y,u,n,p);if(y.push(...this.getAllSearchPaths(n,i,f,s)),t)throw Xr.configNotFound(n,y,i);return{...await this.applyEnvironmentVariables(n,c,u,p),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,c,u){let a=c?Ji(e,i,s):i,p=this.getLocalDirectories(r,n);for(let f of p){if(s)qt.info(`Searching for configuration in: ${f}`);let y=this.fileLoader.generateConfigPaths(e,f,t),b=await this.fileLoader.tryLoadFromPaths(y,a,{arrayStrategy:o,verbose:s,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(b){if(s)qt.success(`Configuration loaded from: ${b.source.path}`);return b}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?Ji(e,r,i):r,c=[bt(ri(),".config",e),bt(ri(),".config"),ri()];for(let u of c){if(i)qt.info(`Checking home directory: ${u}`);let a=this.fileLoader.generateConfigPaths(e,u,t),p=await this.fileLoader.tryLoadFromPaths(a,s,{arrayStrategy:n,verbose:i});if(p){if(i)qt.success(`Configuration loaded from home directory: ${p.source.path}`);return p}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let c=s?Ji(e,n,o):n;try{let u=bt(r,"package.json");if(!dd(u))return null;let a=await import(u),p=a[e],f=e;if(!p&&t)p=a[t],f=t;if(p&&typeof p==="object"&&!Array.isArray(p)){if(o)qt.success(`Configuration loaded from package.json: ${f}`);return{config:Ad(c,p,i),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(o)qt.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ji(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw Xr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return pi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);pi.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,bt(e,"config"),bt(e,".config"),t?bt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(bt(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[bt(ri(),".config",e),bt(ri(),".config"),ri()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function kg(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function jw(e){return Er.loadConfig({...e,__strictErrorHandling:!0})}async function tm(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Er.loadConfig(e);else n=await Er.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)qt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Er.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Fw(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Er.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&kg(r)))return(await Er.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Er.loadConfig({...e,cwd:e.cwd||En.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&kg(t)))return(await Er.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Uw(e,t,r="replace"){let n=new Bs;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Ji(e,t,r=!1){let n=new Ls,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let u={...s};for(let[a,p]of Object.entries(s)){let f=[...c,a],y=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((T)=>T.toUpperCase()).join("")}`,`${i}_${f.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],b,C;for(let T of y)if(b=En.env[T],b!==void 0){C=T;break}if(b!==void 0&&C)if(typeof p==="boolean")u[a]=["true","1","yes"].includes(b.toLowerCase());else if(typeof p==="number"){let T=Number(b);if(!Number.isNaN(T))u[a]=T}else if(Array.isArray(p))try{u[a]=JSON.parse(b)}catch{u[a]=b.split(",").map((T)=>T.trim())}else u[a]=b;else if(p&&typeof p==="object"&&!Array.isArray(p))u[a]=o(p,f)}return u}return o(t)}function zw(e){let t=bt(En.cwd(),e.configDir),r=bt(En.cwd(),e.generatedDir),n=bt(r,"config-types.ts");if(!dd(ig(n)))xv(ig(n),{recursive:!0,mode:511});let i=dd(t)?Dv(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${yI}
|
|
90
|
-
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
91
|
-
`;Ov(n,o,{mode:438})}function Vw(e){let t=null,r=null,n=()=>{if(!r)r=tm(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)qt.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(o,s){if(t)return t[s];let c=i[s];return n(),c},has(o,s){return s in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||i,s)},set(o,s,c){if(!t)t={...i};return t[s]=c,!0}})}function qw(e){let t=Sg(rw.cwd(),e?.configDir||"./config");function r(){if(!ew(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=tw(t).filter((u)=>i.has(Zc(u))).map((u)=>({base:u.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:u})),c=new Map;for(let{base:u,file:a}of s){let p=Zc(a).toLowerCase(),f=c.get(u);if(!f){c.set(u,a);continue}let y=Zc(f).toLowerCase();if(o.indexOf(p)<o.indexOf(y))c.set(u,a)}return Array.from(c.entries()).map(([u,a])=>({base:u,file:a})).sort((u,a)=>u.base.localeCompare(a.base))}function n(){let i=r(),o=i.map((a)=>a.base),s=o.length?o.map((a)=>`'${a}'`).join(" | "):"string",c=i.length?`{
|
|
92
|
-
${i.map((a)=>{let p=Sg(t,a.file).replace(/\\/g,"/");return` '${a.base}': typeof import('${p}').default`}).join(`,
|
|
93
|
-
`)}
|
|
94
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
95
|
-
export type ConfigByName = ${c}
|
|
96
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
97
|
-
export type ConfigOf = Config
|
|
98
|
-
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var rm,pi,Ki,nm,Jw,Ww,Rg,bs,pd,tt,Ae,Hw,Pg,Gw,xg,Kw,Qw,nd,Yw,Dg,Og,id,Xw,Zw,eI,tI,Ss,im,rI,rt,nI,iI,_g,vs,gd,Je,be,oI,Ng,sI,$g,aI,cI,od,dI,Mg,Lg,uI,sd,lI,pI,gI,mI,fI,ws,om,hI,yI="0.15.6",Rt,Ds,Hi,md,fd,Os,hd,yd,Gi,bd,Sd,Xr,sm,am,qt,Er,cm,dm,bI=bw(async()=>{rm=import.meta.require,pi=new Id,Ki=new Cd,nm={createKey:Sw,isEquivalent:vw,estimateMemoryUsage:ww},Jw=Ts(ud.cwd(),"config"),Ww=Ts(ud.cwd(),"src/generated"),Rg=Es.env.CLARITY_LOG_DIR||$v(Ew(),"logs"),bs={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},pd=await Tw(),tt={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Ae=tt,Hw=tt.red,Pg=tt.green,Gw=tt.yellow,xg=tt.blue,Kw=tt.magenta,Qw=tt.cyan,nd=tt.white,Yw=tt.gray,Dg=tt.bgRed,Og=tt.bgYellow,id=tt.bold,Xw=tt.dim,Zw=tt.italic,eI=tt.underline,tI=tt.reset,Ss={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},im={debug:"\uD83D\uDD0D",info:xg("ℹ"),success:Pg("✓"),warning:Og(nd(id(" WARN "))),error:Dg(nd(id(" ERROR ")))},rI=new Rs("stacks"),rt=new Rs("bunfig",{showTags:!0}),nI=yt(Wi.cwd(),"config"),iI=yt(Wi.cwd(),"src/generated"),_g=Cs.env.CLARITY_LOG_DIR||_v(Pw(),"logs"),vs={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_g,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},gd=await xw(),Je={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},be=Je,oI=Je.red,Ng=Je.green,sI=Je.yellow,$g=Je.blue,aI=Je.magenta,cI=Je.cyan,od=Je.white,dI=Je.gray,Mg=Je.bgRed,Lg=Je.bgYellow,uI=Je.bgGray,sd=Je.bold,lI=Je.dim,pI=Je.italic,gI=Je.underline,mI=Je.strikethrough,fI=Je.reset,ws={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},om={debug:"\uD83D\uDD0D",info:$g("ℹ"),success:Ng("✓"),warning:Lg(od(sd(" WARN "))),error:Mg(od(sd(" ERROR ")))},hI=new xs("stacks"),Rt=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Ds=class extends Rt{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Hi=class extends Rt{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},md=class extends Rt{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},fd=class extends Rt{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Os=class extends Rt{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},hd=class extends Rt{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},yd=class extends Rt{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Gi=class extends Rt{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},bd=class extends Rt{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},Sd=class extends Rt{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Xr={configNotFound(e,t,r){return new Ds(e,t,r)},configLoad(e,t,r){return new Hi(e,t,r)},configValidation(e,t,r){return new md(e,t,r)},configMerge(e,t,r,n){return new fd(e,t,r,n)},envVar(e,t,r,n){return new Os(e,t,r,n)},fileSystem(e,t,r){return new hd(e,t,r)},typeGeneration(e,t,r){return new yd(e,t,r)},schemaValidation(e,t,r){return new Gi(e,t,r)},browserConfig(e,t,r,n){return new bd(e,t,r,n)},plugin(e,t,r){return new Sd(e,t,r)}},sm={replace:"replace",concat:"concat",smart:"smart"},am=/^https?:\/\//,qt=new xs("bunfig",{showTags:!0}),Er=new Rd,cm=bt(En.cwd(),"config"),dm=bt(En.cwd(),"src/generated")});function SI(e,t={}){let r=As.cwd();while(r.includes("storage"))r=vg(r,"..");let n=vg(r,e||"");if(t?.relative)return iw(As.cwd(),n);return n}var vI=As.env.CLARITY_LOG_DIR||nw(SI(),"logs"),um={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:vI,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},_s={...um},PD=(async()=>{try{let{loadConfig:e}=await bI().then(()=>Hg),t=await e({name:"clarity",alias:"logging",defaultConfig:um,cwd:As.cwd()});if(t)Object.assign(_s,t)}catch{}return _s})();function We(){if(Cr.env.NODE_ENV==="test"||Cr.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wI(){if(Cr.env.NODE_ENV==="test"||Cr.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Cr<"u"){let e=Cr.type;if(e==="renderer"||e==="worker")return!1;return!!(Cr.versions&&(Cr.versions.node||Cr.versions.bun))}return!1}class lm{async format(e){let t=await wI(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:li.pid,hostname:t(),environment:li.env.NODE_ENV||"development",platform:li.platform,version:li.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:li.env.NODE_ENV||li.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var Ke={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},Se=Ke,xD=Ke.red,II=Ke.green,DD=Ke.yellow,CI=Ke.blue,OD=Ke.magenta,_D=Ke.cyan,Bg=Ke.white,ND=Ke.gray,EI=Ke.bgRed,TI=Ke.bgYellow,$D=Ke.bgGray,jg=Ke.bold,MD=Ke.dim,LD=Ke.italic,BD=Ke.underline,jD=Ke.strikethrough,FD=Ke.reset,ad={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},AI={debug:"\uD83D\uDD0D",info:CI("ℹ"),success:II("✓"),warning:TI(Bg(jg(" WARN "))),error:EI(Bg(jg(" ERROR ")))};class js{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={..._s},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new lm,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??he.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ad,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ad};return{...ad,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:_s.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!We()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await dw(this.config.logDirectory,Eg.F_OK|Eg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await uw(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let u=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:vr.from(e);try{if(!ls(this.currentLogFile))await rd(this.currentLogFile,"",{mode:420});if(i=Cg(this.currentLogFile,"a",420),cw(i,u,{flag:"a"}),Ig(i),i!==void 0)td(i),i=void 0;if((await di(this.currentLogFile)).size===0){if(await rd(this.currentLogFile,u,{flag:"w",mode:420}),(await di(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let p=a;if(p.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(p.code)){if(o<s-1){let f=typeof p.message==="string"?p.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,f);let y=c*2**o;await new Promise((b)=>setTimeout(b,y)),o++;continue}}if(p?.code&&["ENOSPC","EDQUOT"].includes(p.code))throw Error(`Disk quota exceeded or no space left on device: ${p.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",p),p}finally{if(i!==void 0)try{td(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(u){if(o===s-1){let p=u,f=typeof p.message==="string"?p.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),u}o++;let a=c*2**(o-1);await new Promise((p)=>setTimeout(p,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ui(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ui(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ui(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(We())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ed(16).toString("hex")}generateKey(){return ed(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ed(16),n=ow("aes-256-gcm",t,r),i=vr.isBuffer(e)?e:vr.from(e,"utf8"),o=n.update(i),s=n.final(),c=o.length+s.length,u=n.getAuthTag(),a=vr.allocUnsafe(16+c+16);return r.copy(a,0),o.copy(a,16),s.copy(a,16+o.length),u.copy(a,16+c),{encrypted:a,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ag(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(vr.from(vr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(We())return;if(!this.shouldWriteToFile())return;let e=await di(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ps(this.config.logDirectory),o=i.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,a)=>{let p=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-p}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await di(r).catch(()=>null))try{if(await Tg(r,c),t.compress)try{let u=`${c}.gz`;await this.compressLogFile(c,u),await gs(c)}catch(u){console.error("Error compressing rotated file:",u)}if(o.length===0&&!i.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await rd(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await di(r).catch(()=>null))await Tg(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await ps(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await gs(ui(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=wg(e),n=aw(t),i=Ag();await gw(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ls(this.currentLogFile))try{let e=Cg(this.currentLogFile,"r+");Ig(e),td(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!We()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await ps(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await gs(ui(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?Se.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||We())return!1;let e=typeof he.env.NO_COLOR<"u",t=he.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof he.stderr<"u"&&he.stderr.isTTY||typeof he.stdout<"u"&&he.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(b)=>b.replace(this.ANSI_PATTERN,"");if(!this.fancy){let b=[];if(s)b.push(t);if(o==="warning")b.push("WARN");else if(o==="error")b.push("ERROR");else if(r)b.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)b.push(n.replace(/[[\]]/g,""));return b.push(i),b.join(" ")}let u=he.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${Se.cyan(i)}`;if(!s)return a.trim();let p=c(a).trim().length,f=c(t).length,y=Math.max(1,u-2-p-f);return`${a.trim()}${" ".repeat(y)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=Se.underline(Se.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,u="\x1B]8;;",a="\x1B\\";return`\x1B]8;;${c}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>Se.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>Se.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>Se.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>Se.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>Se.strikethrough(n)),t}supportsHyperlinks(){if(We())return!1;let e=he.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=he.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(lw(t)||t.startsWith("./")||t.startsWith("../"))t=pw(t);else return null;return ls(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);let{consoleText:u,fileText:a}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":AI[e],y=this.options.showTags!==!1&&this.name?Se.gray(this.formatTag(this.name)):"",b;switch(e){case"debug":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:Se.gray(u),level:e}),console.error(b);break;case"info":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:u,level:e}),console.warn(b);break;case"success":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:Se.green(u),level:e}),console.error(b);break;case"warning":b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:u,level:e}),console.warn(b);break;case"error":if(b=this.formatConsoleMessage({timestamp:i,icon:f,tag:y,message:u,level:e}),console.error(b),c){let C=c.split(`
|
|
99
|
-
`);for(let T of C)if(T.trim()&&!T.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Se.gray(` ${T}`),level:e,showTimestamp:!1}))}break}}else if(!We()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}let p=`${o} ${this.environment}.${e.toUpperCase()}: ${a}
|
|
100
|
-
`;if(c)p+=`${c}
|
|
101
|
-
`;if(p=p.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(p)}progress(e,t=""){let r={update:(c,u)=>{},finish:(c)=>{},interrupt:(c,u)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!We()&&he.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,u)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),u!==void 0)this.activeProgressBar.message=u;if(this.shouldStyleConsole()&&!We()&&he.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,u="info")=>{if(!We()&&he.stdout.isTTY)he.stdout.write(`
|
|
102
|
-
`);if(this[u==="warning"?"warn":u](c),this.activeProgressBar&&this.shouldStyleConsole()&&!We()&&he.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?Se.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":Se.blue("◐"),tag:r,message:`${Se.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,c=this.formatConsoleTimestamp(s),a=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
103
|
-
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let p=this.options.showTags!==!1&&this.name?Se.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":Se.green("✓"),tag:p,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!We())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new js(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(We())throw Error("createReadStream is not supported in browser environments");if(!ls(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=vr.isBuffer(e)?e:vr.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=sw("aes-256-gcm",r,i);c.setAuthTag(o);let u=c.update(s),a=c.final(),p=u.length+a.length,f=vr.allocUnsafe(p);return u.copy(f,0),a.copy(f,u.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return We()}isServerMode(){return!We()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
104
|
-
`),u=Math.max(...c.map((y)=>y.length))+2,a=`┌${"─".repeat(u)}┐`,p=`└${"─".repeat(u)}┘`,f=c.map((y)=>this.formatConsoleMessage({timestamp:r,message:Se.cyan(y),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Se.cyan(a),showTimestamp:!1})),f.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:Se.cyan(p),showTimestamp:!1}))}else if(!We())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
105
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(We())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Se.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();he.stdin.removeListener("data",r);try{if(typeof he.stdin.setRawMode==="function")he.stdin.setRawMode(!1)}catch{}he.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof he.stdin.setRawMode==="function")he.stdin.setRawMode(!0)}catch{}he.stdin.resume(),he.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let u=/%([sdijfo%])/g,a=0;if(r=e.replace(u,(p,f)=>{if(f==="%")return"%";if(a>=t.length)return p;let y=t[a++];switch(f){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return p}}),a<t.length)r+=` ${t.slice(a).map((p)=>typeof p==="object"?JSON.stringify(p,null,2):String(p)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?Se.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${Se.blue("◐")} `;console.error(`${a}${u} ${Se.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
106
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!he.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=Se.green("━".repeat(n)),s=Se.gray("━".repeat(i)),c=`[${o}${s}]`,u=`${r}%`.padStart(4),a=e.message?` ${e.message}`:"",p=this.options.showIcons===!1?"":t||r===100?Se.green("✓"):Se.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${Se.gray(this.formatTag(this.name))}`:"",y=`\r${p}${f} ${c} ${u}${a}`,b=he.stdout.columns||80,C=" ".repeat(Math.max(0,b-y.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${y}${C}`,he.stdout.write(e.lastRenderedLine),t)he.stdout.write(`
|
|
107
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||We()||!he.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(We()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ps(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=ui(this.config.logDirectory,n);if(e.before)try{if((await di(o)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${o}:`,s);continue}r.push(o)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await gs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var UD=new js("stacks");class Jt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class pm extends Jt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class Ns extends Jt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class gm extends Jt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class mm extends Jt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Pd extends Jt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}}class fm extends Jt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class hm extends Jt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class $s extends Jt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class ym extends Jt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}}class bm extends Jt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var Cn={configNotFound(e,t,r){return new pm(e,t,r)},configLoad(e,t,r){return new Ns(e,t,r)},configValidation(e,t,r){return new gm(e,t,r)},configMerge(e,t,r,n){return new mm(e,t,r,n)},envVar(e,t,r,n){return new Pd(e,t,r,n)},fileSystem(e,t,r){return new fm(e,t,r)},typeGeneration(e,t,r){return new hm(e,t,r)},schemaValidation(e,t,r){return new $s(e,t,r)},browserConfig(e,t,r,n){return new ym(e,t,r,n)},plugin(e,t,r){return new bm(e,t,r)}};async function kI(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(u){if(s=u instanceof Error?u:Error(String(u)),c===r||!i(s))break;if(n>0)await new Promise((a)=>setTimeout(a,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class xd{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:c=!1,trackPerformance:u=!0}=r,a=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let p=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],p,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(u)return wd.track("applyEnvironmentVariables",a,{configName:e});return a()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=s.map((p)=>this.formatEnvKey(p,n.useCamelCase)),u=`${r}_${c.join("_")}`,a=n.useBackwardCompatibility?`${r}_${s.map((p)=>p.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let p=fs.env[u]||(a?fs.env[a]:void 0);if(p!==void 0){if(n.verbose){let f=fs.env[u]?u:a}try{e[i]=this.parseEnvironmentValue(p,typeof o,u,n.customParsers,n.configName)}catch(f){if(f instanceof Pd)throw f;throw Cn.envVar(u,p,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw Cn.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(fs.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=`${r}_${s.map((u)=>this.formatEnvKey(u,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:c,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
108
|
-
|
|
109
|
-
`;for(let n of e)r+=`${n.key}
|
|
110
|
-
`,r+=` Type: ${n.type}
|
|
111
|
-
`,r+=` Description: ${n.description}
|
|
112
|
-
`,r+=` Example: ${n.example}
|
|
113
|
-
|
|
114
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
115
|
-
|
|
116
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
117
|
-
`,r+=`|----------|------|-------------|----------|
|
|
118
|
-
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
119
|
-
`;return r}}function RI(e,t,r={}){return Sm(e,t,r,new WeakMap)}function Sm(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return vm(e,t,i,n);if(!$t(t)||!$t(e))return t;return OI(e,t,r,n)}function vm(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return PI(e,t);case"smart":return xI(e,t,n);default:return t}return t}function PI(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>vd(i,n)))r.push(n);return r}function xI(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if($t(t[0])&&$t(e[0]))return DI(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function DI(e,t,r){let n=[...t];for(let i of e){if(!$t(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in i){if(n.find((a)=>$t(a)&&(c in a)&&a[c]===i[c])){s=!0;break}}if(!s)n.push(i)}return n}function OI(e,t,r,n){let i=t;if($t(i)&&n.has(i))return n.get(i);let o={...e};if($t(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let c=i[s],u=o[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if($t(c)&&$t(u))o[s]=Sm(u,c,r,n);else if(Array.isArray(c)||Array.isArray(u))o[s]=vm(u,c,r.arrayMergeMode||"smart",n);else o[s]=c}return o}function wm(e,t,r="replace"){return RI(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function vd(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!vd(e[r],t[r]))return!1;return!0}if($t(e)&&$t(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!vd(e[i],t[i]))return!1}return!0}return!1}function $t(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Im{extensions=Vg;async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1}=r;if(i){let a=Is.getWithFileCheck("file",e);if(a){if(c)console.log(`Configuration loaded from cache: ${e}`);return a}}let u=async()=>{if(!hs(e))return null;try{let a=`?t=${Date.now()}`,p=await import(e+a),f=p.default||p,y="default"in p,b=Object.keys(p).length>0;if(!y&&!b)throw new Ns(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Ns(e,Error("Configuration must export a valid object"),"unknown");let R={config:wm(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Is.setWithFileCheck("file",R,e,o);return R}catch(a){throw a instanceof Error?Cn.configLoad(e,a):Cn.configLoad(e,Error(String(a)))}};if(s)return wd.track("loadFromPath",u,{path:e});return u()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){return Av({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return qg({name:e,alias:t})}checkFileAccess(e){return kI(async()=>hs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!hs(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let c=Fg(e,`${o}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=Fg(e,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!hs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}var NI=/^https?:\/\//;class Cm{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:u=!1}=r,a=async()=>{let p=[],f=[],y={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:c,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,y);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],y);else return this.validateWithJSONSchema(e,t,y)}catch(b){return p.push({path:"",message:`Validation failed: ${b}`,rule:"system"}),{isValid:!1,errors:p,warnings:f}}};if(c)return await wd.track("validateConfiguration",a);return a()}async validateWithSchemaFile(e,t,r){try{if(!_I(t))throw new $s(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new $s(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,u]of Object.entries(t.properties))if(c in s){let a=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],u,a,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(s))if(!c.has(u))i.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:NI},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Vt=new js("bunfig",{showTags:!0});function $I(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Em{fileLoader=new Im;envProcessor=new xd;validator=new Cm;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let u=this.checkCache(s.name||"",s);if(u)return u}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(u){if(s.configFile)throw u;let a=s.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(a)throw u;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let p=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),f=!p&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),y=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(a&&(y||p))throw u;if(f&&(!a||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!a)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(i||o)await this.validateConfiguration(c.config,i,o,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)Vt.warn(`Slow configuration loading detected: ${u.duration}ms for ${s.name}`);c.metrics=u}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let u=Date.now()-t;throw Vt.error(`Configuration loading failed after ${u}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,configFile:o,cwd:s,configDir:c,defaultConfig:u,checkEnv:a=!0,arrayStrategy:p="replace",verbose:f=!1}=e,y=s||Ms.cwd(),b=[];if(o){let L=or(y,o);b.push(L);let P=a?Vi(n,u,f):u,G=await this.fileLoader.tryLoadFromPaths([L],P,{arrayStrategy:p,verbose:f,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!G)throw Cn.configNotFound(n||o,b,i);if(f)Vt.success(`Configuration loaded from explicit path: ${L}`);return this.finalizeResult(G,b,a,n,f)}let C=await this.loadLocalConfiguration(n,i,y,c,u,p,f,a,r);if(C)return b.push(...this.getLocalSearchPaths(n,i,y,c)),this.finalizeResult(C,b,a,n,f);let T=await this.loadHomeConfiguration(n,i,u,p,f,a);if(T)return b.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(T,b,a,n,f);let R=await this.loadPackageJsonConfiguration(n,i,y,u,p,f,a);if(R)return b.push(or(y,"package.json")),this.finalizeResult(R,b,a,n,f);if(b.push(...this.getAllSearchPaths(n,i,y,c)),t)throw Cn.configNotFound(n,b,i);return{...await this.applyEnvironmentVariables(n,u,a,f),warnings:[`No configuration file found for "${n}"${$I(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,c,u){let a=c?Vi(e,i,s):i,p=this.getLocalDirectories(r,n);for(let f of p){if(s)Vt.info(`Searching for configuration in: ${f}`);let y=this.fileLoader.generateConfigPaths(e,f,t),b=await this.fileLoader.tryLoadFromPaths(y,a,{arrayStrategy:o,verbose:s,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(b){if(s)Vt.success(`Configuration loaded from: ${b.source.path}`);return b}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?Vi(e,r,i):r,c=[or(ti(),".config",e),or(ti(),".config"),ti()];for(let u of c){if(i)Vt.info(`Checking home directory: ${u}`);let a=this.fileLoader.generateConfigPaths(e,u,t),p=await this.fileLoader.tryLoadFromPaths(a,s,{arrayStrategy:n,verbose:i});if(p){if(i)Vt.success(`Configuration loaded from home directory: ${p.source.path}`);return p}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let c=s?Vi(e,n,o):n;try{let u=or(r,"package.json");if(!Rv(u))return null;let a={};try{a=JSON.parse(Pv(u,"utf8"))}catch(y){if(o)Vt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let p=a[e],f=e;if(!p&&t){let y=Array.isArray(t)?t:[t];for(let b of y){if(!b)continue;if(a[b]){p=a[b],f=b;break}}}if(p&&typeof p==="object"&&!Array.isArray(p)){if(o)Vt.success(`Configuration loaded from package.json: ${f}`);return{config:wm(c,p,i),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(o)Vt.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Vi(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw Cn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Is.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Is.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return kv({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(or(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[or(ti(),".config",e),or(ti(),".config"),ti()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var cd=new Em;async function Tm(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await cd.loadConfig(e);else n=await cd.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){if(e.configFile)throw n;let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)Vt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await cd.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function Vi(e,t,r=!1){let n=new xd,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let u={...s};for(let[a,p]of Object.entries(s)){let f=[...c,a],y=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((T)=>T.toUpperCase()).join("")}`,`${i}_${f.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],b,C;for(let T of y)if(b=Ms.env[T],b!==void 0){C=T;break}if(b!==void 0&&C)if(typeof p==="boolean")u[a]=["true","1","yes"].includes(b.toLowerCase());else if(typeof p==="number"){let T=Number(b);if(!Number.isNaN(T))u[a]=T}else if(Array.isArray(p))try{u[a]=JSON.parse(b)}catch{u[a]=b.split(",").map((T)=>T.trim())}else u[a]=b;else if(p&&typeof p==="object"&&!Array.isArray(p))u[a]=o(p,f)}return u}return o(t)}var WD=or(Ms.cwd(),"config"),HD=or(Ms.cwd(),"src/generated");var Rm={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},Tn=null;function BI(e){return e.project?.slug===Rm.project?.slug&&Object.keys(e.environments??{}).length===1&&!!e.environments?.production}async function jI(){let e=[Am(process.cwd(),"config","cloud.ts"),Am(process.cwd(),"config","cloud.js")];for(let t of e){if(!MI(t))continue;let r=await import(`${LI(t).href}?t=${Date.now()}`),n=r.tsCloud??r.default?.tsCloud??r.default??r.cloud??r.config;if(n)return n}return null}async function FI(){if(!Tn){if(Tn=await Tm({name:"cloud",defaultConfig:Rm}),BI(Tn))Tn=await jI()??Tn;km(Tn.stateDir)}return Tn}var Pm=FI;var UI=async(e)=>{let t=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),[r,n,i]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);return{code:r,stdout:n,stderr:i}};class Om{async scan(e,t){return Dm(e,t)}async exec(e,t){if(e.trustState!=="pinned")throw Error("SSH host key must be pinned before remote execution.");return UI(["ssh","-p",String(e.sshPort),"-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",`${e.sshUser}@${e.endpoint}`,t])}}var zI=xm,VI=`set -eu; printf '{'; printf '"os":"%s",' "$(. /etc/os-release 2>/dev/null; printf %s "\${PRETTY_NAME:-Linux}")"; printf '"arch":"%s",' "$(uname -m)"; printf '"cpuCores":%s,' "$(getconf _NPROCESSORS_ONLN)"; printf '"memoryBytes":%s,' "$(awk '/MemTotal/{print $2*1024}' /proc/meminfo)"; printf '"diskBytes":%s,' "$(df -B1 / | awk 'NR==2{print $2}')"; printf '"diskFreeBytes":%s,' "$(df -B1 / | awk 'NR==2{print $4}')"; printf '"dnsOk":'; getent hosts example.com >/dev/null && printf true || printf false; printf ',"timeSkewSeconds":0,"tools":{"curl":"'; command -v curl >/dev/null && printf installed; printf '","tar":"'; command -v tar >/dev/null && printf installed; printf '"},"privilege":"'; sudo -n true >/dev/null 2>&1 && printf sudo || printf user; printf '"}'`;class Qi{provider;transport;discoverer;constructor(e,t=new Om,r){this.provider=e;this.transport=t;this.discoverer=r}discover(e){return this.discoverer?.(e)??Promise.resolve([])}async test(e){try{let t=await this.transport.scan(e.endpoint,e.sshPort);return{reachable:!0,hostKeyAlgorithm:t.algorithm,hostKeyFingerprint:zI(t.key),latencyMs:0}}catch{return{reachable:!1,hostKeyAlgorithm:"unknown",hostKeyFingerprint:"",latencyMs:0}}}async validate(e){let t=await this.transport.exec(e,VI);if(t.code!==0)throw Error(`Fleet validation failed: ${t.stderr.trim()||t.code}`);try{return JSON.parse(t.stdout)}catch{throw Error("Fleet validation returned malformed facts.")}}async bootstrap(e,t){let r=await this.transport.exec(e,`sudo -n ts-cloud-agent bootstrap --version 1 --steps ${t.length}`);if(r.code!==0)throw Error(`Fleet bootstrap failed: ${r.stderr.trim()||r.code}`);return{version:"1"}}capabilities(){return{document:{supported:!0,reason:"fleet-capabilities/v1; sha256:driver-contract"},validate:{supported:!0},bootstrap:{supported:!0},heartbeat:{supported:!0},drain:{supported:!0},archive:{supported:!0},terminate:{supported:!1,reason:"Inventory removal never terminates provider infrastructure."}}}}function _m(e,t){return{"fleet.bootstrap":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.get(String(n.serverId??""));if(!i)throw Error("Queued fleet server was not found.");let o=t.find((u)=>u.provider===i.provider);if(!o)throw Error(`No ${i.provider} fleet driver is configured.`);let s=Array.isArray(n.steps)?n.steps.map(String):[];if(r.checkpoint("preflight","Rechecking pinned trust and healthy validation."),i.trustState!=="pinned"||!i.validation?.valid)throw Error("Fleet bootstrap requires pinned trust and a healthy validation report.");r.checkpoint("bootstrap","Applying the reviewed idempotent bootstrap plan.");let c=await o.bootstrap(i,s);return e.update(i.id,{bootstrapVersion:c.version,status:"ready"}),r.checkpoint("verify","Bootstrap completed; heartbeat can now establish freshness."),{serverId:i.id,bootstrapVersion:c.version,steps:s.length}}}}var sr=(e)=>e==null?void 0:String(e),An=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Dd=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),resourceId:String(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:sr(e.provider_id),region:sr(e.region),zone:sr(e.zone),endpoint:String(e.endpoint),sshUser:String(e.ssh_user),sshPort:Number(e.ssh_port),credentialRef:String(e.credential_ref),hostKeyAlgorithm:sr(e.host_key_algorithm),hostKeyFingerprint:sr(e.host_key_fingerprint),pendingHostKey:sr(e.pending_host_key),roles:An(e.roles,[]),labels:An(e.labels,{}),taints:An(e.taints,[]),capacity:An(e.capacity,{}),usage:An(e.usage,{}),capabilities:An(e.capabilities,{}),status:String(e.status),trustState:String(e.trust_state),validation:An(e.validation,void 0),bootstrapVersion:sr(e.bootstrap_version),heartbeatAt:sr(e.heartbeat_at),lastSeenAt:sr(e.last_seen_at),archivedAt:sr(e.archived_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Od{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}get(e){let t=this.control.database.query("SELECT * FROM fleet_servers WHERE id=?").get(e);return t?Dd(t):void 0}list(e,t=!1){return this.control.database.query("SELECT * FROM fleet_servers WHERE project_id=? ORDER BY name").all(e).map(Dd).filter((r)=>t||r.status!=="archived")}findProvider(e,t,r){let n=this.control.database.query("SELECT * FROM fleet_servers WHERE organization_id=? AND provider=? AND provider_id=? AND archived_at IS NULL").get(e,t,r);return n?Dd(n):void 0}create(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO fleet_servers (id,organization_id,project_id,resource_id,name,provider,provider_id,region,zone,endpoint,ssh_user,ssh_port,credential_ref,host_key_algorithm,host_key_fingerprint,pending_host_key,roles,labels,taints,capacity,usage,capabilities,status,trust_state,validation,bootstrap_version,heartbeat_at,last_seen_at,archived_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.resourceId,e.name,e.provider,e.providerId??null,e.region??null,e.zone??null,e.endpoint,e.sshUser,e.sshPort,e.credentialRef,e.hostKeyAlgorithm??null,e.hostKeyFingerprint??null,e.pendingHostKey??null,JSON.stringify(e.roles),JSON.stringify(e.labels),JSON.stringify(e.taints),JSON.stringify(e.capacity),JSON.stringify(e.usage),JSON.stringify(e.capabilities),e.status,e.trustState,JSON.stringify(e.validation??{}),e.bootstrapVersion??null,e.heartbeatAt??null,e.lastSeenAt??null,e.archivedAt??null,r,r]),this.get(t)}update(e,t){let r=this.get(e);if(!r)throw Error("Server was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE fleet_servers SET name=?,provider_id=?,region=?,zone=?,endpoint=?,ssh_user=?,ssh_port=?,credential_ref=?,host_key_algorithm=?,host_key_fingerprint=?,pending_host_key=?,roles=?,labels=?,taints=?,capacity=?,usage=?,capabilities=?,status=?,trust_state=?,validation=?,bootstrap_version=?,heartbeat_at=?,last_seen_at=?,archived_at=?,version=version+1,updated_at=? WHERE id=?",[n.name,n.providerId??null,n.region??null,n.zone??null,n.endpoint,n.sshUser,n.sshPort,n.credentialRef,n.hostKeyAlgorithm??null,n.hostKeyFingerprint??null,n.pendingHostKey??null,JSON.stringify(n.roles),JSON.stringify(n.labels),JSON.stringify(n.taints),JSON.stringify(n.capacity),JSON.stringify(n.usage),JSON.stringify(n.capabilities),n.status,n.trustState,JSON.stringify(n.validation??{}),n.bootstrapVersion??null,n.heartbeatAt??null,n.lastSeenAt??null,n.archivedAt??null,i,e]),this.get(e)}}var qI=/^(?:[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9a-fA-F:]+\])$/;class _d{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new xe(e.control)}driver(e){let t=this.drivers.find((r)=>r.provider===e);if(!t)throw Error(`No ${e} fleet driver is configured.`);return t}enroll(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Server name is invalid.");if(!qI.test(e.endpoint)||e.sshUser==="root"||!e.credentialRef.startsWith("secret://"))throw Error("Enrollment requires a valid endpoint, non-root SSH user, and secret credential reference.");let t=e.providerId?this.store.findProvider(e.organizationId,e.provider,e.providerId):void 0;if(t)return this.store.update(t.id,{endpoint:e.endpoint,region:e.region,zone:e.zone});let r=this.store.control.createResource({projectId:e.projectId,kind:"server",slug:e.name,name:e.name,provider:e.provider,providerId:e.providerId}),n=this.driver(e.provider);return this.store.create({...e,resourceId:r.id,sshPort:e.sshPort??22,labels:e.labels??{},taints:[],capacity:{},usage:{},capabilities:n.capabilities(),status:"pending",trustState:"unverified"})}async test(e){let t=this.store.get(e);if(!t)throw Error("Server was not found.");let r=await this.driver(t.provider).test(t);if(!r.reachable)return this.store.update(e,{status:"unreachable"});if(t.hostKeyFingerprint&&t.hostKeyFingerprint!==r.hostKeyFingerprint)return this.store.update(e,{status:"degraded",trustState:"rotation_pending",pendingHostKey:r.hostKeyFingerprint});return this.store.update(e,{hostKeyAlgorithm:r.hostKeyAlgorithm,hostKeyFingerprint:r.hostKeyFingerprint,pendingHostKey:void 0,trustState:"pinned",status:"validating",lastSeenAt:this.now().toISOString()})}reviewHostKey(e,t){let r=this.store.get(e);if(!r||r.pendingHostKey!==t)throw Error("Pending host key does not match.");return this.store.update(e,{hostKeyFingerprint:t,pendingHostKey:void 0,trustState:"pinned",status:"validating"})}async validate(e){let t=this.store.get(e);if(!t||t.trustState!=="pinned")throw Error("Pin the SSH host key before validation.");let r=await this.driver(t.provider).validate(t),n=[];if(!["x64","arm64","x86_64","aarch64"].includes(r.arch??""))n.push({code:"arch.unsupported",severity:"error",message:"Unsupported architecture.",remediation:"Use x86_64 or arm64 Linux."});for(let s of["curl","tar"])if(!r.tools?.[s])n.push({code:`tool.${s}`,severity:"error",message:`${s} is missing.`,remediation:`Install ${s} before bootstrap.`});if(Math.abs(r.timeSkewSeconds??0)>60)n.push({code:"time.skew",severity:"error",message:"Clock skew exceeds 60 seconds.",remediation:"Enable NTP synchronization."});if(!r.dnsOk)n.push({code:"dns.failed",severity:"error",message:"DNS validation failed.",remediation:"Repair resolver configuration."});let i={valid:!n.some((s)=>s.severity==="error"),facts:r,findings:n,validatedAt:this.now().toISOString(),validatorVersion:"1"},o={cpu:r.cpuCores??0,memoryBytes:r.memoryBytes??0,diskBytes:r.diskBytes??0};return this.store.update(e,{validation:i,capacity:o,status:i.valid?"ready":"degraded"})}bootstrap(e,t=!1){let r=this.store.get(e);if(!r?.validation?.valid)throw Error("A healthy validation report is required.");let n=["install runtime dependencies","install ts-cloud agent","configure heartbeat","verify least-privilege access"];if(!t)return{preview:!0,steps:n};let i=this.queue.enqueue({projectId:r.projectId,resourceId:r.resourceId,kind:"fleet.bootstrap",input:{serverId:e,steps:n},lockKey:`server:${e}`,providerKey:r.provider}).operation;return{preview:!1,steps:n,operation:i}}heartbeat(e,t){let r=this.store.get(e);if(!r)throw Error("Server was not found.");let n=this.now().toISOString();return this.store.update(e,{usage:t.usage,capabilities:t.capabilities??r.capabilities,heartbeatAt:n,lastSeenAt:n,status:r.status==="draining"||r.status==="drained"?r.status:"ready"})}drain(e,t=!1){return this.store.update(e,{status:t?"drained":"draining"})}uncordon(e){return this.store.update(e,{status:"ready"})}archive(e,t){let r=this.store.get(e);if(!r||t!==r.name)throw Error("Exact server name confirmation is required.");return this.store.update(e,{status:"archived",archivedAt:this.now().toISOString()})}}import{createHash as Nd,createPublicKey as Mm,verify as JI}from"node:crypto";function Yi(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Yi).join(",")}]`;return`{${Object.keys(e).sort().map((t)=>`${JSON.stringify(t)}:${Yi(e[t])}`).join(",")}}`}var Lm=(e)=>Nd("sha256").update(Yi(e)).digest("hex"),Fs=(e)=>Nd("sha256").update(Yi(e)).digest("hex"),Bm=(e)=>Nd("sha256").update(Mm(e).export({type:"spki",format:"der"})).digest("hex");function jm(e,t,r){try{return JI(null,Buffer.from(Yi(e)),Mm(r),Buffer.from(t,"base64"))}catch{return!1}}var Nm=(e)=>e.replace(/^v/,"").split(/[.-]/).slice(0,3).map((t)=>Number(t)||0),$m=(e,t)=>{let r=Nm(e),n=Nm(t);for(let i=0;i<3;i++){let o=(r[i]??0)-(n[i]??0);if(o)return o}return 0};function Fm(e,t){let r=[];if(t.schemaVersion<e.minimumSchema)r.push(`schema ${t.schemaVersion} is below ${e.minimumSchema}`);if(t.schemaVersion>e.maximumSchema)r.push(`schema ${t.schemaVersion} is above ${e.maximumSchema}`);if(e.minimumVersion&&$m(t.currentVersion,e.minimumVersion)<0)r.push(`platform ${t.currentVersion} is below ${e.minimumVersion}`);if($m(e.version,t.currentVersion)<=0)r.push(`version ${e.version} is not newer than ${t.currentVersion}`);if(!e.artifacts.some((n)=>n.platform===t.platform&&n.architecture===t.architecture))r.push(`no artifact for ${t.platform}/${t.architecture}`);return{compatible:r.length===0,reasons:r}}var Tr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},nt=(e)=>e==null?void 0:String(e),WI=(e)=>({id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),algorithm:"ed25519",publicKeyPem:String(e.public_key_pem),fingerprint:String(e.fingerprint),revokedAt:nt(e.revoked_at),createdAt:String(e.created_at)}),Um=(e)=>({id:String(e.id),organizationId:String(e.organization_id),version:String(e.version),channel:String(e.channel),publishedAt:String(e.published_at),keyId:String(e.key_id),digest:String(e.digest),document:Tr(e.document,{}),signature:String(e.signature),verificationStatus:String(e.verification_status),compatibility:Tr(e.compatibility,{compatible:!1,reasons:[]}),createdAt:String(e.created_at)}),zm=(e)=>({id:String(e.id),projectId:String(e.project_id),name:String(e.name),schedule:String(e.schedule),timezone:String(e.timezone),durationMinutes:Number(e.duration_minutes),allowedOperations:Tr(e.allowed_operations,[]),requireApproval:Number(e.require_approval)===1,enabled:Number(e.enabled)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Vm=(e)=>({id:String(e.id),projectId:String(e.project_id),manifestId:String(e.manifest_id),windowId:nt(e.window_id),fromVersion:String(e.from_version),strategy:String(e.strategy),batchSize:Number(e.batch_size),healthGate:Tr(e.health_gate,{}),status:String(e.status),currentStage:nt(e.current_stage),backupId:nt(e.backup_id),approvedBy:nt(e.approved_by),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),$d=(e)=>({id:String(e.id),campaignId:String(e.campaign_id),serverId:nt(e.server_id),target:String(e.target),cohort:Number(e.cohort),previousVersion:String(e.previous_version),status:String(e.status),evidence:Tr(e.evidence,{}),error:nt(e.error),startedAt:nt(e.started_at),finishedAt:nt(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),qm=(e)=>({id:String(e.id),projectId:String(e.project_id),kind:String(e.kind),criteria:Tr(e.criteria,{}),candidates:Tr(e.candidates,[]),candidateDigest:String(e.candidate_digest),estimatedBytes:Number(e.estimated_bytes),status:String(e.status),confirmation:nt(e.confirmation),expiresAt:String(e.expires_at),result:Tr(e.result,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Jm=(e)=>({id:String(e.id),projectId:String(e.project_id),backupPolicyId:nt(e.backup_policy_id),recoveryPointId:nt(e.recovery_point_id),topologyId:nt(e.topology_id),scenario:String(e.scenario),isolatedTarget:String(e.isolated_target),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),status:String(e.status),operationId:nt(e.operation_id),evidence:Tr(e.evidence,{}),measuredRpoMinutes:e.measured_rpo_minutes==null?void 0:Number(e.measured_rpo_minutes),measuredRtoMinutes:e.measured_rto_minutes==null?void 0:Number(e.measured_rto_minutes),cleanupVerified:Number(e.cleanup_verified)===1,error:nt(e.error),startedAt:nt(e.started_at),finishedAt:nt(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Md{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}addTrustedKey(e){let t=this.id(),r=this.now().toISOString(),n=Bm(e.publicKeyPem);return this.control.database.run("INSERT INTO platform_trusted_keys (id,organization_id,name,algorithm,public_key_pem,fingerprint,created_at) VALUES (?,?,?,'ed25519',?,?,?)",[t,e.organizationId,e.name,e.publicKeyPem,n,r]),this.key(t)}key(e){let t=this.control.database.query("SELECT * FROM platform_trusted_keys WHERE id=?").get(e);return t?WI(t):void 0}revokeKey(e){return this.control.database.run("UPDATE platform_trusted_keys SET revoked_at=? WHERE id=?",[this.now().toISOString(),e]),this.key(e)}importManifest(e){let t=this.key(e.keyId);if(!t||t.organizationId!==e.organizationId)throw Error("Trusted update key was not found.");if(t.revokedAt)throw Error("Update signing key is revoked.");if(!jm(e.document,e.signature,t.publicKeyPem))throw Error("Update manifest signature is invalid.");let r=Fm(e.document,e.current),n=Lm(e.document),i=this.id(),o=this.now().toISOString();return this.control.database.run("INSERT INTO platform_update_manifests (id,organization_id,version,channel,published_at,key_id,digest,document,signature,verification_status,compatibility,created_at) VALUES (?,?,?,?,?,?,?,?,?,'verified',?,?)",[i,e.organizationId,e.document.version,e.document.channel,new Date(e.document.publishedAt).toISOString(),e.keyId,n,JSON.stringify(e.document),e.signature,JSON.stringify(r),o]),this.manifest(i)}manifest(e){let t=this.control.database.query("SELECT * FROM platform_update_manifests WHERE id=?").get(e);return t?Um(t):void 0}manifests(e){return this.control.database.query("SELECT * FROM platform_update_manifests WHERE organization_id=? ORDER BY published_at DESC").all(e).map(Um)}createWindow(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO maintenance_windows (id,project_id,name,schedule,timezone,duration_minutes,allowed_operations,require_approval,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,1,?,?)",[t,e.projectId,e.name,e.schedule,e.timezone,e.durationMinutes,JSON.stringify(e.allowedOperations),e.requireApproval===!1?0:1,r,r]),this.window(t)}window(e){let t=this.control.database.query("SELECT * FROM maintenance_windows WHERE id=?").get(e);return t?zm(t):void 0}windows(e){return this.control.database.query("SELECT * FROM maintenance_windows WHERE project_id=? ORDER BY name").all(e).map(zm)}createCampaign(e){return this.control.transaction(()=>{let t=this.manifest(e.manifestId);if(!t?.compatibility.compatible||t.verificationStatus!=="verified")throw Error("A verified compatible update manifest is required.");if(!e.backupId)throw Error("A verified pre-upgrade backup is required.");let r=this.id(),n=this.now().toISOString();return this.control.database.run("INSERT INTO platform_upgrade_campaigns (id,project_id,manifest_id,window_id,from_version,strategy,batch_size,health_gate,status,backup_id,approved_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'planned',?,?,?,?)",[r,e.projectId,e.manifestId,e.windowId??null,e.fromVersion,e.strategy,e.batchSize,JSON.stringify(e.healthGate),e.backupId,e.approvedBy??null,n,n]),e.targets.forEach((i,o)=>this.control.database.run("INSERT INTO platform_upgrade_targets (id,campaign_id,server_id,target,cohort,previous_version,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,i.serverId??null,i.target,e.strategy==="canary"?o===0?0:1+Math.floor((o-1)/e.batchSize):Math.floor(o/e.batchSize),i.previousVersion,n,n])),this.campaign(r)})}campaign(e){let t=this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE id=?").get(e);return t?Vm(t):void 0}campaigns(e){return this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE project_id=? ORDER BY created_at DESC").all(e).map(Vm)}targets(e){return this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE campaign_id=? ORDER BY cohort,target").all(e).map($d)}updateCampaign(e,t){let r=this.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n={...r,...t};return this.control.database.run("UPDATE platform_upgrade_campaigns SET status=?,current_stage=?,updated_at=? WHERE id=?",[n.status,n.currentStage??null,this.now().toISOString(),e]),this.campaign(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e);if(!r)throw Error("Upgrade target was not found.");let n={...$d(r),...t};return this.control.database.run("UPDATE platform_upgrade_targets SET status=?,evidence=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.evidence),n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),$d(this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e))}createCleanup(e){let t=[...e.candidates].sort((s,c)=>s.id.localeCompare(c.id)),r=Fs(t),n=this.id(),i=this.now().toISOString(),o=new Date(this.now().getTime()+(e.ttlMinutes??60)*60000).toISOString();return this.control.database.run("INSERT INTO cleanup_plans (id,project_id,kind,criteria,candidates,candidate_digest,estimated_bytes,status,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'preview',?,?,?)",[n,e.projectId,e.kind,JSON.stringify(e.criteria),JSON.stringify(t),r,t.reduce((s,c)=>s+c.bytes,0),o,i,i]),this.cleanup(n)}cleanup(e){let t=this.control.database.query("SELECT * FROM cleanup_plans WHERE id=?").get(e);return t?qm(t):void 0}cleanups(e){return this.control.database.query("SELECT * FROM cleanup_plans WHERE project_id=? ORDER BY created_at DESC").all(e).map(qm)}updateCleanup(e,t){let r=this.cleanup(e);if(!r)throw Error("Cleanup plan was not found.");let n={...r,...t};return this.control.database.run("UPDATE cleanup_plans SET status=?,confirmation=?,result=?,updated_at=? WHERE id=?",[n.status,n.confirmation??null,JSON.stringify(n.result),this.now().toISOString(),e]),this.cleanup(e)}createDrill(e){if(!/^isolated:\/\//.test(e.isolatedTarget))throw Error("DR drills require an isolated target.");let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO disaster_recovery_drills (id,project_id,backup_policy_id,recovery_point_id,topology_id,scenario,isolated_target,expected_rpo_minutes,expected_rto_minutes,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'planned',?,?)",[t,e.projectId,e.backupPolicyId??null,e.recoveryPointId??null,e.topologyId??null,e.scenario,e.isolatedTarget,e.expectedRpoMinutes,e.expectedRtoMinutes,r,r]),this.drill(t)}drill(e){let t=this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE id=?").get(e);return t?Jm(t):void 0}drills(e){return this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE project_id=? ORDER BY created_at DESC").all(e).map(Jm)}updateDrill(e,t){let r=this.drill(e);if(!r)throw Error("DR drill was not found.");let n={...r,...t};return this.control.database.run("UPDATE disaster_recovery_drills SET status=?,operation_id=?,evidence=?,measured_rpo_minutes=?,measured_rto_minutes=?,cleanup_verified=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,n.operationId??null,JSON.stringify(n.evidence),n.measuredRpoMinutes??null,n.measuredRtoMinutes??null,n.cleanupVerified?1:0,n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),this.drill(e)}}function HI(e,t=new Date){if(!e.enabled)return!1;let r=new Date(e.schedule);if(!Number.isNaN(r.getTime()))return t>=r&&t.getTime()<=r.getTime()+e.durationMinutes*60000;let n=/^(\d{2}):(\d{2})$/.exec(e.schedule);if(!n)return!1;let i=new Intl.DateTimeFormat("en-US",{timeZone:e.timezone,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(t),o=Number(i.find((c)=>c.type==="hour")?.value)*60+Number(i.find((c)=>c.type==="minute")?.value),s=Number(n[1])*60+Number(n[2]);return o>=s&&o<s+e.durationMinutes}class Ld{store;now;queue;constructor(e,t,r=()=>new Date){this.store=e;this.now=r;this.queue=t??new xe(e.control)}enqueueCampaign(e,t={}){let r=this.store.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n=r.windowId?this.store.window(r.windowId):void 0;if(n&&!n.allowedOperations.includes("platform.upgrade"))throw Error("Maintenance window does not permit platform upgrades.");if(n&&!t.overrideWindow&&!HI(n,this.now()))throw Error("Upgrade is outside its maintenance window.");if(n?.requireApproval&&!t.approvedBy&&!r.approvedBy)throw Error("Maintenance approval is required.");let i=this.queue.enqueue({projectId:r.projectId,actorId:t.approvedBy,kind:"maintenance.upgrade",input:{campaignId:e},lockKey:"platform-upgrade",providerKey:"platform",timeoutSeconds:7200,cancellationMode:"cooperative",resumePolicy:"fail"}).operation;return{campaign:this.store.updateCampaign(e,{status:"queued"}),operation:i}}async previewCleanup(e,t){let r=t.find((n)=>n.kind===e.kind);if(!r)throw Error(`No ${e.kind} cleanup driver is configured.`);return this.store.createCleanup({...e,candidates:await r.discover(e.criteria)})}enqueueCleanup(e,t){let r=this.store.cleanup(e);if(!r||r.status!=="preview")throw Error("A current cleanup preview is required.");if(new Date(r.expiresAt)<=this.now())throw Error("Cleanup preview expired; generate it again.");let n=`DELETE ${r.candidates.length} ${r.kind}`;if(t!==n)throw Error(`Exact confirmation ${n} is required.`);let i=this.queue.enqueue({projectId:r.projectId,kind:"maintenance.cleanup",input:{planId:e},lockKey:`cleanup:${r.kind}`,providerKey:"cleanup",timeoutSeconds:3600,cancellationMode:"cooperative"}).operation;return{plan:this.store.updateCleanup(e,{status:"approved",confirmation:t}),operation:i}}enqueueDrill(e){let t=this.store.drill(e);if(!t||t.status!=="planned")throw Error("A planned DR drill is required.");let r=this.queue.enqueue({projectId:t.projectId,kind:"maintenance.drill",input:{drillId:e},lockKey:`drill:${t.scenario}:${t.id}`,providerKey:"recovery",timeoutSeconds:7200,cancellationMode:"cooperative"}).operation;return{drill:this.store.updateDrill(e,{status:"queued",operationId:r.id}),operation:r}}}var Bd=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function Wm(e){return{"maintenance.upgrade":async(i)=>{let o=e.store.campaign(String(Bd(i.operation.input).campaignId??""));if(!o||!e.platform)throw Error("Upgrade campaign or platform maintenance driver is unavailable.");let s=e.store.manifest(o.manifestId);if(!s?.compatibility.compatible||s.verificationStatus!=="verified")throw Error("Update manifest is no longer verified and compatible.");let c=s.document.artifacts.find((a)=>a.platform===process.platform&&a.architecture===process.arch)??s.document.artifacts[0];if(!c)throw Error("No update artifact matches this platform.");e.store.updateCampaign(o.id,{status:"running",currentStage:"preflight"});let u=[];try{for(let a of[...new Set(e.store.targets(o.id).map((p)=>p.cohort))].sort((p,f)=>p-f)){e.store.updateCampaign(o.id,{currentStage:`cohort:${a}`});for(let p of e.store.targets(o.id).filter((f)=>f.cohort===a)){i.throwIfCancellationRequested(),i.checkpoint(`download:${p.target}`,"Downloading signed platform artifact."),e.store.updateTarget(p.id,{status:"downloading",startedAt:new Date().toISOString()});let f=await e.platform.download({target:p,artifact:c,signal:i.signal});if(f.sha256!==c.sha256)throw Error(`Artifact checksum mismatch for ${p.target}.`);i.checkpoint(`install:${p.target}`,"Installing verified artifact."),e.store.updateTarget(p.id,{status:"installing"}),await e.platform.install({target:p,path:f.path,version:s.version,signal:i.signal}),u.push(p);let y=await e.platform.health({target:p,gate:o.healthGate});if(!y.healthy)throw Error(`Upgrade health gate failed for ${p.target}.`);e.store.updateTarget(p.id,{status:"healthy",evidence:y.evidence,finishedAt:new Date().toISOString()})}}return e.store.updateCampaign(o.id,{status:"succeeded",currentStage:void 0}),{campaignId:o.id,version:s.version,targets:u.length}}catch(a){e.store.updateCampaign(o.id,{status:"rolling_back",currentStage:"rollback"});for(let p of u.reverse())e.store.updateTarget(p.id,{status:"rolling_back"}),await e.platform.rollback({target:p,version:p.previousVersion,signal:i.signal}),e.store.updateTarget(p.id,{status:"rolled_back",finishedAt:new Date().toISOString()});throw e.store.updateCampaign(o.id,{status:"rolled_back",currentStage:void 0}),a}},"maintenance.cleanup":async(i)=>{let o=e.store.cleanup(String(Bd(i.operation.input).planId??""));if(!o||o.status!=="approved")throw Error("Approved cleanup plan was not found.");if(Fs([...o.candidates].sort((p,f)=>p.id.localeCompare(f.id)))!==o.candidateDigest)throw Error("Cleanup candidate set changed after preview.");let s=e.cleanup?.find((p)=>p.kind===o.kind);if(!s)throw Error(`No ${o.kind} cleanup driver is configured.`);e.store.updateCleanup(o.id,{status:"running"});let c=[],u=[];for(let p of o.candidates){i.throwIfCancellationRequested();try{await s.remove(p),c.push(p.id)}catch(f){u.push({id:p.id,error:f instanceof Error?f.message:String(f)})}}let a=u.length?c.length?"partial":"failed":"succeeded";if(e.store.updateCleanup(o.id,{status:a,result:{removed:c,failed:u,reclaimedBytes:o.candidates.filter((p)=>c.includes(p.id)).reduce((p,f)=>p+f.bytes,0)}}),u.length)throw Error(`Cleanup failed for ${u.length} candidate(s).`);return{planId:o.id,removed:c.length,reclaimedBytes:o.estimatedBytes}},"maintenance.drill":async(i)=>{let o=e.store.drill(String(Bd(i.operation.input).drillId??""));if(!o)throw Error("DR drill was not found.");let s=e.recovery?.find((f)=>f.scenario===o.scenario);if(!s)throw Error(`No ${o.scenario} recovery driver is configured.`);let c=new Date;e.store.updateDrill(o.id,{status:"restoring",startedAt:c.toISOString()});let u=o.isolatedTarget,a={},p={};try{i.checkpoint("restore","Restoring into isolated drill target.");let f=await s.restore({drill:o,signal:i.signal});if(!f.target.startsWith("isolated://"))throw Error("Recovery driver attempted a non-isolated target.");u=f.target,a=f.evidence;let y=(c.getTime()-new Date(f.recoveryPointAt).getTime())/60000;e.store.updateDrill(o.id,{status:"verifying",measuredRpoMinutes:y,evidence:{restore:a}}),i.checkpoint("verify","Running recovery health checks without production traffic.");let b=await s.verify({drill:o,target:u});p=b.evidence;let C=(Date.now()-c.getTime())/60000;if(!b.healthy||y>o.expectedRpoMinutes||C>o.expectedRtoMinutes)throw Error("DR drill failed its health, RPO, or RTO objective.");e.store.updateDrill(o.id,{measuredRpoMinutes:y,measuredRtoMinutes:C,evidence:{restore:a,verify:p}})}catch(f){throw e.store.updateDrill(o.id,{status:"failed",error:f instanceof Error?f.message:String(f),evidence:{restore:a,verify:p}}),f}finally{e.store.updateDrill(o.id,{status:"cleaning"});try{await s.cleanup({drill:o,target:u});let f=e.store.drill(o.id);e.store.updateDrill(o.id,{status:f.error?"failed":"passed",cleanupVerified:!0,finishedAt:new Date().toISOString()})}catch(f){e.store.updateDrill(o.id,{status:"cleanup_required",cleanupVerified:!1,error:f instanceof Error?f.message:String(f),finishedAt:new Date().toISOString()})}}return{drillId:o.id,status:e.store.drill(o.id).status}}}}var Hm={releases:{select:"SELECT id,created_at,0 bytes FROM releases WHERE project_id=? AND pinned=0 AND status IN ('failed','rolled_back','superseded') AND created_at<?",remove:"DELETE FROM releases WHERE id=?"},artifacts:{select:"SELECT a.id,a.created_at,a.size bytes FROM release_artifacts a WHERE a.organization_id=? AND NOT EXISTS(SELECT 1 FROM releases r WHERE r.artifact_id=a.id) AND a.created_at<?",remove:"DELETE FROM release_artifacts WHERE id=?"},operations:{select:"SELECT id,created_at,0 bytes FROM operations WHERE project_id=? AND state IN ('succeeded','failed','cancelled','timed_out') AND updated_at<?",remove:"DELETE FROM operations WHERE id=?"},logs:{select:"SELECT l.id,l.created_at,length(l.message) bytes FROM operation_logs l JOIN operations o ON o.id=l.operation_id WHERE o.project_id=? AND o.state IN ('succeeded','failed','cancelled','timed_out') AND l.created_at<?",remove:"DELETE FROM operation_logs WHERE id=?"},previews:{select:"SELECT id,created_at,0 bytes FROM preview_instances WHERE project_id=? AND status IN ('destroyed','failed') AND updated_at<?",remove:"DELETE FROM preview_instances WHERE id=?"},snapshots:{select:"SELECT id,created_at,size_bytes bytes FROM recovery_points WHERE project_id=? AND pinned=0 AND held=0 AND status IN ('failed','deleted') AND created_at<?",remove:"DELETE FROM recovery_points WHERE id=?"},orphaned_resources:{select:"SELECT id,created_at,COALESCE(capacity_bytes,0) bytes FROM persistent_volumes WHERE project_id=? AND status='orphaned' AND orphaned_at<?",remove:"UPDATE persistent_volumes SET status='deleted',deleted_at=datetime('now'),updated_at=datetime('now') WHERE id=? AND status='orphaned'"}};class jd{kind;control;projectId;organizationId;constructor(e,t,r,n){this.kind=e;this.control=t;this.projectId=r;this.organizationId=n}async discover(e){let t=Math.max(1,Math.min(3650,Number(e.olderThanDays??30))),r=new Date(Date.now()-t*86400000).toISOString(),n=Hm[this.kind],i=this.kind==="artifacts"?this.organizationId:this.projectId;return this.control.database.query(n.select).all(i,r).map((s)=>({id:String(s.id),kind:this.kind,label:`${this.kind}:${String(s.id)}`,bytes:Number(s.bytes??0),metadata:{createdAt:String(s.created_at)}}))}async remove(e){if(this.control.database.run(Hm[this.kind].remove,[e.id]).changes!==1)throw Error(`${e.label} changed or is no longer removable.`)}}var Wt=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Et=(e)=>e==null?void 0:String(e),Qm=()=>({cpu:0,memoryBytes:0,diskBytes:0,gpu:0}),gi=(e={})=>({...Qm(),...e});function Gm(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),purpose:String(e.purpose),backend:String(e.backend),region:Et(e.region),architecture:Et(e.architecture),labels:Wt(e.labels,{}),requiredServerLabels:Wt(e.required_server_labels,{}),toleratedTaints:Wt(e.tolerated_taints,[]),capacity:gi(Wt(e.capacity,{})),reserved:Wt(e.reserved,{}),maxWorkloads:Number(e.max_workloads),costWeight:Number(e.cost_weight),spreadKey:Et(e.spread_key),concurrency:Number(e.concurrency),ephemeralWorkspaces:Number(e.ephemeral_workspaces)===1,allowProductionSecrets:Number(e.allow_production_secrets)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Km(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:Et(e.environment_id),resourceId:String(e.resource_id),releaseId:Et(e.release_id),poolId:String(e.pool_id),serverId:Et(e.server_id),purpose:String(e.purpose),requirements:Wt(e.requirements,{}),decision:Wt(e.decision,{}),stateful:Number(e.stateful)===1,autoReschedule:Number(e.auto_reschedule)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function GI(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:Et(e.resource_id),poolId:String(e.pool_id),placementId:Et(e.placement_id),operationId:Et(e.operation_id),sourceSha:String(e.source_sha),buildSpec:Wt(e.build_spec,{}),credentialPolicy:Wt(e.credential_policy,{productionSecrets:!1,shortLivedTokenExpiresAt:""}),workspace:Et(e.workspace),cacheKey:Et(e.cache_key),artifactUri:Et(e.artifact_uri),artifactDigest:Et(e.artifact_digest),status:String(e.status),cleanupAt:Et(e.cleanup_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Fd{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}createPool(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO capacity_pools (id,organization_id,project_id,name,purpose,backend,region,architecture,labels,required_server_labels,tolerated_taints,capacity,reserved,max_workloads,cost_weight,spread_key,concurrency,ephemeral_workspaces,allow_production_secrets,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.purpose,e.backend,e.region??null,e.architecture??null,JSON.stringify(e.labels),JSON.stringify(e.requiredServerLabels),JSON.stringify(e.toleratedTaints),JSON.stringify(gi(e.capacity)),"{}",e.maxWorkloads,e.costWeight,e.spreadKey??null,e.concurrency,e.ephemeralWorkspaces?1:0,e.allowProductionSecrets?1:0,e.status,r,r]),this.getPool(t)}getPool(e){let t=this.control.database.query("SELECT * FROM capacity_pools WHERE id=?").get(e);return t?Gm(t):void 0}listPools(e){return this.control.database.query("SELECT * FROM capacity_pools WHERE project_id=? ORDER BY name").all(e).map(Gm)}updatePool(e,t){let r=this.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE capacity_pools SET status=?,reserved=?,capacity=?,concurrency=?,version=version+1,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.reserved),JSON.stringify(n.capacity),n.concurrency,i,e]),this.getPool(e)}addMember(e,t,r={}){let n=this.now().toISOString();this.control.database.run("INSERT INTO capacity_pool_members (pool_id,server_id,capacity_override,status,created_at,updated_at) VALUES (?,?,?,'active',?,?) ON CONFLICT(pool_id,server_id) DO UPDATE SET capacity_override=excluded.capacity_override,status='active',updated_at=excluded.updated_at",[e,t,JSON.stringify(r),n,n])}members(e){return this.control.database.query("SELECT * FROM capacity_pool_members WHERE pool_id=? ORDER BY server_id").all(e).map((t)=>({serverId:String(t.server_id),status:String(t.status),capacityOverride:Wt(t.capacity_override,{})}))}memberStatus(e,t,r){this.control.database.run("UPDATE capacity_pool_members SET status=?,updated_at=? WHERE pool_id=? AND server_id=?",[r,this.now().toISOString(),e,t])}listPlacements(e,t){let r=this.control.database.query("SELECT * FROM workload_placements WHERE project_id=? ORDER BY created_at,id").all(e).map(Km);return t?.length?r.filter((n)=>t.includes(n.status)):r}getPlacement(e){let t=this.control.database.query("SELECT * FROM workload_placements WHERE id=?").get(e);return t?Km(t):void 0}activeUsage(e,t){let r=this.control.database.query("SELECT l.resources,l.server_id FROM capacity_leases l WHERE l.pool_id=? AND l.state='active' AND l.expires_at>?").all(e,this.now().toISOString()),n=t?r.filter((i)=>String(i.server_id)===t):r;return{resources:n.reduce((i,o)=>{let s=gi(Wt(o.resources,{}));for(let c of Object.keys(i))i[c]+=s[c];return i},Qm()),count:n.length}}expireLeases(){return this.control.database.run("UPDATE capacity_leases SET state='expired',updated_at=? WHERE state='active' AND expires_at<=?",[this.now().toISOString(),this.now().toISOString()]).changes}reserve(e){return this.control.transaction(()=>{this.expireLeases();let t=this.id(),r=this.id(),n=this.now().toISOString(),i=new Date(this.now().getTime()+(e.requirements.leaseSeconds??300)*1000).toISOString();return this.control.database.run("INSERT INTO workload_placements (id,project_id,environment_id,resource_id,release_id,pool_id,server_id,purpose,requirements,decision,stateful,auto_reschedule,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'reserved',?,?)",[t,e.projectId,e.environmentId??null,e.resourceId,e.releaseId??null,e.decision.poolId,e.decision.serverId??null,e.requirements.purpose,JSON.stringify(e.requirements),JSON.stringify(e.decision),e.requirements.stateful?1:0,e.requirements.autoReschedule&&!e.requirements.stateful?1:0,n,n]),this.control.database.run("INSERT INTO capacity_leases (id,placement_id,pool_id,server_id,resources,state,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,'active',?,?,?)",[r,t,e.decision.poolId,e.decision.serverId??null,JSON.stringify(gi(e.requirements.resources)),i,n,n]),this.getPlacement(t)})}transitionPlacement(e,t){if(!this.getPlacement(e))throw Error("Placement was not found.");let n=this.now().toISOString();if(this.control.database.run("UPDATE workload_placements SET status=?,version=version+1,updated_at=? WHERE id=?",[t,n,e]),["released","failed","blocked"].includes(t))this.control.database.run("UPDATE capacity_leases SET state='released',updated_at=? WHERE placement_id=? AND state='active'",[n,e]);return this.getPlacement(e)}createBuild(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO remote_builds (id,project_id,resource_id,pool_id,placement_id,operation_id,source_sha,build_spec,credential_policy,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'queued',?,?)",[t,e.projectId,e.resourceId??null,e.poolId,e.placementId??null,e.operationId??null,e.sourceSha,JSON.stringify(e.buildSpec),JSON.stringify({productionSecrets:!1,shortLivedTokenExpiresAt:e.tokenExpiresAt}),r,r]),this.getBuild(t)}getBuild(e){let t=this.control.database.query("SELECT * FROM remote_builds WHERE id=?").get(e);return t?GI(t):void 0}updateBuild(e,t){let r=this.getBuild(e);if(!r)throw Error("Remote build was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE remote_builds SET operation_id=?,workspace=?,cache_key=?,artifact_uri=?,artifact_digest=?,status=?,cleanup_at=?,updated_at=? WHERE id=?",[n.operationId??null,n.workspace??null,n.cacheKey??null,n.artifactUri??null,n.artifactDigest??null,n.status,n.cleanupAt??null,i,e]),this.getBuild(e)}}var Us=["cpu","memoryBytes","diskBytes","gpu"],Ym=(e,t={})=>Object.entries(t).every(([r,n])=>e[r]===n),KI=(e,t,r)=>Object.fromEntries(Us.map((n)=>[n,Math.max(0,e[n]-t[n]-(r[n]??0))])),QI=(e,t)=>Us.every((r)=>e[r]>=(t[r]??0)),YI=(e,t)=>Us.reduce((r,n)=>r+(t[n]??0)/(e[n]||1),0);class Ud{store;fleet;constructor(e,t){this.store=e;this.fleet=t}poolCandidates(e,t,r){let n=[];for(let i of this.store.listPools(e)){if(i.id===r)continue;let o=[];if(i.status!=="active")o.push(`pool is ${i.status}`);if(i.purpose!==t.purpose)o.push(`purpose is ${i.purpose}`);if(t.region&&i.region!==t.region)o.push(`region is ${i.region??"unset"}`);if(t.architecture&&i.architecture!==t.architecture)o.push(`architecture is ${i.architecture??"unset"}`);if(!Ym(i.labels,t.labels))o.push("pool labels do not match");if(i.backend==="server"){let s=this.store.members(i.id);if(!s.length)n.push(this.decision(i,void 0,t,[...o,"pool has no servers"]));for(let c of s){let u=this.fleet.get(c.serverId),a=[...o];if(!u)a.push("server is missing");else this.serverReasons(i,u,c.status,t,a);n.push(this.decision(i,u,t,a,c.capacityOverride))}}else n.push(this.decision(i,void 0,t,o))}return n.sort((i,o)=>Number(o.eligible)-Number(i.eligible)||i.score.cost-o.score.cost||i.score.spread-o.score.spread||i.score.fit-o.score.fit||i.poolName.localeCompare(o.poolName)||(i.serverId??"").localeCompare(o.serverId??""))}serverReasons(e,t,r,n,i){if(r!=="active")i.push(`member is ${r}`);if(t.status!=="ready")i.push(`server is ${t.status}`);if(!t.roles.includes(n.purpose==="build"?"build":n.purpose))i.push(`server lacks ${n.purpose} role`);if(!Ym(t.labels,e.requiredServerLabels))i.push("server labels do not match pool selector");for(let o of t.taints)if(!e.toleratedTaints.includes(o))i.push(`taint ${o} is not tolerated`)}decision(e,t,r,n,i={}){let o=gi({...t?.capacity,...i}),s=t?Object.fromEntries(Us.map((a)=>[a,Math.min(e.capacity[a],o[a])])):e.capacity,c=this.store.activeUsage(e.id,t?.id),u=KI(s,c.resources,e.reserved);if(c.count>=e.maxWorkloads)n.push("workload limit reached");if(r.purpose==="build"&&c.count>=e.concurrency)n.push("build concurrency reached");if(!QI(u,r.resources))n.push("insufficient capacity");return{poolId:e.id,poolName:e.name,serverId:t?.id,eligible:n.length===0,reasons:n,available:u,score:{fit:YI(u,r.resources),spread:c.count,cost:e.costWeight}}}explain(e,t){return this.poolCandidates(e,t)}place(e){return this.store.control.transaction(()=>{let t=this.poolCandidates(e.projectId,e.requirements).find((r)=>r.eligible);if(!t)throw Error(`No eligible capacity: ${this.explain(e.projectId,e.requirements).flatMap((r)=>r.reasons).join("; ")}`);return this.store.reserve({...e,decision:t})})}activate(e){return this.store.transitionPlacement(e,"active")}release(e){return this.store.transitionPlacement(e,"released")}drainPool(e){let t=this.store.updatePool(e,{status:"draining"}),r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["reserved","active"]).filter((o)=>o.poolId===e)){if(i.stateful){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"moving");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id)),this.store.transitionPlacement(i.id,"released")}return{pool:t,moved:r,blocked:n}}drainServer(e,t){this.store.memberStatus(e,t,"draining");let r=this.store.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n=[],i=[];for(let o of this.store.listPlacements(r.projectId,["reserved","active"]).filter((s)=>s.poolId===e&&s.serverId===t)){if(o.stateful){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}this.store.transitionPlacement(o.id,"moving");let s=this.poolCandidates(o.projectId,o.requirements).find((u)=>u.eligible);if(!s){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}let c=this.store.reserve({projectId:o.projectId,environmentId:o.environmentId,resourceId:o.resourceId,releaseId:o.releaseId,requirements:o.requirements,decision:s});n.push(this.activate(c.id)),this.store.transitionPlacement(o.id,"released")}return{moved:n,blocked:i}}reconcileFailure(e){let t=this.fleet.get(e);if(!t)throw Error("Server was not found.");let r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["active"]).filter((o)=>o.serverId===e)){if(i.stateful||!i.autoReschedule){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"failed");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id))}return{rescheduled:r,blocked:n}}}var Ar=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Mt=(e)=>e==null?void 0:String(e),Xm=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Mt(e.environment_id),name:String(e.name),hostname:String(e.hostname),homeRegion:String(e.home_region),regions:Ar(e.regions,[]),trafficPolicy:String(e.traffic_policy),dataPolicy:Ar(e.data_policy,{replicate:[],maxLagSeconds:60,retainOnDestroy:!0}),status:String(e.status),activeRegion:String(e.active_region),revision:Mt(e.revision),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),zd=(e)=>({id:String(e.id),topologyId:String(e.topology_id),region:String(e.region),role:String(e.role),provider:String(e.provider),stackId:Mt(e.stack_id),stackRevision:Mt(e.stack_revision),status:String(e.status),health:Ar(e.health,{}),lastHealthyAt:Mt(e.last_healthy_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Vd=(e)=>({id:String(e.id),topologyId:String(e.topology_id),kind:String(e.kind),sourceRegion:String(e.source_region),targetRegion:String(e.target_region),config:Ar(e.config,{}),status:String(e.status),checkpoint:Mt(e.checkpoint),lagSeconds:e.lag_seconds==null?void 0:Number(e.lag_seconds),lastVerifiedAt:Mt(e.last_verified_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),qd=(e)=>({id:String(e.id),topologyId:String(e.topology_id),hostname:String(e.hostname),dnsProvider:String(e.dns_provider),cdnEnabled:Number(e.cdn_enabled)===1,wafEnabled:Number(e.waf_enabled)===1,weights:Ar(e.weights,{}),desiredWeights:Ar(e.desired_weights,{}),status:String(e.status),providerState:Ar(e.provider_state,{}),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Zm=(e)=>({id:String(e.id),topologyId:String(e.topology_id),operationId:Mt(e.operation_id),kind:String(e.kind),requestedRegion:Mt(e.requested_region),revision:Mt(e.revision),plan:Ar(e.plan,[]),currentStep:Mt(e.current_step),completedSteps:Ar(e.completed_steps,[]),status:String(e.status),error:Mt(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Jd{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}create(e){return this.control.transaction(()=>{if(e.regions.length<2||new Set(e.regions.map((o)=>o.region)).size!==e.regions.length||e.regions.filter((o)=>o.role==="primary").length!==1)throw Error("A topology requires unique regions and exactly one primary.");let t=e.regions.find((o)=>o.role==="primary"),r=this.id(),n=this.now().toISOString();this.control.database.run("INSERT INTO regional_topologies (id,organization_id,project_id,environment_id,name,hostname,home_region,regions,traffic_policy,data_policy,status,active_region,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,'draft',?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.name,e.hostname,t.region,JSON.stringify(e.regions),e.trafficPolicy,JSON.stringify(e.dataPolicy),t.region,n,n]);for(let o of e.regions)this.control.database.run("INSERT INTO regional_targets (id,topology_id,region,role,provider,status,created_at,updated_at) VALUES (?,?,?,?,?,'pending',?,?)",[this.id(),r,o.region,o.role,o.provider,n,n]);for(let o of e.dataPolicy.replicate)for(let s of e.regions)for(let c of e.regions.filter((u)=>u.region!==s.region))this.control.database.run("INSERT INTO regional_replication_channels (id,topology_id,kind,source_region,target_region,config,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,o,s.region,c.region,"{}",n,n]);let i=Object.fromEntries(e.regions.map((o)=>[o.region,o.region===t.region?100:0]));return this.control.database.run("INSERT INTO regional_traffic_routes (id,topology_id,hostname,dns_provider,cdn_enabled,waf_enabled,weights,desired_weights,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'pending',?,?)",[this.id(),r,e.hostname,e.dnsProvider??"route53",e.cdnEnabled?1:0,e.wafEnabled?1:0,JSON.stringify(i),JSON.stringify(i),n,n]),this.get(r)})}get(e){let t=this.control.database.query("SELECT * FROM regional_topologies WHERE id=?").get(e);return t?Xm(t):void 0}list(e){return this.control.database.query("SELECT * FROM regional_topologies WHERE project_id=? ORDER BY name").all(e).map(Xm)}targets(e){return this.control.database.query("SELECT * FROM regional_targets WHERE topology_id=? ORDER BY role,region").all(e).map(zd)}channels(e){return this.control.database.query("SELECT * FROM regional_replication_channels WHERE topology_id=? ORDER BY kind,target_region").all(e).map(Vd)}route(e){let t=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE topology_id=?").get(e);return t?qd(t):void 0}updateTopology(e,t){let r=this.get(e);if(!r)throw Error("Regional topology was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_topologies SET status=?,active_region=?,revision=?,regions=?,version=version+1,updated_at=? WHERE id=?",[n.status,n.activeRegion,n.revision??null,JSON.stringify(n.regions),i,e]),this.get(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e);if(!r)throw Error("Regional target was not found.");let n=zd(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_targets SET role=?,stack_id=?,stack_revision=?,status=?,health=?,last_healthy_at=?,version=version+1,updated_at=? WHERE id=?",[i.role,i.stackId??null,i.stackRevision??null,i.status,JSON.stringify(i.health),i.lastHealthyAt??null,o,e]),zd(this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e))}updateChannel(e,t){let r=this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e);if(!r)throw Error("Replication channel was not found.");let n=Vd(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_replication_channels SET status=?,checkpoint=?,lag_seconds=?,last_verified_at=?,version=version+1,updated_at=? WHERE id=?",[i.status,i.checkpoint??null,i.lagSeconds??null,i.lastVerifiedAt??null,o,e]),Vd(this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e))}updateRoute(e,t){let r=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e);if(!r)throw Error("Traffic route was not found.");let n=qd(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_traffic_routes SET weights=?,desired_weights=?,status=?,provider_state=?,version=version+1,updated_at=? WHERE id=?",[JSON.stringify(i.weights),JSON.stringify(i.desiredWeights),i.status,JSON.stringify(i.providerState),o,e]),qd(this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e))}createExecution(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO regional_executions (id,topology_id,operation_id,kind,requested_region,revision,plan,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'queued',?,?)",[t,e.topologyId,e.operationId??null,e.kind,e.requestedRegion??null,e.revision??null,JSON.stringify(e.plan),r,r]),this.execution(t)}execution(e){let t=this.control.database.query("SELECT * FROM regional_executions WHERE id=?").get(e);return t?Zm(t):void 0}executions(e){return this.control.database.query("SELECT * FROM regional_executions WHERE topology_id=? ORDER BY created_at DESC").all(e).map(Zm)}updateExecution(e,t){let r=this.execution(e);if(!r)throw Error("Regional execution was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_executions SET operation_id=?,current_step=?,completed_steps=?,status=?,error=?,updated_at=? WHERE id=?",[n.operationId??null,n.currentStep??null,JSON.stringify(n.completedSteps),n.status,n.error??null,i,e]),this.execution(e)}}class Wd{store;queue;constructor(e,t){this.store=e;this.queue=t??new xe(e.control)}create(e){return this.store.create(e)}plan(e,t,r){if(!this.store.get(e))throw Error("Regional topology was not found.");let i=this.store.targets(e),o=this.store.channels(e);if(t==="rollout")return[...i.filter((s)=>s.role==="secondary").map((s)=>`apply:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`apply:${s.region}`),...o.map((s)=>`replicate:${s.kind}:${s.targetRegion}`),"traffic:activate"];if(t==="failover"||t==="failback")return[`health:${r}`,`replication:${r}`,`traffic:${r}`,`roles:${r}`];if(t==="destroy")return["traffic:drain",...i.filter((s)=>s.role==="secondary").map((s)=>`delete:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`delete:${s.region}`),"complete"];return["observe","repair"]}enqueue(e){let t=this.store.get(e.topologyId);if(!t)throw Error("Regional topology was not found.");if(["failover","failback"].includes(e.kind)&&(!e.targetRegion||!t.regions.some((o)=>o.region===e.targetRegion)))throw Error("A topology target region is required.");if(e.kind==="failover"&&e.targetRegion===t.activeRegion)throw Error("Target region is already active.");if((e.kind==="destroy"||e.deleteData)&&e.confirmation!==t.name)throw Error("Exact topology name confirmation is required.");if(e.deleteData&&t.dataPolicy.retainOnDestroy)throw Error("Topology policy requires regional data retention.");if(e.kind==="rollout"&&!/^[A-Za-z0-9._:@/-]{7,200}$/.test(e.revision??""))throw Error("An immutable revision is required.");let r=this.plan(t.id,e.kind,e.targetRegion),n=this.store.createExecution({topologyId:t.id,kind:e.kind,requestedRegion:e.targetRegion,revision:e.revision,plan:r}),i=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,kind:`region.${e.kind}`,input:{executionId:n.id,manifest:e.manifest??{},deleteData:e.deleteData===!0},lockKey:`regional-topology:${t.id}`,providerKey:"multi-region",timeoutSeconds:7200,cancellationMode:"provider_non_cancellable",resumePolicy:"requeue",maxAttempts:3}).operation;return this.store.updateExecution(n.id,{operationId:i.id}),{execution:this.store.execution(n.id),operation:i}}}var XI=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function ef(e,t){let r=(a)=>{let p=t.find((f)=>f.provider===a.provider);if(!p)throw Error(`No ${a.provider} regional driver is configured.`);return p},n=(a,p,f)=>{a.throwIfCancellationRequested(),a.checkpoint(f,f),e.updateExecution(p.id,{status:"running",currentStep:f,completedSteps:[...e.execution(p.id).completedSteps,f]})},i=async(a,p)=>{let f=e.route(a.id);if(!f)throw Error("Regional traffic route was not found.");let y=e.targets(a.id).find((C)=>C.region===a.activeRegion)??e.targets(a.id)[0];if(!y)throw Error("Regional traffic target was not found.");e.updateRoute(f.id,{status:"applying",desiredWeights:p});let b=await r(y).applyTraffic({route:e.route(a.id),topology:a,weights:p});e.updateRoute(f.id,{status:Object.values(p).every((C)=>C===0)?"drained":"in_sync",weights:p,providerState:b.providerState})},o=async(a,p,f,y)=>{e.updateTopology(f.id,{status:"provisioning"});let b=p.revision,C=y.manifest??{},T=e.targets(f.id).sort((x,L)=>Number(x.role==="primary")-Number(L.role==="primary"));for(let x of T){n(a,p,`apply:${x.region}`),e.updateTarget(x.id,{status:"provisioning"});let L=await r(x).applyStack({target:x,revision:b,manifest:C,signal:a.signal}),P=await r(x).health({target:e.updateTarget(x.id,{stackId:L.stackId,stackRevision:b})});if(!P.healthy)throw Error(`Regional health gate failed in ${x.region}.`);e.updateTarget(x.id,{status:"ready",health:P.evidence,lastHealthyAt:new Date().toISOString()})}for(let x of e.channels(f.id)){n(a,p,`replicate:${x.kind}:${x.targetRegion}`),e.updateChannel(x.id,{status:"configuring"});let L=T.find((ae)=>ae.region===x.sourceRegion),P=await r(L).configureReplication({channel:x,topology:f}),G=await r(L).verifyReplication({channel:e.updateChannel(x.id,{checkpoint:P.checkpoint,lagSeconds:P.lagSeconds}),topology:f});if(!G.healthy||G.lagSeconds>f.dataPolicy.maxLagSeconds)throw Error(`${x.kind} replication to ${x.targetRegion} exceeds the RPO.`);e.updateChannel(x.id,{status:"in_sync",checkpoint:G.checkpoint,lagSeconds:G.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,p,"traffic:activate");let R=Object.fromEntries(f.regions.map((x)=>[x.region,x.region===f.activeRegion?100:0]));return await i(f,R),e.updateTopology(f.id,{status:"ready",revision:b}),{revision:b,activeRegion:f.activeRegion}},s=async(a,p,f)=>{let y=p.requestedRegion,b=e.targets(f.id).find((R)=>R.region===y);if(!b)throw Error("Requested regional target was not found.");e.updateTopology(f.id,{status:p.kind==="failover"?"failing_over":"failing_back"}),n(a,p,`health:${y}`);let C=await r(b).health({target:b});if(!C.healthy)throw Error(`Target region ${y} is unhealthy.`);e.updateTarget(b.id,{status:"ready",health:C.evidence,lastHealthyAt:new Date().toISOString()}),n(a,p,`replication:${y}`);for(let R of e.channels(f.id).filter((x)=>x.targetRegion===y)){let x=await r(b).verifyReplication({channel:R,topology:f});if(!x.healthy||x.lagSeconds>f.dataPolicy.maxLagSeconds)throw Error(`${R.kind} replication is outside the failover RPO.`);e.updateChannel(R.id,{status:"in_sync",checkpoint:x.checkpoint,lagSeconds:x.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,p,`traffic:${y}`),await i(f,Object.fromEntries(f.regions.map((R)=>[R.region,R.region===y?100:0]))),n(a,p,`roles:${y}`);let T=f.regions.map((R)=>({...R,role:R.region===y?"primary":"secondary"}));for(let R of e.targets(f.id))e.updateTarget(R.id,{role:R.region===y?"primary":"secondary"});return e.updateTopology(f.id,{status:p.kind==="failover"?"failed_over":"ready",activeRegion:y,regions:T}),{activeRegion:y}},c=async(a,p,f,y)=>{e.updateTopology(f.id,{status:"destroying"}),n(a,p,"traffic:drain"),await i(f,Object.fromEntries(f.regions.map((C)=>[C.region,0])));let b=y.deleteData!==!0;for(let C of e.targets(f.id).sort((T,R)=>Number(T.role==="primary")-Number(R.role==="primary")))n(a,p,`delete:${C.region}`),e.updateTarget(C.id,{status:"deleting"}),await r(C).deleteStack({target:C,retainData:b,signal:a.signal}),e.updateTarget(C.id,{status:"deleted"});return n(a,p,"complete"),e.updateTopology(f.id,{status:"destroyed"}),{destroyed:!0,dataRetained:b}},u=async(a)=>{let p=XI(a.operation.input),f=e.execution(String(p.executionId??""));if(!f)throw Error("Regional execution was not found.");let y=e.get(f.topologyId);if(!y)throw Error("Regional topology was not found.");try{let b;if(f.kind==="rollout")b=await o(a,f,y,p);else if(f.kind==="failover"||f.kind==="failback")b=await s(a,f,y);else if(f.kind==="destroy")b=await c(a,f,y,p);else throw Error("Regional reconciliation is not configured.");return e.updateExecution(f.id,{status:"succeeded",currentStep:void 0}),{executionId:f.id,...b}}catch(b){if(e.updateExecution(f.id,{status:a.cancellationRequested()?"cancelled":"failed",error:b instanceof Error?b.message:String(b)}),e.get(y.id)?.status!=="destroyed")e.updateTopology(y.id,{status:"failed"});throw b}};return{"region.rollout":u,"region.failover":u,"region.failback":u,"region.destroy":u,"region.reconcile":u}}class Hd{provider;reason;constructor(e,t="Configure a regional provider transport before executing this operation."){this.provider=e;this.reason=t}fail(){throw Error(this.reason)}async applyStack(){return this.fail()}async deleteStack(){this.fail()}async health(){return this.fail()}async configureReplication(){return this.fail()}async verifyReplication(){return this.fail()}async applyTraffic(){return this.fail()}}function ar(e,t,r){return[e,t,r].map((n)=>encodeURIComponent(n)).join(":")}function ZI(e){return Object.fromEntries(["start","stop","restart","redeploy","scale","logs","exec","inspect","files"].map((t)=>[t,{supported:!1,reason:e}]))}function kn(e,t,r=["exec","files"]){let n=ZI(t);for(let i of e)n[i]={supported:!0,requiresConfirmation:!["logs","inspect"].includes(i),requiresRecentAuth:r.includes(i)};return n}var eC=/(?:secret|password|passwd|token|api[_-]?key|private[_-]?key|credential|authorization|cookie)/i;function Rr(e){let t=String(e??"").trim().toLowerCase();if(["active","running","ready","healthy","available","steady","active:running"].includes(t))return"running";if(["activating","pending","provisioning","starting","created","initializing"].includes(t))return"starting";if(["deactivating","stopping","draining","terminating"].includes(t))return"stopping";if(["inactive","stopped","complete","completed","exited","disabled"].includes(t))return"stopped";if(["degraded","unhealthy","warning"].includes(t))return"degraded";if(["failed","dead","error","crashed","oomkilled"].includes(t))return"failed";return"unknown"}function kr(e){if(Array.isArray(e))return e.map((r)=>kr(r));if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e))t[r]=eC.test(r)?"[REDACTED]":kr(n);return t}function Rn(e,t=new Date){if(!e)return;let r=new Date(e).getTime();return Number.isFinite(r)?Math.max(0,Math.floor((t.getTime()-r)/1000)):void 0}function tf(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function tC(e){let t=String(e?.message??e);if(/(?:unauthorized|accessdenied|forbidden|credentials)/i.test(t))return"unauthorized";if(/(?:timeout|unreachable|econnrefused|enotfound|network)/i.test(t))return"unreachable";return"error"}async function rf(e,t={},r={}){let n=t.now??new Date,i=Math.max(100,r.timeoutMs??1e4),o=Math.max(1,r.staleAfterSeconds??60),s=await Promise.all(e.map(async(u)=>{try{let a=await Promise.race([u.discover({...t,now:n}),new Promise((p,f)=>setTimeout(()=>f(Error(`Runtime source ${u.id} timed out after ${i}ms`)),i))]);return{workloads:a,source:{id:u.id,provider:u.provider,status:"fresh",discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:a.length}}}catch(a){return{workloads:[],source:{id:u.id,provider:u.provider,status:tC(a),discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:0,message:String(a?.message??a).slice(0,500)}}}})),c=s.map((u)=>u.source);return{generatedAt:n.toISOString(),workloads:s.flatMap((u)=>u.workloads).sort((u,a)=>u.name.localeCompare(a.name)||u.id.localeCompare(a.id)),sources:c,degraded:c.some((u)=>u.status!=="fresh")}}function rC(e,t){if(!t)return e;return e.startsWith(t)?e.slice(t.length):e}function nf(e,t,r){let n=rC(e,t);return`${r??""}${n}`}function of(e,t,r){if(r&&r.some((n)=>e.startsWith(n)))return!1;if(t&&t.length>0)return t.some((n)=>e.startsWith(n));return!0}async function nC(e,t,r){let n=0,i=[],o=Math.max(1,Math.min(t,e.length||1));for(let s=0;s<o;s++)i.push((async()=>{while(!0){let c=n++;if(c>=e.length)return;await r(e[c],c)}})());await Promise.all(i)}function sf(e){if(e.client)return e.client;return af({provider:e.provider,region:e.region,endpoint:e.endpoint,forcePathStyle:e.forcePathStyle,credentials:e.credentials})}async function e_(e){let t=e.concurrency??8,r=sf(e.from),n=sf(e.to),i=await r.listAllObjects({bucket:e.from.bucket,prefix:e.from.prefix}),o={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},s=[];for(let p of i){if(!of(p.Key,e.include,e.exclude)){o.excluded++,o.excludedKeys.push(p.Key);continue}s.push({source:p,destKey:nf(p.Key,e.from.prefix,e.to.prefix)})}if(e.dryRun){o.plan=s.map(({source:y,destKey:b})=>({key:y.Key,destKey:b,size:y.Size}));let p=i.length,f=0;for(let y of i){f++;let b=!of(y.Key,e.include,e.exclude);e.onProgress?.({key:y.Key,destKey:b?"":nf(y.Key,e.from.prefix,e.to.prefix),size:y.Size,action:b?"excluded":"planned",index:f,total:p})}return o}let c=s.length,u=0;await nC(s,t,async({source:p,destKey:f})=>{let y=++u;try{if(!e.force){let T=await n.headObject(e.to.bucket,f);if(T&&T.ContentLength===p.Size){o.skipped++,e.onProgress?.({key:p.Key,destKey:f,size:p.Size,action:"skipped",index:y,total:c});return}}let{body:b,contentType:C}=await r.getObjectBytes(e.from.bucket,p.Key);await n.putObject({bucket:e.to.bucket,key:f,body:b,contentType:C}),o.copied++,o.bytesCopied+=b.byteLength,e.onProgress?.({key:p.Key,destKey:f,size:p.Size,action:"copied",index:y,total:c})}catch(b){o.errors.push({key:p.Key,message:b?.message??String(b)}),e.onProgress?.({key:p.Key,destKey:f,size:p.Size,action:"error",index:y,total:c})}});let a=new Set(s.map((p)=>p.destKey));if(e.deleteExtraneous){let f=(await n.listAllObjects({bucket:e.to.bucket,prefix:e.to.prefix})).filter((y)=>!a.has(y.Key)).map((y)=>y.Key);for(let y of f)try{await n.deleteObject(e.to.bucket,y),o.deleted.push(y)}catch(b){o.errors.push({key:y,message:`delete failed: ${b?.message??String(b)}`})}}if(e.verify){let p=await n.listAllObjects({bucket:e.to.bucket,prefix:e.to.prefix}),f=new Map(p.map((T)=>[T.Key,T.Size])),y=[],b=[],C=0;for(let{source:T,destKey:R}of s){if(!f.has(R)){y.push(R);continue}let x=f.get(R);if(x!==T.Size){b.push({key:R,expected:T.Size,actual:x});continue}C++}o.verification={ok:y.length===0&&b.length===0,matched:C,missing:y,sizeMismatches:b}}return o}var iC={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function oC(e,t){switch(e){case"backblaze":return`s3.${t}.backblazeb2.com`;case"hetzner":return`${t}.your-objectstorage.com`;case"aws":default:return}}function Pt(...e){for(let t of e){let r=process.env[t];if(r)return r}return}function sC(e,t){if(t?.accessKeyId&&t.secretAccessKey)return t;let r,n;if(e==="backblaze")r=Pt("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=Pt("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if(e==="hetzner")r=Pt("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=Pt("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else r=Pt("S3_ACCESS_KEY_ID"),n=Pt("S3_SECRET_ACCESS_KEY");if(r&&n)return{accessKeyId:r,secretAccessKey:n,sessionToken:Pt("AWS_SESSION_TOKEN")};return}function aC(e={}){let t=e.provider||Pt("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",r=e.region||(t==="backblaze"?Pt("B2_REGION"):void 0)||(t==="hetzner"?Pt("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||Pt("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||iC[t],n=e.endpoint||Pt("S3_ENDPOINT")||oC(t,r),i=e.forcePathStyle??Pt("S3_FORCE_PATH_STYLE")==="true",o=sC(t,e.credentials),s=(c)=>{let u=n||`s3.${r}.amazonaws.com`;return i?`https://${u}/${c}`:`https://${c}.${u}`};return{provider:t,region:r,endpoint:n,forcePathStyle:i,credentials:o,profile:e.profile,publicBaseUrl:s}}function af(e={}){let t=aC(e),r={endpoint:t.endpoint,forcePathStyle:t.forcePathStyle,credentials:t.credentials};return new hr(t.region,t.profile,r)}class Xi{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new pe(void 0,{profile:t})}async describeServices(e){let t={cluster:e.cluster,services:e.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listServices(e,t={}){let r={cluster:e,...t};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTasks(e,t,r={}){let n={cluster:e,...r};if(t)n.serviceName=t;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(n)})}async describeTasks(e,t){let r={cluster:e,tasks:t};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async updateService(e){let t={cluster:e.cluster,service:e.service};if(e.forceNewDeployment!==void 0)t.forceNewDeployment=e.forceNewDeployment;if(e.desiredCount!==void 0)t.desiredCount=e.desiredCount;if(e.taskDefinition)t.taskDefinition=e.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async createService(e){let t={cluster:e.cluster,serviceName:e.serviceName,taskDefinition:e.taskDefinition,desiredCount:e.desiredCount};if(e.launchType)t.launchType=e.launchType;if(e.networkConfiguration)t.networkConfiguration=e.networkConfiguration;if(e.loadBalancers)t.loadBalancers=e.loadBalancers;if(e.healthCheckGracePeriodSeconds!==void 0)t.healthCheckGracePeriodSeconds=e.healthCheckGracePeriodSeconds;if(e.deploymentConfiguration)t.deploymentConfiguration=e.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteService(e){let t={cluster:e.cluster,service:e.service};if(e.force!==void 0)t.force=e.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listClusters(e={}){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async describeClusters(e){let t={clusters:e,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async stopTask(e){let t={cluster:e.cluster,task:e.task};if(e.reason)t.reason=e.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async runTask(e){let t={cluster:e.cluster,taskDefinition:e.taskDefinition};if(e.count!==void 0)t.count=e.count;if(e.launchType)t.launchType=e.launchType;if(e.networkConfiguration)t.networkConfiguration=e.networkConfiguration;if(e.overrides)t.overrides=e.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async registerTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async deregisterTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:e})})}async describeTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:e,include:["TAGS"]})})}async listTaskDefinitionFamilies(e){let t={};if(e?.familyPrefix)t.familyPrefix=e.familyPrefix;if(e?.status)t.status=e.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async waitForServiceStable(e,t,r=40,n=15000){for(let i=0;i<r;i++){let s=(await this.describeServices({cluster:e,services:[t]})).services?.[0];if(s){let c=s.deployments?.find((u)=>u.status==="PRIMARY");if(c&&c.runningCount===c.desiredCount&&s.deployments?.length===1)return!0}await new Promise((c)=>setTimeout(c,n))}return!1}async forceNewDeployment(e,t){return this.updateService({cluster:e,service:t,forceNewDeployment:!0})}async scaleService(e,t,r){return this.updateService({cluster:e,service:t,desiredCount:r})}}class Gd{client;region;constructor(e="us-east-1"){this.region=e,this.client=new pe}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&")}async createTopic(e){let t={Action:"CreateTopic",Version:"2010-03-31",Name:e.Name};if(e.DisplayName)t["Attributes.entry.1.key"]="DisplayName",t["Attributes.entry.1.value"]=e.DisplayName;if(e.Tags)e.Tags.forEach((n,i)=>{t[`Tags.member.${i+1}.Key`]=n.Key,t[`Tags.member.${i+1}.Value`]=n.Value});if(e.Attributes){let n=e.DisplayName?2:1;Object.entries(e.Attributes).forEach(([i,o])=>{t[`Attributes.entry.${n}.key`]=i,t[`Attributes.entry.${n}.value`]=o,n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{TopicArn:r?.CreateTopicResponse?.CreateTopicResult?.TopicArn||r?.TopicArn}}async deleteTopic(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:e})})}async listTopics(e){let t={Action:"ListTopics",Version:"2010-03-31"};if(e)t.NextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=r?.ListTopicsResponse?.ListTopicsResult||r?.ListTopicsResult,i=n?.Topics?.member;return{Topics:Array.isArray(i)?i:i?[i]:[],NextToken:n?.NextToken}}async getTopicAttributes(e){let r=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:e})}))?.GetTopicAttributesResponse?.GetTopicAttributesResult?.Attributes?.entry,n={TopicArn:e};if(Array.isArray(r))r.forEach((i)=>{n[i.key]=i.value});return n}async setTopicAttributes(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:e.TopicArn,AttributeName:e.AttributeName,AttributeValue:e.AttributeValue})})}async subscribe(e){let t={Action:"Subscribe",Version:"2010-03-31",TopicArn:e.TopicArn,Protocol:e.Protocol,Endpoint:e.Endpoint};if(e.ReturnSubscriptionArn)t.ReturnSubscriptionArn="true";if(e.Attributes){let n=1;Object.entries(e.Attributes).forEach(([i,o])=>{t[`Attributes.entry.${n}.key`]=i,t[`Attributes.entry.${n}.value`]=o,n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{SubscriptionArn:r?.SubscribeResponse?.SubscribeResult?.SubscriptionArn||r?.SubscriptionArn}}async unsubscribe(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:e})})}async listSubscriptionsByTopic(e,t){let r={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:e};if(t)r.NextToken=t;let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)}),i=n?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.Subscriptions?.member;return{Subscriptions:Array.isArray(i)?i:i?[i]:[],NextToken:n?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.NextToken}}async publish(e){let t={Action:"Publish",Version:"2010-03-31",Message:e.Message};if(e.TopicArn)t.TopicArn=e.TopicArn;if(e.TargetArn)t.TargetArn=e.TargetArn;if(e.PhoneNumber)t.PhoneNumber=e.PhoneNumber;if(e.Subject)t.Subject=e.Subject;if(e.MessageStructure)t.MessageStructure=e.MessageStructure;if(e.MessageAttributes){let n=1;Object.entries(e.MessageAttributes).forEach(([i,o])=>{if(t[`MessageAttributes.entry.${n}.Name`]=i,t[`MessageAttributes.entry.${n}.Value.DataType`]=o.DataType,o.StringValue)t[`MessageAttributes.entry.${n}.Value.StringValue`]=o.StringValue;if(o.BinaryValue)t[`MessageAttributes.entry.${n}.Value.BinaryValue`]=o.BinaryValue;n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{MessageId:r?.PublishResponse?.PublishResult?.MessageId||r?.MessageId}}async publishSMS(e,t,r){let n={};if(r)n["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:r};return this.publish({PhoneNumber:e,Message:t,MessageAttributes:Object.keys(n).length>0?n:void 0})}async subscribeEmail(e,t){return this.subscribe({TopicArn:e,Protocol:"email",Endpoint:t})}async subscribeLambda(e,t){return this.subscribe({TopicArn:e,Protocol:"lambda",Endpoint:t})}async subscribeSqs(e,t,r){let n={};if(r)n.RawMessageDelivery="true";return this.subscribe({TopicArn:e,Protocol:"sqs",Endpoint:t,Attributes:Object.keys(n).length>0?n:void 0})}async subscribeHttp(e,t,r){let n=t.startsWith("https")?"https":"http",i={};if(r)i.RawMessageDelivery="true";return this.subscribe({TopicArn:e,Protocol:n,Endpoint:t,Attributes:Object.keys(i).length>0?i:void 0})}async subscribeSms(e,t){return this.subscribe({TopicArn:e,Protocol:"sms",Endpoint:t})}async topicExists(e){try{return await this.getTopicAttributes(e),!0}catch(t){if(t.code==="NotFound"||t.statusCode===404)return!1;throw t}}async getSMSAttributes(){let t=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}))?.GetSMSAttributesResponse?.GetSMSAttributesResult?.attributes?.entry,r={};if(Array.isArray(t))t.forEach((n)=>{r[n.key]=n.value});else if(t)r[t.key]=t.value;return r}async setSMSAttributes(e){let t={Action:"SetSMSAttributes",Version:"2010-03-31"},r=1;Object.entries(e).forEach(([n,i])=>{if(i!==void 0)t[`attributes.entry.${r}.key`]=n,t[`attributes.entry.${r}.value`]=i,r++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async checkIfPhoneNumberIsOptedOut(e){return(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:e})}))?.CheckIfPhoneNumberIsOptedOutResponse?.CheckIfPhoneNumberIsOptedOutResult?.isOptedOut==="true"}async listPhoneNumbersOptedOut(e){let t={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if(e)t.nextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=r?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.phoneNumbers?.member;return{phoneNumbers:Array.isArray(n)?n:n?[n]:[],nextToken:r?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.nextToken}}async optInPhoneNumber(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:e})})}async listSMSSandboxPhoneNumbers(e){let t={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if(e)t.NextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=r?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.PhoneNumbers?.member;return{PhoneNumbers:Array.isArray(n)?n:n?[n]:[],NextToken:r?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.NextToken}}async createSMSSandboxPhoneNumber(e,t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e,LanguageCode:t||"en-US"})})}async verifySMSSandboxPhoneNumber(e,t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e,OneTimePassword:t})})}async deleteSMSSandboxPhoneNumber(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e})})}async getSMSSandboxAccountStatus(){return{IsInSandbox:(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})}))?.GetSMSSandboxAccountStatusResponse?.GetSMSSandboxAccountStatusResult?.IsInSandbox==="true"}}}class Pn{client;region;endpoint;constructor(e="us-east-1",t){this.region=e,this.endpoint=t?.endpoint,this.client=new pe}async request(e,t){if(this.endpoint){let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${e}`},body:JSON.stringify(t)});if(!r.ok){let n=await r.text();throw Error(`DynamoDB request failed: ${r.status} ${n}`)}return r.json()}return this.client.request({service:"dynamodb",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${e}`},body:JSON.stringify(t)})}async createTable(e){return this.request("CreateTable",e)}async deleteTable(e){return this.request("DeleteTable",e)}async describeTable(e){return this.request("DescribeTable",e)}async listTables(e){return this.request("ListTables",e||{})}async putItem(e){return this.request("PutItem",e)}async getItem(e){return this.request("GetItem",e)}async updateItem(e){return this.request("UpdateItem",e)}async deleteItem(e){return this.request("DeleteItem",e)}async query(e){return this.request("Query",e)}async scan(e){return this.request("Scan",e)}async batchWriteItem(e){return this.request("BatchWriteItem",e)}async batchGetItem(e){return this.request("BatchGetItem",e)}async updateTimeToLive(e){return this.request("UpdateTimeToLive",e)}static marshal(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Pn.marshalValue(n);return t}static marshalValue(e){if(e===null||e===void 0)return{NULL:!0};if(typeof e==="string")return{S:e};if(typeof e==="number")return{N:String(e)};if(typeof e==="boolean")return{BOOL:e};if(Array.isArray(e))return{L:e.map((t)=>Pn.marshalValue(t))};if(typeof e==="object")return{M:Pn.marshal(e)};return{S:String(e)}}static unmarshal(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Pn.unmarshalValue(n);return t}static unmarshalValue(e){if(e.S!==void 0)return e.S;if(e.N!==void 0)return Number(e.N);if(e.BOOL!==void 0)return e.BOOL;if(e.NULL!==void 0)return null;if(e.L!==void 0)return e.L.map((t)=>Pn.unmarshalValue(t));if(e.M!==void 0)return Pn.unmarshal(e.M);if(e.SS!==void 0)return e.SS;if(e.NS!==void 0)return e.NS.map(Number);return null}}class Kd{client;region;constructor(e="us-east-1"){this.region=e,this.client=new pe}async request(e,t){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${e}`},body:JSON.stringify(t)})}async putRule(e){return this.request("PutRule",e)}async deleteRule(e){return this.request("DeleteRule",e)}async describeRule(e){return this.request("DescribeRule",e)}async listRules(e){return this.request("ListRules",e||{})}async listEventBuses(e){return this.request("ListEventBuses",e||{})}async enableRule(e){return this.request("EnableRule",e)}async disableRule(e){return this.request("DisableRule",e)}async putTargets(e){return this.request("PutTargets",e)}async removeTargets(e){return this.request("RemoveTargets",e)}async listTargetsByRule(e){return this.request("ListTargetsByRule",e)}async putEvents(e){return this.request("PutEvents",e)}async createSchedule(e){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${e.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}class cf{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new pe}async createRule(e){let t={Action:"PutRule",Name:e.name,ScheduleExpression:e.scheduleExpression,Version:"2015-10-07"};if(e.description)t.Description=e.description;if(e.state)t.State=e.state;else t.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e.name,ScheduleExpression:e.scheduleExpression,State:e.state||"ENABLED",Description:e.description})})).RuleArn}}async putTargets(e,t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e,Targets:t})})}async listRules(e){let t={};if(e)t.NamePrefix=e;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).Rules||[]}}async describeRule(e){let t=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})});return{Name:t.Name,Arn:t.Arn,ScheduleExpression:t.ScheduleExpression,State:t.State,Description:t.Description}}async listTargetsByRule(e){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e})})).Targets||[]}}async deleteRule(e,t){if(t)try{let r=await this.listTargetsByRule(e);if(r.Targets&&r.Targets.length>0)await this.removeTargets(e,r.Targets.map((n)=>n.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e,Force:t||!1})})}async removeTargets(e,t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e,Ids:t})})}async enableRule(e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})})}async disableRule(e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})})}async createLambdaSchedule(e){let t=await this.createRule({name:e.name,scheduleExpression:e.scheduleExpression,description:e.description,state:"ENABLED"});return await this.putTargets(e.name,[{Id:"1",Arn:e.functionArn,Input:e.input}]),t}async createEcsSchedule(e){let t=await this.createRule({name:e.name,scheduleExpression:e.scheduleExpression,description:e.description,state:"ENABLED"});return await this.putTargets(e.name,[{Id:"1",Arn:e.clusterArn,RoleArn:e.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),t}async listSchedules(e){let t={};if(e?.NamePrefix)t.NamePrefix=e.NamePrefix;if(e?.State)t.State=e.State;let r=e?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...t,ScheduleGroup:r}}))?.Schedules||[]}}async getSchedule(e){try{let t={};if(e.GroupName)t.groupName=e.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent(e.Name)}`,queryParams:Object.keys(t).length>0?t:void 0})}catch(t){if(t.statusCode===404||t.code==="ResourceNotFoundException")return null;throw t}}async createSchedule(e){let t={ScheduleExpression:e.ScheduleExpression,FlexibleTimeWindow:e.FlexibleTimeWindow,Target:e.Target};if(e.GroupName)t.GroupName=e.GroupName;if(e.ScheduleExpressionTimezone)t.ScheduleExpressionTimezone=e.ScheduleExpressionTimezone;if(e.Description)t.Description=e.Description;if(e.State)t.State=e.State;if(e.StartDate)t.StartDate=e.StartDate.toISOString();if(e.EndDate)t.EndDate=e.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent(e.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))?.ScheduleArn||""}}async updateSchedule(e){let t={};if(e.GroupName)t.GroupName=e.GroupName;if(e.ScheduleExpression)t.ScheduleExpression=e.ScheduleExpression;if(e.ScheduleExpressionTimezone)t.ScheduleExpressionTimezone=e.ScheduleExpressionTimezone;if(e.Description!==void 0)t.Description=e.Description;if(e.State)t.State=e.State;if(e.FlexibleTimeWindow)t.FlexibleTimeWindow=e.FlexibleTimeWindow;if(e.Target)t.Target=e.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent(e.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))?.ScheduleArn||""}}async deleteSchedule(e){let t={};if(e.GroupName)t.groupName=e.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent(e.Name)}`,queryParams:Object.keys(t).length>0?t:void 0})}async listScheduleGroups(e){let t={};if(e?.NamePrefix)t.NamePrefix=e.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(t).length>0?t:void 0}))?.ScheduleGroups||[]}}}function mi(e){return e?.split("/").at(-1)??e?.split(":").at(-1)??"unknown"}function df(e,t,r,n="ecs:aws",i=[]){let o=r.now??new Date;return e.map((s)=>{let c=s.serviceName??mi(s.serviceArn),u=t.filter((x)=>!s.clusterArn||x.clusterArn===s.clusterArn),a=u.some((x)=>!!x.group)?u.filter((x)=>x.group===`service:${c}`):u,p=s.status==="ACTIVE"?(s.runningCount??0)<(s.desiredCount??0)?"degraded":"running":Rr(s.status),f=i.find((x)=>x.taskDefinitionArn===s.taskDefinition),y=Array.isArray(f?.containerDefinitions)?f.containerDefinitions:[],b=[...new Set(y.map((x)=>x.logConfiguration?.options?.["awslogs-group"]).filter((x)=>typeof x==="string"))],C=y.flatMap((x)=>(x.mountPoints??[]).map((L)=>({source:L.sourceVolume,target:L.containerPath,type:"volume",readOnly:!!L.readOnly}))),T=y.flatMap((x)=>(x.portMappings??[]).map((L,P)=>({id:`${x.name??"container"}:${P}`,name:x.name,mode:f?.networkMode,ports:[{container:L.containerPort,host:L.hostPort,protocol:L.protocol}]}))),R=r.project&&r.environment&&c.startsWith(`${r.project}-${r.environment}-`)?c.slice(`${r.project}-${r.environment}-`.length):c;return{id:ar("ecs",n,s.serviceArn??c),provider:"ecs",kind:"service",name:c,status:p,rawStatus:s.status,health:p==="running"?"healthy":p==="failed"||p==="degraded"?"unhealthy":"unknown",desiredReplicas:s.desiredCount,runningReplicas:s.runningCount,image:y[0]?.image,runtime:s.launchType??"ECS",version:mi(s.taskDefinition),ageSeconds:Rn(s.deployments?.[0]?.createdAt,o),restartCount:0,tags:{},links:{project:r.project,environment:r.environment,service:R,release:mi(s.taskDefinition),providerId:s.serviceArn},replicas:a.map((x)=>{let L=Rr(x.lastStatus);return{id:ar("ecs",n,x.taskArn??mi(x.taskArn)),name:mi(x.taskArn),status:L,rawStatus:x.lastStatus,createdAt:x.createdAt,startedAt:x.startedAt,stoppedAt:x.stoppedAt,host:x.containerInstanceArn,containers:(x.containers??[]).map((P)=>({id:P.containerArn??P.name??"container",name:P.name??"container",image:y.find((G)=>G.name===P.name)?.image,imageDigest:P.imageDigest,status:Rr(P.lastStatus),rawStatus:P.lastStatus,exitCode:P.exitCode,reason:P.reason,runtime:"ecs"}))}}),networks:T,mounts:C,capabilities:kn(["start","stop","restart","redeploy","scale","inspect",...b.length?["logs"]:[]],"This ECS runtime does not expose exec or file transfer; logs require an awslogs task-definition driver"),config:kr({clusterArn:s.clusterArn,taskDefinition:s.taskDefinition,launchType:s.launchType,pendingCount:s.pendingCount,deployments:s.deployments,logGroups:b,executionRoleArn:f?.executionRoleArn,taskRoleArn:f?.taskRoleArn,cpu:f?.cpu,memory:f?.memory}),discoveredAt:o.toISOString(),sourceId:n}})}function uf(e,t,r="lambda:aws"){let n=t.now??new Date;return e.map((i)=>{let o=i.FunctionName??mi(i.FunctionArn),s=i.State==="Active"?"running":Rr(i.State);return{id:ar("lambda",r,i.FunctionArn??o),provider:"lambda",kind:"function",name:o,status:s,rawStatus:i.State,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:void 0,runningReplicas:void 0,image:void 0,runtime:i.Runtime,version:i.Version,architecture:i.Architectures?.join(", "),ageSeconds:Rn(i.LastModified,n),restartCount:0,tags:{},links:{project:t.project,environment:t.environment,service:o,providerId:i.FunctionArn},resources:{memoryLimitBytes:i.MemorySize==null?void 0:i.MemorySize*1024*1024},replicas:[],networks:[],mounts:[],capabilities:kn(["logs","inspect"],"Lambda has no persistent process to start, stop, restart, exec, or browse files; deploy a release to replace code"),config:kr({handler:i.Handler,timeout:i.Timeout,codeSize:i.CodeSize,stateReason:i.StateReason,environmentKeys:Object.keys(i.Environment?.Variables??{})}),discoveredAt:n.toISOString(),sourceId:r}})}function cC(e){let t=e.trim();if(!t)return[];let r=JSON.parse(t);if(!Array.isArray(r))throw Error("Docker inspect output must be an array");return r.filter((n)=>n&&typeof n.Id==="string")}function dC(e){let t=Object.entries(e.NetworkSettings?.Ports??{}).flatMap(([r,n])=>{let[i,o]=r.split("/");return(n??[]).map((s)=>({container:Number(i)||void 0,host:Number(s.HostPort)||void 0,protocol:o,address:s.HostIp}))});return Object.entries(e.NetworkSettings?.Networks??{}).map(([r,n])=>({id:n.NetworkID||r,name:r,mode:e.HostConfig?.NetworkMode,addresses:[n.IPAddress,n.GlobalIPv6Address].filter(Boolean),ports:t}))}function uC(e){return(e.Mounts??[]).filter((t)=>!!t.Destination).map((t)=>({source:t.Source,target:t.Destination,type:t.Type,readOnly:t.RW===!1}))}function lC(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=i.State?.OOMKilled?"oomkilled":i.State?.Restarting?"starting":i.State?.Status,s=Rr(o),c=(i.Name??i.Id.slice(0,12)).replace(/^\//,""),u=i.Config?.Labels??{},a=uC(i),p=dC(i),f={id:i.Id,name:c,image:i.Config?.Image,imageDigest:i.Image,runtime:"docker",status:s,rawStatus:o,exitCode:i.State?.ExitCode,reason:i.State?.Error,resources:{memoryLimitBytes:i.HostConfig?.Memory||void 0},networks:p,mounts:a};return{id:ar("docker",r,i.Id),provider:"docker",kind:"container",name:c,status:s,rawStatus:o,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:s==="running"?1:0,image:i.Config?.Image,runtime:"docker",ageSeconds:Rn(i.State?.StartedAt,n),restartCount:i.RestartCount??0,tags:u,links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^docker:/,""),service:u["com.docker.compose.service"]??u["ts-cloud.service"]??c,release:u["ts-cloud.release"],providerId:i.Id},resources:f.resources,replicas:[{id:ar("docker",r,`${i.Id}:0`),name:c,status:s,rawStatus:o,startedAt:i.State?.StartedAt,stoppedAt:i.State?.FinishedAt,restartCount:i.RestartCount,containers:[f],resources:f.resources}],networks:p,mounts:a,capabilities:kn(["start","stop","restart","logs","exec","inspect","files"],"Use the owning Compose service for redeploy and scale"),config:kr({image:i.Config?.Image,labels:u,environmentKeys:(i.Config?.Env??[]).map((y)=>y.split("=",1)[0]),networkMode:i.HostConfig?.NetworkMode}),discoveredAt:n.toISOString(),sourceId:r}})}class Qd{inspect;id;provider="docker";constructor(e,t="docker:local"){this.inspect=e;this.id=t}async discover(e){return lC(cC(await this.inspect(e)),e,this.id)}}function pC(e){let t=[];for(let r of e.split(`
|
|
120
|
-
`)){if(!r.startsWith("TSCLOUD_SYSTEMD\t"))continue;let[,n,i,o,s,c,u,a,p,f,y,b,C,T]=r.split("\t");if(!n||!/^[A-Za-z0-9_.@:-]+\.service$/.test(n))continue;t.push({unit:n,load:i,active:o,sub:s,description:c,enabled:u,pid:Number(a)||void 0,memoryBytes:tf(p),restartCount:Number(f)||0,activeSince:y||void 0,fragmentPath:b||void 0,workingDirectory:C?.startsWith("/")?C:void 0,user:T||void 0})}return t}function gC(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=Rr(i.active==="active"?i.sub||i.active:i.active),s=i.unit.replace(/\.service$/,""),c=/^(.*?) (?:release [^ ]+|queue worker|daemon |scheduler)(?: |$)/.exec(i.description??"")?.[1]??(t.project&&s.startsWith(`${t.project}-`)?s.slice(t.project.length+1).split("@",1)[0]:void 0),u=s.includes("@")?s.slice(s.indexOf("@")+1):void 0,a=i.workingDirectory?[{target:i.workingDirectory,type:"working-directory"}]:[],p=["start","stop","restart","logs","exec","inspect",...a.length?["files"]:[]];return{id:ar("systemd",r,i.unit),provider:"systemd",kind:"service",name:s,displayName:i.description||s,status:o,rawStatus:[i.load,i.active,i.sub].filter(Boolean).join("/"),health:o==="running"?"healthy":o==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:o==="running"?1:0,ageSeconds:Rn(i.activeSince,n),restartCount:i.restartCount,tags:{enabled:i.enabled??"unknown"},links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^systemd:/,""),service:c,release:u,providerId:i.unit},resources:{memoryBytes:i.memoryBytes},replicas:[{id:ar("systemd",r,`${i.unit}:main`),name:"main",status:o,pid:i.pid,startedAt:i.activeSince,restartCount:i.restartCount,resources:{memoryBytes:i.memoryBytes}}],networks:[],mounts:a,capabilities:kn(p,a.length?"This systemd runtime does not support redeploy or replica scaling through the scoped explorer":"File transfer requires a provider-reported service working directory; redeploy and scaling are unavailable"),config:kr({fragmentPath:i.fragmentPath,workingDirectory:i.workingDirectory,user:i.user,environment:i.environment,enabled:i.enabled}),discoveredAt:n.toISOString(),sourceId:r}})}class Yd{read;id;provider="systemd";constructor(e,t="systemd:local"){this.read=e;this.id=t}async discover(e){return gC(pC(await this.read(e)),e,this.id)}}function mC(e,t){if(!e.success)throw Error(e.error||e.perInstance?.[0]?.error||`${t} discovery failed`);return e.perInstance?.[0]?.output??""}function fC(){return["set -uo pipefail",'command -v systemctl >/dev/null 2>&1 || { echo "systemctl is unavailable" >&2; exit 127; }',"systemctl list-units --type=service --all --plain --no-legend 2>/dev/null | awk '{print $1}' | while IFS= read -r unit; do",' [ -n "$unit" ] || continue',' clean() { printf "%s" "$1" | tr "\\t\\r\\n" " "; }',' load=$(systemctl show "$unit" -p LoadState --value 2>/dev/null || true)',' active=$(systemctl show "$unit" -p ActiveState --value 2>/dev/null || true)',' sub=$(systemctl show "$unit" -p SubState --value 2>/dev/null || true)',' description=$(systemctl show "$unit" -p Description --value 2>/dev/null || true)',' enabled=$(systemctl is-enabled "$unit" 2>/dev/null || true)',' pid=$(systemctl show "$unit" -p MainPID --value 2>/dev/null || true)',' memory=$(systemctl show "$unit" -p MemoryCurrent --value 2>/dev/null || true)',' restarts=$(systemctl show "$unit" -p NRestarts --value 2>/dev/null || true)',' since=$(systemctl show "$unit" -p ActiveEnterTimestamp --value 2>/dev/null || true)',' fragment=$(systemctl show "$unit" -p FragmentPath --value 2>/dev/null || true)',' working=$(systemctl show "$unit" -p WorkingDirectory --value 2>/dev/null || true)',' user=$(systemctl show "$unit" -p User --value 2>/dev/null || true)',' printf "TSCLOUD_SYSTEMD\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n" "$(clean "$unit")" "$(clean "$load")" "$(clean "$active")" "$(clean "$sub")" "$(clean "$description")" "$(clean "$enabled")" "$(clean "$pid")" "$(clean "$memory")" "$(clean "$restarts")" "$(clean "$since")" "$(clean "$fragment")" "$(clean "$working")" "$(clean "$user")"',"done"]}function hC(){return["set -uo pipefail",'if ! command -v docker >/dev/null 2>&1; then echo "[]"; exit 0; fi',"ids=$(docker ps -aq)",'if [ -z "$ids" ]; then echo "[]"; else docker inspect $ids; fi']}function lf(e,t,r,n,i){let o=`${e}:${r.id}`,s=async()=>mC(await t.runRemoteDeploy({targets:[r],commands:e==="systemd"?fC():hC(),timeoutSeconds:30,comment:`ts-cloud runtime discovery:${e}`,tags:{Project:n.project.slug,Environment:i,Role:"app"}}),o);return e==="systemd"?new Yd(s,o):new Qd(s,o)}async function zs(e,t=100){let r=[],n;for(let i=0;i<t;i++){let o=await e(n);if(r.push(...o.items),!o.nextToken)return r;n=o.nextToken}throw Error(`Provider pagination exceeded ${t} pages`)}class pf{client;prefix;id="ecs:aws";provider="ecs";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=await zs(async(o)=>{let s=await this.client.listClusters({nextToken:o,maxResults:100});return{items:s.clusterArns??[],nextToken:s.nextToken}}),r=[],n=[],i=[];for(let o of t){let s=(await zs(async(c)=>{let u=await this.client.listServices(o,{nextToken:c,maxResults:100});return{items:u.serviceArns??[],nextToken:u.nextToken}})).filter((c)=>c.split("/").at(-1)?.startsWith(this.prefix));for(let c=0;c<s.length;c+=10){let u=await this.client.describeServices({cluster:o,services:s.slice(c,c+10)});r.push(...u.services??[])}for(let c of r.filter((u)=>u.clusterArn===o||!u.clusterArn)){let u=await zs(async(a)=>{let p=await this.client.listTasks(o,c.serviceName,{nextToken:a,maxResults:100});return{items:p.taskArns??[],nextToken:p.nextToken}});for(let a=0;a<u.length;a+=100){let p=await this.client.describeTasks(o,u.slice(a,a+100));n.push(...p.tasks??[])}}}if(this.client.describeTaskDefinition)for(let o of[...new Set(r.map((s)=>s.taskDefinition).filter((s)=>!!s))]){let s=await this.client.describeTaskDefinition(o);if(s.taskDefinition)i.push(s.taskDefinition)}return df(r,n,e,this.id,i)}}class gf{client;prefix;id="lambda:aws";provider="lambda";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=(await zs(async(r)=>{let n=await this.client.listFunctions({Marker:r,MaxItems:50});return{items:n.Functions??[],nextToken:n.NextMarker}})).filter((r)=>r.FunctionName?.startsWith(this.prefix));return uf(t,e,this.id)}}async function yC(e,t,r={}){let n=[],i=Pr(e),o=Xd(e),s=e.aws?.profile,c=e.aws?.region??e.project.region??"us-east-1",u=`${e.project.slug}-${t}`;if(i!=="serverless"){let a=r.driver??xr({config:e}),p=await a.findComputeTargets({slug:e.project.slug,environment:t,role:"app"});for(let f of p)n.push(lf("systemd",a,f,e,t)),n.push(lf("docker",a,f,e,t))}if(o==="aws")n.push(new pf(r.ecs??new Xi(c,s),u)),n.push(new gf(r.lambda??new Vs(c,s),u));return n}async function Ht(e,t,r={}){let n={project:e.project.slug,environment:t};try{return await rf(await yC(e,t,r),n)}catch(i){return{generatedAt:new Date().toISOString(),workloads:[],sources:[{id:"runtime:bootstrap",provider:Xd(e)==="aws"?"ecs":"systemd",status:"error",discoveredAt:new Date().toISOString(),staleAfterSeconds:60,itemCount:0,message:String(i?.message??i).slice(0,500)}],degraded:!0}}}var mf=65536,Zi=49152,Js=/^[A-Za-z0-9_.@:-]+\.service$/,Ws=/^[a-fA-F0-9]{12,128}$/,bC=["/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run"];function fi(e){let t=Buffer.from(e);return t.byteLength<=mf?e:`${t.subarray(0,mf-24).toString("utf8")}
|
|
121
|
-
[output truncated]`}function qs(e){return{success:!1,instanceCount:0,perInstance:[],error:e instanceof Error?e.message:String(e)}}function Lt(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function SC(e,t){return Number.isFinite(e)?Math.min(1e4,Math.max(0,Math.floor(e))):t}function vC(e){let t=e.config,r=typeof t.clusterArn==="string"?t.clusterArn:void 0,n=e.links.providerId||e.name;return r&&n?{cluster:r,service:n}:void 0}function wC(e,t){return e.find((r)=>r.id===t.links.server)??(e.length===1?e[0]:void 0)}function IC(e,t){if(e.provider==="systemd"){let r=e.links.providerId;if(!r||!Js.test(r)||!["start","stop","restart"].includes(t))return;return[`systemctl ${t} ${r}`,`systemctl is-active ${r} 2>/dev/null || true`]}if(e.provider==="docker"){let r=e.links.providerId;if(!r||!Ws.test(r)||!["start","stop","restart"].includes(t))return;return[`docker ${t} ${r}`,`docker inspect --format '{{.State.Status}}' ${r}`]}return}function CC(e,t){if(!t.startsWith("/")||t.includes("\x00"))return{ok:!1,error:"An absolute path is required."};let r=[];for(let c of t.split("/")){if(!c||c===".")continue;if(c===".."){if(!r.length)return{ok:!1,error:"Path traversal is not allowed."};r.pop()}else r.push(c)}let n=`/${r.join("/")}`;if(bC.some((c)=>n===c||n.startsWith(`${c}/`)))return{ok:!1,error:"Sensitive host paths are not available through runtime file access."};let i=e.links.project?.replace(/[^A-Za-z0-9_-]/g,""),o=e.links.service?.replace(/[^A-Za-z0-9_-]/g,"");if(![...i&&o?[`/var/www/${i}/${o}`,`/srv/${i}/${o}`]:[],...e.mounts.map((c)=>c.target).filter((c)=>c.startsWith("/"))].some((c)=>n===c||n.startsWith(`${c.replace(/\/$/,"")}/`)))return{ok:!1,error:"Path is outside this service’s owned roots."};return{ok:!0,path:n}}function EC(e,t){let r=e.links.project?.replace(/[^A-Za-z0-9_-]/g,""),n=e.links.service?.replace(/[^A-Za-z0-9_-]/g,"");return[...r&&n?[`/var/www/${r}/${n}`,`/srv/${r}/${n}`]:[],...e.mounts.map((i)=>i.target).filter((i)=>i.startsWith("/"))].sort((i,o)=>o.length-i.length).find((i)=>t===i||t.startsWith(`${i.replace(/\/$/,"")}/`))}var ff={process:["ps","-eo","pid,ppid,user,%cpu,%mem,etime,command","--sort=-%cpu"],sockets:["ss","-lntup"],filesystem:["df","-h"]};class cr{config;environment;dependencies;region;profile;constructor(e,t,r={}){this.config=e;this.environment=t;this.dependencies=r;this.region=e.aws?.region??e.project.region??"us-east-1",this.profile=e.aws?.profile}async inventory(){return this.dependencies.inventory?.()??Ht(this.config,this.environment,{driver:this.dependencies.driver})}async workload(e){return(await this.inventory()).workloads.find((t)=>t.id===e)}async remote(e,t,r,n){let i=this.dependencies.driver??xr({config:this.config}),o=await i.findComputeTargets({slug:this.config.project.slug,environment:this.environment,role:"app"}),s=wC(o,e);if(!s)throw Error("The workload server is no longer reachable in this scope.");return i.runRemoteDeploy({targets:[s],commands:t,timeoutSeconds:r,comment:n,tags:{Project:this.config.project.slug,Environment:this.environment,Role:"app"}})}async run(e){let t=await this.workload(e.workloadId),r={workloadId:e.workloadId,action:e.action};if(!t)return{...r,ok:!1,error:"Workload was not found in the current project and environment."};let n=t.capabilities[e.action];if(!n.supported)return{...r,ok:!1,error:n.reason??`${e.action} is unsupported for ${t.provider}.`};if(n.requiresConfirmation&&e.confirm!==t.name)return{...r,ok:!1,error:`Type "${t.name}" to ${e.action} this workload.`};if(n.requiresRecentAuth&&!e.recentAuth)return{...r,ok:!1,error:"Sign in again before using elevated runtime access."};if(e.action==="inspect")return{...r,ok:!0,workload:t};if(t.provider==="systemd"||t.provider==="docker"){let i=IC(t,e.action);if(!i)return{...r,ok:!1,error:`${e.action} is not implemented for ${t.provider}.`};let o=await this.remote(t,["set -uo pipefail",...i],60,`ts-cloud runtime:${e.action}`).catch(qs);return{...r,ok:o.success,command:i[0],stdout:fi(o.perInstance?.[0]?.output??""),stderr:fi(o.perInstance?.[0]?.error??o.error??""),error:o.success?void 0:o.error??"Runtime operation failed."}}if(t.provider==="ecs"){let i=vC(t);if(!i)return{...r,ok:!1,error:"ECS cluster or service identity is unavailable."};let o=this.dependencies.ecs??new Xi(this.region,this.profile);if(e.action==="scale"){let s=SC(e.replicas,t.desiredReplicas??1);return await o.scaleService(i.cluster,i.service,s),{...r,ok:!0,command:`ecs scale ${t.name} ${s}`}}if(e.action==="start"||e.action==="stop"){let s=e.action==="stop"?0:Math.max(1,t.desiredReplicas??1);return await o.scaleService(i.cluster,i.service,s),{...r,ok:!0,command:`ecs scale ${t.name} ${s}`}}if(e.action==="restart"||e.action==="redeploy")return await o.forceNewDeployment(i.cluster,i.service),{...r,ok:!0,command:`ecs redeploy ${t.name}`}}return{...r,ok:!1,error:`${e.action} is not implemented for ${t.provider}.`}}async exec(e){let t={workloadId:e.workloadId,preset:e.preset},r=await this.workload(e.workloadId);if(!r)return{...t,ok:!1,error:"Workload was not found in the current project and environment."};if(process.env.TS_CLOUD_RUNTIME_EXEC==="0")return{...t,ok:!1,error:"Runtime exec is disabled by TS_CLOUD_RUNTIME_EXEC."};if(!r.capabilities.exec.supported)return{...t,ok:!1,error:r.capabilities.exec.reason??"Exec is unsupported for this workload."};if(e.confirm!==r.name)return{...t,ok:!1,error:`Type "${r.name}" to open exec access.`};if(!e.recentAuth)return{...t,ok:!1,error:"Sign in again before using elevated runtime access."};let n=e.preset&&ff[e.preset];if(!n&&!e.command?.trim())return{...t,ok:!1,error:"Choose a diagnostic preset or provide a command."};if(e.command&&r.provider!=="docker")return{...t,ok:!1,error:"Free-form exec is restricted to isolated containers; use a diagnostic preset for system services."};let i=r.links.providerId??"",o;if(r.provider==="docker"&&Ws.test(i)){let c=e.command?.trim()||n.map(Lt).join(" ");o=`docker exec ${i} sh -lc ${Lt(c)}`}else if(r.provider==="systemd"&&Js.test(i)&&e.preset)o=e.preset==="process"?`systemctl status ${i} --no-pager --full`:ff[e.preset].map(Lt).join(" ");if(!o)return{...t,ok:!1,error:"Exec target identity is invalid or unsupported."};let s=await this.remote(r,["set -uo pipefail",o],60,"ts-cloud runtime:exec").catch(qs);return{...t,ok:s.success,command:o,stdout:fi(s.perInstance?.[0]?.output??""),stderr:fi(s.perInstance?.[0]?.error??s.error??""),error:s.success?void 0:s.error??"Exec command failed."}}async readFile(e){let t={workloadId:e.workloadId,path:e.path},r=await this.fileTarget(e);if("error"in r)return{...t,ok:!1,error:r.error};let{workload:n,path:i,root:o,providerId:s}=r,u=`sh -c ${Lt('resolved=$(realpath -m "$1"); root=$(realpath -m "$3"); case "$resolved" in "$root"|"$root"/*) ;; *) exit 73;; esac; test -f "$resolved"; size=$(wc -c < "$resolved"); printf "__TSCLOUD_SIZE__=%s\\n" "$size"; head -c "$2" "$resolved" | base64')} sh ${Lt(i)} ${Zi} ${Lt(o)}`,a=n.provider==="docker"?`docker exec ${s} ${u}`:u,p=await this.remote(n,[a],30,"ts-cloud runtime:file-read").catch(qs);if(!p.success)return{...t,ok:!1,error:p.error??p.perInstance?.[0]?.error??"File read failed."};let f=p.perInstance?.[0]?.output??"",y=/__TSCLOUD_SIZE__=(\d+)\r?\n/.exec(f);if(!y)return{...t,ok:!1,error:"The remote file response was invalid."};let b=Number(y[1]),C=f.slice((y.index??0)+y[0].length).replace(/\s+/g,"");if(Buffer.from(C,"base64").byteLength>Zi)return{...t,ok:!1,error:"The remote file exceeded the transfer limit."};return{...t,ok:!0,contentBase64:C,size:b,truncated:b>Zi}}async writeFile(e){let t={workloadId:e.workloadId,path:e.path},r=await this.fileTarget(e);if("error"in r)return{...t,ok:!1,error:r.error};if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e.contentBase64))return{...t,ok:!1,error:"File content must be valid base64."};let n=Buffer.from(e.contentBase64,"base64");if(n.toString("base64")!==e.contentBase64)return{...t,ok:!1,error:"File content must be canonical base64."};if(n.byteLength>Zi)return{...t,ok:!1,error:`File uploads are limited to ${Zi} bytes.`};let{workload:i,path:o,root:s,providerId:c}=r,a=`sh -c ${Lt('resolved=$(realpath -m "$1"); root=$(realpath -m "$2"); case "$resolved" in "$root"|"$root"/*) ;; *) exit 73;; esac; mkdir -p "$(dirname "$resolved")"; tmp="$resolved.ts-cloud-$$"; base64 -d > "$tmp"; chmod 600 "$tmp"; mv "$tmp" "$resolved"')} sh ${Lt(o)} ${Lt(s)}`,p=i.provider==="docker"?`printf %s ${Lt(e.contentBase64)} | docker exec -i ${c} ${a}`:`printf %s ${Lt(e.contentBase64)} | ${a}`,f=await this.remote(i,[p],30,"ts-cloud runtime:file-write").catch(qs);return{...t,ok:f.success,size:n.byteLength,truncated:!1,error:f.success?void 0:f.error??f.perInstance?.[0]?.error??"File write failed."}}async fileTarget(e){let t=await this.workload(e.workloadId);if(!t)return{error:"Workload was not found in the current project and environment."};if(process.env.TS_CLOUD_RUNTIME_FILE_ACCESS==="0")return{error:"Runtime file access is disabled by TS_CLOUD_RUNTIME_FILE_ACCESS."};if(!t.capabilities.files.supported)return{error:t.capabilities.files.reason??"File access is unsupported for this workload."};if(e.confirm!==t.name)return{error:`Type "${t.name}" to access workload files.`};if(!e.recentAuth)return{error:"Sign in again before using elevated runtime access."};let r=CC(t,e.path);if(!r.ok)return{error:r.error};let n=EC(t,r.path),i=t.links.providerId??"";if(!n||t.provider==="systemd"&&!Js.test(i)||t.provider==="docker"&&!Ws.test(i))return{error:"File target identity is invalid or unsupported."};return{workload:t,path:r.path,root:n,providerId:i}}async logs(e,t={}){let r=await this.workload(e);if(!r)throw Error("Workload was not found in the current project and environment.");if(!r.capabilities.logs.supported)throw Error(r.capabilities.logs.reason??"Logs are unsupported for this workload.");let n=Math.min(1000,Math.max(1,Math.floor(t.limit??200)));if(r.provider==="lambda"||r.provider==="ecs"){let p=this.dependencies.logs??new hf(this.region,this.profile),f=r.config.logGroups,y=r.provider==="lambda"?`/aws/lambda/${r.name}`:Array.isArray(f)&&typeof f[0]==="string"?f[0]:void 0;if(!y)throw Error("The ECS task definition does not declare an awslogs group.");let b=await p.filterLogEvents({logGroupName:y,startTime:t.since?.getTime(),limit:n}),C=(b.events??[]).slice(0,n).map((T)=>({timestamp:T.timestamp==null?void 0:new Date(T.timestamp).toISOString(),message:fi(String(T.message??""))}));return{workloadId:e,provider:r.provider,lines:C,nextCursor:b.nextToken,truncated:(b.events?.length??0)>=n}}let i=r.links.providerId??"",o=t.since&&Number.isFinite(t.since.getTime())?t.since:void 0,s=r.provider==="systemd"&&Js.test(i)?`journalctl -u ${i} --no-pager -n ${n} -o short-iso${o?` --since ${Lt(o.toISOString())}`:""}`:r.provider==="docker"&&Ws.test(i)?`docker logs --timestamps --tail ${n}${o?` --since ${Math.floor(o.getTime()/1000)}`:""} ${i} 2>&1`:void 0;if(!s)throw Error("Log target identity is invalid.");let c=await this.remote(r,[s],30,"ts-cloud runtime:logs");if(!c.success)throw Error(c.error??c.perInstance?.[0]?.error??"Log read failed.");let u=fi(c.perInstance?.[0]?.output??""),a=u.split(`
|
|
122
|
-
`).filter(Boolean).slice(-n).map((p)=>{let f=/^(\d{4}-\d{2}-\d{2}T\S+)\s+(.*)$/.exec(p);return{timestamp:f?.[1],message:f?.[2]??p}});return{workloadId:e,provider:r.provider,lines:a,truncated:u.includes("[output truncated]")||a.length>=n}}}import{randomUUID as TC}from"node:crypto";class Zd{records=new Map;maxBufferBytes;ttlMs;now;constructor(e={}){this.maxBufferBytes=Math.max(1024,e.maxBufferBytes??262144),this.ttlMs=Math.max(1000,e.ttlMs??900000),this.now=e.now??(()=>new Date)}create(e,t){this.sweep();let r=this.now().toISOString(),n={id:TC(),workloadId:t,kind:e,state:"open",chunks:[],cursor:0,droppedBytes:0,bufferedBytes:0,createdAt:r,updatedAt:r,abort:new AbortController,listeners:new Set};return this.records.set(n.id,n),this.snapshot(n,0)}signal(e){return this.records.get(e)?.abort.signal}append(e,t,r="stdout"){let n=this.records.get(e);if(!n||n.state!=="open"||!t)return n?this.snapshot(n,n.cursor):void 0;let i=Buffer.from(t),o=i.byteLength>this.maxBufferBytes?i.subarray(i.byteLength-this.maxBufferBytes).toString("utf8"):t,s={cursor:++n.cursor,stream:r,data:o,at:this.now().toISOString()};n.chunks.push(s),n.bufferedBytes+=Buffer.byteLength(o),n.updatedAt=s.at;while(n.bufferedBytes>this.maxBufferBytes&&n.chunks.length>1){let c=n.chunks.shift(),u=Buffer.byteLength(c.data);n.bufferedBytes-=u,n.droppedBytes+=u}return this.publish(n),this.snapshot(n,s.cursor-1)}read(e,t,r=0){let n=this.records.get(e);if(!n||n.workloadId!==t)return;return n.updatedAt=this.now().toISOString(),this.snapshot(n,Math.max(0,Math.floor(r)))}close(e,t="complete",r){let n=this.records.get(e);if(!n||n.state!=="open")return n?this.snapshot(n,n.cursor):void 0;if(n.state=t,n.error=r,n.updatedAt=this.now().toISOString(),t==="cancelled")n.abort.abort();return this.publish(n),this.snapshot(n,n.cursor)}cancel(e,t){let r=this.records.get(e);if(!r||r.workloadId!==t)return;return this.close(e,"cancelled")}subscribe(e,t,r){let n=this.records.get(e);if(!n||n.workloadId!==t)return;return n.listeners.add(r),()=>n.listeners.delete(r)}sweep(){let e=this.now().getTime()-this.ttlMs,t=0;for(let[r,n]of this.records){if(new Date(n.updatedAt).getTime()>e)continue;n.abort.abort(),this.records.delete(r),t++}return t}clear(){for(let e of this.records.values())e.abort.abort();this.records.clear()}snapshot(e,t){let r=e.chunks[0]?.cursor??e.cursor+1,n=t>0&&t<r-1;return{id:e.id,workloadId:e.workloadId,kind:e.kind,state:e.state,chunks:e.chunks.filter((i)=>n||i.cursor>t),cursor:e.cursor,reset:n,droppedBytes:e.droppedBytes,createdAt:e.createdAt,updatedAt:e.updatedAt,error:e.error}}publish(e){let t=this.snapshot(e,0);for(let r of e.listeners)r(t)}}import{createHash as AC}from"node:crypto";var nu={info:0,low:1,medium:2,high:3,critical:4},iu={record:0,warn:1,block:2},yf=new Set(["skipped","unavailable","unsupported","stale"]);function Ne(e){return typeof e==="string"?e:void 0}function Zr(e,t){try{return JSON.parse(String(e))}catch{return t}}function Gt(e){return JSON.stringify($e(e))}function kC(e){if(!e)return;return String($e(e,2000))}function eu(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:Ne(e.project_id),environmentId:Ne(e.environment_id),resourceId:Ne(e.resource_id),releaseId:Ne(e.release_id),scannerId:String(e.scanner_id),scannerVersion:String(e.scanner_version),status:String(e.status),error:Ne(e.error),metadata:Zr(e.metadata,{}),findingsCount:Number(e.findings_count),startedAt:String(e.started_at),completedAt:String(e.completed_at),durationMs:Number(e.duration_ms)}}function bf(e){return{id:String(e.id),fingerprint:String(e.fingerprint),organizationId:String(e.organization_id),projectId:Ne(e.project_id),environmentId:Ne(e.environment_id),resourceId:Ne(e.resource_id),releaseId:Ne(e.release_id),scanRunId:String(e.scan_run_id),scannerId:String(e.scanner_id),scannerVersion:String(e.scanner_version),ruleId:String(e.rule_id),severity:String(e.severity),title:String(e.title),description:String(e.description),evidence:Zr(e.evidence,{}),remediation:Ne(e.remediation),subject:String(e.subject),status:String(e.status),ownerActorId:Ne(e.owner_actor_id),recurrenceCount:Number(e.recurrence_count),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),resolvedAt:Ne(e.resolved_at),updatedAt:String(e.updated_at)}}function tu(e){return{id:String(e.id),organizationId:String(e.organization_id),environmentId:Ne(e.environment_id),name:String(e.name),rules:Zr(e.rules,[]),requiredScanners:Zr(e.required_scanners,[]),scannerFailMode:String(e.scanner_fail_mode),enabled:Number(e.enabled)===1,version:Number(e.version),createdByActorId:Ne(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Sf(e,t){let r=Ne(e.revoked_at),n=String(e.expires_at);return{id:String(e.id),findingId:String(e.finding_id),policyId:Ne(e.policy_id),reason:String(e.reason),referenceUrl:Ne(e.reference_url),createdByActorId:String(e.created_by_actor_id),expiresAt:n,revokedAt:r,state:r?"revoked":n<=t?"expired":"active",createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ru(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Ne(e.environment_id),releaseId:String(e.release_id),kind:String(e.kind),format:String(e.format),digest:String(e.digest),summary:Zr(e.summary,{}),content:Ne(e.content),sensitive:Number(e.sensitive)===1,createdAt:String(e.created_at)}}function vf(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),operationId:Ne(e.operation_id),policyId:String(e.policy_id),policyVersion:Number(e.policy_version),outcome:String(e.outcome),scannerVersions:Zr(e.scanner_versions,{}),findingIds:Zr(e.finding_ids,[]),waiverIds:Zr(e.waiver_ids,[]),explanation:String(e.explanation),createdAt:String(e.created_at)}}function RC(e,t){let r=[e.trim().toLowerCase(),t.ruleId.trim().toLowerCase(),t.organizationId,t.projectId??"",t.environmentId??"",t.resourceId??"",t.releaseId??"",t.subject.trim().toLowerCase()].join("\x00");return AC("sha256").update(r).digest("hex")}function wf(e){if(!e)return;let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error("Security references must use HTTP or HTTPS");return t.toString()}function If(e){if(!e.length)throw Error("A security policy needs at least one rule");return e.map((t)=>{if(!(t.minimumSeverity in nu))throw Error(`Unknown security severity: ${t.minimumSeverity}`);if(!(t.action in iu))throw Error(`Unknown security policy action: ${t.action}`);return{minimumSeverity:t.minimumSeverity,action:t.action,...t.scannerId?{scannerId:t.scannerId.trim()}:{}}})}class eo{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}recordScan(e){if(!e.organizationId||!e.scannerId.trim()||!e.scannerVersion.trim())throw Error("Organization, scanner id, and scanner version are required");let t=e.completedAt??this.now(),r=e.startedAt??t,n=e.durationMs??Math.max(0,new Date(t).getTime()-new Date(r).getTime()),i=e.findings??[],o=this.idFn(),s=new Set,c=[];return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_scan_runs
|
|
123
|
-
(id, organization_id, project_id, environment_id, resource_id, release_id, scanner_id, scanner_version, status, error, metadata, findings_count, started_at, completed_at, duration_ms)
|
|
124
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,e.organizationId,e.projectId??null,e.environmentId??null,e.resourceId??null,e.releaseId??null,e.scannerId.trim(),e.scannerVersion.trim(),e.status,kC(e.error)??null,Gt(e.metadata??{}),i.length,r,t,Math.max(0,Math.floor(n))]);for(let u of i){let a={...u,organizationId:e.organizationId,projectId:u.projectId??e.projectId,environmentId:u.environmentId??e.environmentId,resourceId:u.resourceId??e.resourceId,releaseId:u.releaseId??e.releaseId},p=a.fingerprint?.trim()||RC(e.scannerId,a);s.add(p);let f=this.controlPlane.database.query("SELECT * FROM security_findings WHERE fingerprint = ?").get(p),y=f?this.controlPlane.database.query("SELECT * FROM security_waivers WHERE finding_id = ? AND revoked_at IS NULL AND expires_at > ? ORDER BY expires_at DESC LIMIT 1").get(String(f.id),t):void 0;if(f){let b=String(f.status)==="resolved"?Number(f.recurrence_count)+1:Number(f.recurrence_count),C=y?"waived":String(f.status)==="acknowledged"?"acknowledged":"open";this.run(`UPDATE security_findings SET scan_run_id = ?, scanner_version = ?, severity = ?, title = ?, description = ?, evidence = ?, remediation = ?,
|
|
125
|
-
status = ?, recurrence_count = ?, last_seen_at = ?, resolved_at = NULL, updated_at = ? WHERE id = ?`,[o,e.scannerVersion,a.severity,a.title.trim(),a.description.trim(),Gt(a.evidence??{}),a.remediation?.trim()||null,C,b,t,t,String(f.id)]),c.push(this.getFinding(String(f.id)))}else{let b=this.idFn();this.run(`INSERT INTO security_findings
|
|
126
|
-
(id, fingerprint, organization_id, project_id, environment_id, resource_id, release_id, scan_run_id, scanner_id, scanner_version, rule_id,
|
|
127
|
-
severity, title, description, evidence, remediation, subject, status, first_seen_at, last_seen_at, updated_at)
|
|
128
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`,[b,p,a.organizationId,a.projectId??null,a.environmentId??null,a.resourceId??null,a.releaseId??null,o,e.scannerId,e.scannerVersion,a.ruleId.trim(),a.severity,a.title.trim(),a.description.trim(),Gt(a.evidence??{}),a.remediation?.trim()||null,a.subject.trim(),t,t,t]),c.push(this.getFinding(b))}}if(e.status==="passed"||e.status==="failed"){let u=this.controlPlane.database.query(`SELECT * FROM security_findings WHERE organization_id = ? AND scanner_id = ?
|
|
129
|
-
AND project_id IS ? AND environment_id IS ? AND resource_id IS ? AND release_id IS ? AND status != 'resolved'`).all(e.organizationId,e.scannerId,e.projectId??null,e.environmentId??null,e.resourceId??null,e.releaseId??null);for(let a of u){if(s.has(String(a.fingerprint)))continue;this.run("UPDATE security_findings SET status = 'resolved', resolved_at = ?, updated_at = ? WHERE id = ?",[t,t,String(a.id)]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,type:"security.finding.resolved",payload:{findingId:String(a.id),scannerId:e.scannerId,reason:"not-observed"}})}}this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,type:"security.scan.completed",level:e.status==="failed"||yf.has(e.status)?"warning":"info",payload:{scanRunId:o,scannerId:e.scannerId,scannerVersion:e.scannerVersion,status:e.status,findingsCount:i.length,durationMs:n}})}),{run:this.getScanRun(o),findings:c.map((u)=>this.getFinding(u.id))}}getScanRun(e){let t=this.controlPlane.database.query("SELECT * FROM security_scan_runs WHERE id = ?").get(e);return t?eu(t):void 0}listScanRuns(e){return this.controlPlane.database.query("SELECT * FROM security_scan_runs WHERE organization_id = ? AND project_id IS ? AND environment_id IS ? ORDER BY completed_at DESC, id DESC LIMIT ?").all(e.organizationId,e.projectId??null,e.environmentId??null,Math.min(500,Math.max(1,e.limit??100))).map(eu)}getFinding(e){let t=this.controlPlane.database.query("SELECT * FROM security_findings WHERE id = ?").get(e);return t?bf(t):void 0}listFindings(e){this.expireWaivers();let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.environmentId)t.push("environment_id = ?"),r.push(e.environmentId);if(e.status)t.push("status = ?"),r.push(e.status);if(e.severity)t.push("severity = ?"),r.push(e.severity);return r.push(Math.min(1000,Math.max(1,e.limit??250))),this.controlPlane.database.query(`SELECT * FROM security_findings WHERE ${t.join(" AND ")} ORDER BY CASE severity WHEN 'critical' THEN 4 WHEN 'high' THEN 3 WHEN 'medium' THEN 2 WHEN 'low' THEN 1 ELSE 0 END DESC, last_seen_at DESC LIMIT ?`).all(...r).map(bf)}assignFinding(e,t,r){let n=this.getFinding(e);if(!n)throw Error("Security finding was not found");if(t&&!this.controlPlane.getActor(t))throw Error("Finding owner was not found");return this.run("UPDATE security_findings SET owner_actor_id = ?, updated_at = ? WHERE id = ?",[t??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,resourceId:n.resourceId,actorId:r,type:"security.finding.assigned",payload:{findingId:e,ownerActorId:t??null}}),this.getFinding(e)}acknowledgeFinding(e,t){let r=this.getFinding(e);if(!r)throw Error("Security finding was not found");if(r.status==="resolved")throw Error("A resolved finding cannot be acknowledged");return this.run("UPDATE security_findings SET status = 'acknowledged', updated_at = ? WHERE id = ?",[this.now(),e]),this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,resourceId:r.resourceId,actorId:t,type:"security.finding.acknowledged",payload:{findingId:e}}),this.getFinding(e)}addComment(e){let t=this.getFinding(e.findingId);if(!t)throw Error("Security finding was not found");let r=e.body.trim();if(r.length<2||r.length>4000)throw Error("Finding comments must contain 2-4,000 characters");let n=wf(e.referenceUrl),i=this.idFn(),o=this.now();return this.run("INSERT INTO security_finding_comments (id, finding_id, actor_id, body, reference_url, created_at) VALUES (?, ?, ?, ?, ?, ?)",[i,e.findingId,e.actorId,r,n??null,o]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,actorId:e.actorId,type:"security.finding.commented",payload:{findingId:e.findingId,commentId:i,referenceUrl:n??null}}),{id:i,findingId:e.findingId,actorId:e.actorId,body:r,referenceUrl:n,createdAt:o}}listComments(e){return this.controlPlane.database.query("SELECT * FROM security_finding_comments WHERE finding_id = ? ORDER BY created_at, id").all(e).map((t)=>({id:String(t.id),findingId:String(t.finding_id),actorId:String(t.actor_id),body:String(t.body),referenceUrl:Ne(t.reference_url),createdAt:String(t.created_at)}))}createWaiver(e){let t=this.getFinding(e.findingId);if(!t)throw Error("Security finding was not found");let r=e.reason.trim();if(r.length<8||r.length>1000)throw Error("A waiver reason must contain 8-1,000 characters");let n=this.now(),i=new Date(e.expiresAt);if(!Number.isFinite(i.getTime())||i.toISOString()<=n)throw Error("A waiver must have a future expiry");if(i.getTime()-new Date(n).getTime()>31536000000)throw Error("A waiver cannot last longer than one year");let o=e.policyId?this.getPolicy(e.policyId):void 0;if(e.policyId&&(!o||o.organizationId!==t.organizationId))throw Error("Waiver policy does not match the finding organization");let s=this.idFn(),c=wf(e.referenceUrl);return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_waivers (id, finding_id, policy_id, reason, reference_url, created_by_actor_id, expires_at, created_at, updated_at)
|
|
130
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s,t.id,e.policyId??null,r,c??null,e.actorId,i.toISOString(),n,n]),this.run("UPDATE security_findings SET status = 'waived', updated_at = ? WHERE id = ?",[n,t.id]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,actorId:e.actorId,type:"security.waiver.created",level:"warning",payload:{waiverId:s,findingId:t.id,policyId:e.policyId??null,reason:r,expiresAt:i.toISOString(),referenceUrl:c??null}})}),this.getWaiver(s)}revokeWaiver(e,t){let r=this.getWaiver(e);if(!r)throw Error("Security waiver was not found");if(r.revokedAt)return r;let n=this.getFinding(r.findingId),i=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE security_waivers SET revoked_at = ?, updated_at = ? WHERE id = ?",[i,i,e]),this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ? AND status = 'waived'",[i,r.findingId]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,resourceId:n.resourceId,actorId:t,type:"security.waiver.revoked",level:"warning",payload:{waiverId:e,findingId:r.findingId}})}),this.getWaiver(e)}getWaiver(e){let t=this.controlPlane.database.query("SELECT * FROM security_waivers WHERE id = ?").get(e);return t?Sf(t,this.now()):void 0}listWaivers(e){return(e?this.controlPlane.database.query("SELECT * FROM security_waivers WHERE finding_id = ? ORDER BY created_at DESC").all(e):this.controlPlane.database.query("SELECT * FROM security_waivers ORDER BY created_at DESC").all()).map((r)=>Sf(r,this.now()))}expireWaivers(){let e=this.now(),t=this.controlPlane.database.query(`SELECT w.id AS waiver_id, f.* FROM security_waivers w JOIN security_findings f ON f.id = w.finding_id
|
|
131
|
-
WHERE w.revoked_at IS NULL AND w.expires_at <= ? AND f.status = 'waived'`).all(e);for(let r of t)this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ?",[e,String(r.id)]),this.controlPlane.appendEvent({organizationId:String(r.organization_id),projectId:Ne(r.project_id),resourceId:Ne(r.resource_id),type:"security.waiver.expired",level:"warning",payload:{waiverId:String(r.waiver_id),findingId:String(r.id)}});return t.length}createPolicy(e){let t=e.name.trim();if(!t)throw Error("Security policy name is required");let r=If(e.rules),n=this.idFn(),i=this.now(),o=[...new Set((e.requiredScanners??[]).map((s)=>s.trim()).filter(Boolean))].sort();return this.run(`INSERT INTO security_policies (id, organization_id, environment_id, name, rules, required_scanners, scanner_fail_mode, created_by_actor_id, created_at, updated_at)
|
|
132
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.organizationId,e.environmentId??null,t,Gt(r),Gt(o),e.scannerFailMode,e.actorId??null,i,i]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"security.policy.created",payload:{policyId:n,environmentId:e.environmentId??null,scannerFailMode:e.scannerFailMode,requiredScanners:o,rules:$e(r)}}),this.getPolicy(n)}updatePolicy(e,t,r){let n=this.getPolicy(e);if(!n||n.version!==t)throw Error(`Security policy ${e} changed since version ${t}`);let i=r.rules?If(r.rules):n.rules,o=r.requiredScanners?[...new Set(r.requiredScanners.map((u)=>u.trim()).filter(Boolean))].sort():n.requiredScanners,s=this.now();if(this.controlPlane.database.run("UPDATE security_policies SET name = ?, rules = ?, required_scanners = ?, scanner_fail_mode = ?, enabled = ?, version = version + 1, updated_at = ? WHERE id = ? AND version = ?",[r.name?.trim()||n.name,Gt(i),Gt(o),r.scannerFailMode??n.scannerFailMode,r.enabled??n.enabled?1:0,s,e,t]).changes!==1)throw Error(`Security policy ${e} changed since version ${t}`);return this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"security.policy.updated",payload:{policyId:e,fromVersion:t,toVersion:t+1}}),this.getPolicy(e)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM security_policies WHERE id = ?").get(e);return t?tu(t):void 0}listPolicies(e){return this.controlPlane.database.query("SELECT * FROM security_policies WHERE organization_id = ? ORDER BY environment_id, name").all(e).map(tu)}evaluateGate(e){this.expireWaivers();let t=e.policyId?this.getPolicy(e.policyId):this.controlPlane.database.query(`SELECT * FROM security_policies WHERE organization_id = ? AND enabled = 1 AND (environment_id = ? OR environment_id IS NULL)
|
|
133
|
-
ORDER BY CASE WHEN environment_id = ? THEN 0 ELSE 1 END, updated_at DESC LIMIT 1`).get(e.organizationId,e.environmentId,e.environmentId),r=t&&"rules"in t&&Array.isArray(t.rules)?t:t?tu(t):void 0;if(!r||!r.enabled)throw Error("No enabled security policy applies to this environment");let n=this.listFindings({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,limit:1000}).filter((Z)=>Z.status!=="resolved"),i=new Map;for(let Z of n){let Le=this.listWaivers(Z.id).find((ue)=>ue.state==="active"&&(!ue.policyId||ue.policyId===r.id));if(Le)i.set(Z.id,Le)}let o=(Z)=>r.rules.filter((Le)=>(!Le.scannerId||Le.scannerId===Z.scannerId)&&nu[Z.severity]>=nu[Le.minimumSeverity]).reduce((Le,ue)=>iu[ue.action]>iu[Le]?ue.action:Le,"record"),s=n.filter((Z)=>!i.has(Z.id)&&o(Z)==="block"),c=n.filter((Z)=>!i.has(Z.id)&&o(Z)==="warn"),u=this.controlPlane.database.query(`SELECT run.* FROM security_scan_runs run
|
|
134
|
-
WHERE run.organization_id = ? AND run.project_id = ? AND run.environment_id = ?
|
|
135
|
-
AND run.id = (SELECT candidate.id FROM security_scan_runs candidate
|
|
136
|
-
WHERE candidate.organization_id = run.organization_id AND candidate.project_id = run.project_id
|
|
137
|
-
AND candidate.environment_id = run.environment_id AND candidate.scanner_id = run.scanner_id
|
|
138
|
-
ORDER BY candidate.completed_at DESC, candidate.rowid DESC LIMIT 1)`).all(e.organizationId,e.projectId,e.environmentId),a=e.staleAfterMs??86400000,p=this.nowFn().getTime(),f=u.map(eu).map((Z)=>p-new Date(Z.completedAt).getTime()>a?{...Z,status:"stale"}:Z),y=new Set(f.map((Z)=>Z.scannerId)),b=r.requiredScanners.filter((Z)=>!y.has(Z)).map((Z)=>({id:`missing:${Z}`,organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,scannerId:Z,scannerVersion:"unavailable",status:"unavailable",metadata:{},findingsCount:0,startedAt:this.now(),completedAt:this.now(),durationMs:0})),C=[...f,...b],T=C.filter((Z)=>r.requiredScanners.includes(Z.scannerId)&&yf.has(Z.status)),R=Object.fromEntries(C.map((Z)=>[Z.scannerId,Z.scannerVersion])),x=r.scannerFailMode==="closed"&&T.length>0,L=s.length||x?"block":c.length||T.length?"warn":"allow",P=[];if(s.length)P.push(`${s.length} finding${s.length===1?"":"s"} blocked by policy`);if(c.length)P.push(`${c.length} warning${c.length===1?"":"s"} require review`);if(T.length)P.push(`${T.length} scanner${T.length===1?"":"s"} ${r.scannerFailMode==="closed"?"failed closed":"failed open"}`);if(i.size)P.push(`${i.size} active time-limited waiver${i.size===1?"":"s"}`);if(!P.length)P.push("All recorded checks satisfy policy");let G=this.idFn(),ae=this.now();return this.run(`INSERT INTO security_deploy_decisions
|
|
139
|
-
(id, organization_id, project_id, environment_id, operation_id, policy_id, policy_version, outcome, scanner_versions, finding_ids, waiver_ids, explanation, created_at)
|
|
140
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[G,e.organizationId,e.projectId,e.environmentId,e.operationId??null,r.id,r.version,L,Gt(R),Gt([...s,...c].map((Z)=>Z.id)),Gt([...i.values()].map((Z)=>Z.id)),P.join("; "),ae]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,operationId:e.operationId,type:"security.deploy.decision",level:L==="block"?"error":L==="warn"?"warning":"info",payload:{decisionId:G,outcome:L,policyId:r.id,policyVersion:r.version,scannerVersions:R,blockerIds:s.map((Z)=>Z.id),waiverIds:[...i.values()].map((Z)=>Z.id),explanation:P.join("; ")}}),this.getDecision(G)}getDecision(e){let t=this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE id = ?").get(e);return t?vf(t):void 0}listDecisions(e,t=100){return this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE environment_id = ? ORDER BY created_at DESC LIMIT ?").all(e,Math.min(500,Math.max(1,t))).map(vf)}addReleaseArtifact(e){let t=this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? AND kind = ? AND digest = ?").get(e.releaseId,e.kind,e.digest);if(t)return ru(t);let r=this.idFn(),n=this.now();return this.run(`INSERT INTO release_security_artifacts
|
|
141
|
-
(id, organization_id, project_id, environment_id, release_id, kind, format, digest, summary, content, sensitive, created_at)
|
|
142
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.projectId,e.environmentId??null,e.releaseId,e.kind,e.format,e.digest,Gt(e.summary),e.content??null,e.sensitive?1:0,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,type:"security.release_artifact.created",payload:{artifactId:r,releaseId:e.releaseId,kind:e.kind,format:e.format,digest:e.digest,sensitive:e.sensitive}}),ru(this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE id = ?").get(r))}listReleaseArtifacts(e,t=!1){return this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? ORDER BY created_at, kind").all(e).map(ru).map((r)=>r.sensitive&&!t?{...r,content:void 0}:r)}summary(e,t,r){let n=this.listFindings({organizationId:e,projectId:t,environmentId:r,limit:1000}),i=this.listScanRuns({organizationId:e,projectId:t,environmentId:r,limit:1000}),o={info:0,low:0,medium:0,high:0,critical:0};for(let c of n)if(c.status==="open"||c.status==="acknowledged")o[c.severity]++;let s={passed:0,failed:0,skipped:0,unavailable:0,unsupported:0,stale:0};for(let c of i)s[c.status]++;return{open:o,waived:n.filter((c)=>c.status==="waived").length,resolved:n.filter((c)=>c.status==="resolved").length,checks:s,lastScannedAt:i[0]?.completedAt}}exportPosture(e){let t=this.controlPlane.listProjects().filter((r)=>r.organizationId===e);return $e({format:"ts-cloud-security-posture",version:1,exportedAt:this.now(),organizationId:e,policies:this.listPolicies(e),findings:this.listFindings({organizationId:e,limit:1000}),waivers:this.listWaivers().filter((r)=>this.getFinding(r.findingId)?.organizationId===e),scans:t.flatMap((r)=>this.listScanRuns({organizationId:e,projectId:r.id,limit:1000})),decisions:t.flatMap((r)=>this.controlPlane.listEnvironments(r.id).flatMap((n)=>this.listDecisions(n.id,1000)))})}}import{existsSync as PC,readdirSync as xC,readFileSync as DC,statSync as OC}from"node:fs";import{extname as _C,join as NC,relative as $C}from"node:path";var Cf=[{name:"AWS Access Key ID",pattern:/(?:^|[^A-Z0-9])((AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16})(?:[^A-Z0-9]|$)/g,severity:"critical",description:"AWS Access Key ID detected"},{name:"AWS Secret Access Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key|secretAccessKey)['"]?\s*[=:]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,severity:"critical",description:"AWS Secret Access Key detected"},{name:"AWS Secret Key (Generic)",pattern:/(?:^|['"`:=\s])([A-Za-z0-9/+=]{40})(?:['"`\s]|$)/g,severity:"high",description:"Potential AWS Secret Key (40-char base64)"},{name:"Generic API Key",pattern:/(?:api[_-]?key|apikey|api[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,severity:"high",description:"Generic API key detected"},{name:"RSA Private Key",pattern:/-----BEGIN RSA PRIVATE KEY-----/g,severity:"critical",description:"RSA private key detected"},{name:"OpenSSH Private Key",pattern:/-----BEGIN OPENSSH PRIVATE KEY-----/g,severity:"critical",description:"OpenSSH private key detected"},{name:"EC Private Key",pattern:/-----BEGIN EC PRIVATE KEY-----/g,severity:"critical",description:"EC private key detected"},{name:"PGP Private Key",pattern:/-----BEGIN PGP PRIVATE KEY BLOCK-----/g,severity:"critical",description:"PGP private key detected"},{name:"GitHub Token",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"critical",description:"GitHub personal access token detected"},{name:"GitHub OAuth",pattern:/github[_-]?oauth[_-]?token\s*[=:]\s*['"]?([A-Za-z0-9_]{40})['"]?/gi,severity:"critical",description:"GitHub OAuth token detected"},{name:"Slack Token",pattern:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,severity:"critical",description:"Slack token detected"},{name:"Slack Webhook",pattern:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high",description:"Slack webhook URL detected"},{name:"Discord Webhook",pattern:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g,severity:"high",description:"Discord webhook URL detected"},{name:"JWT Token",pattern:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,severity:"high",description:"JWT token detected"},{name:"Google API Key",pattern:/AIza[0-9A-Za-z_-]{35}/g,severity:"critical",description:"Google API key detected"},{name:"Google OAuth ID",pattern:/[0-9]+-[A-Za-z0-9_]{32}\.apps\.googleusercontent\.com/g,severity:"high",description:"Google OAuth client ID detected"},{name:"Firebase API Key",pattern:/(?:firebase[_-]?api[_-]?key)\s*[=:]\s*['"]?([A-Za-z0-9_-]{39})['"]?/gi,severity:"critical",description:"Firebase API key detected"},{name:"Cloudflare API Token",pattern:/(?:cloudflare[_-]?api[_-]?token|cf[_-]?api[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{40})['"]?/gi,severity:"critical",description:"Cloudflare API token detected"},{name:"Azure Client Secret",pattern:/(?:azure[_-]?client[_-]?secret|client[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9~._-]{34,})['"]?/gi,severity:"critical",description:"Azure client secret detected"},{name:"Heroku API Key",pattern:/(?:heroku[_-]?api[_-]?key)\s*[=:]\s*['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})['"]?/gi,severity:"critical",description:"Heroku API key detected"},{name:"Database Connection String",pattern:/(?:mysql|postgres|postgresql|mongodb|redis|mongodb\+srv):\/\/[^:]+:[^@]+@[^/\s]+/gi,severity:"critical",description:"Database connection string with credentials detected"},{name:"Database Password",pattern:/(?:db[_-]?password|database[_-]?password|mysql[_-]?password|postgres[_-]?password)\s*[=:]\s*['"]?([^'"\s]{8,})['"]?/gi,severity:"critical",description:"Database password detected"},{name:"Stripe API Key",pattern:/(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}/g,severity:"critical",description:"Stripe API key detected"},{name:"PayPal Client ID",pattern:/(?:paypal[_-]?client[_-]?id)\s*[=:]\s*['"]?([A-Za-z0-9_-]{80})['"]?/gi,severity:"high",description:"PayPal client ID detected"},{name:"Square Access Token",pattern:/sq0[a-z]{3}-[0-9A-Za-z_-]{22,}/g,severity:"critical",description:"Square access token detected"},{name:"Twilio API Key",pattern:/SK[a-f0-9]{32}/g,severity:"critical",description:"Twilio API key detected"},{name:"SendGrid API Key",pattern:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g,severity:"critical",description:"SendGrid API key detected"},{name:"Mailgun API Key",pattern:/key-[0-9a-zA-Z]{32}/g,severity:"critical",description:"Mailgun API key detected"},{name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"]([^'"]{8,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded password detected"},{name:"Secret/Token Assignment",pattern:/(?:secret|token|auth[_-]?token|access[_-]?token)\s*[=:]\s*['"]([A-Za-z0-9_\-/+=]{16,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded secret or token detected"},{name:"NPM Token",pattern:/(?:npm[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{36})['"]?/gi,severity:"critical",description:"NPM token detected"},{name:"SSH Private Key Path Exposed",pattern:/~\/\.ssh\/id_[a-z]+|\/home\/[^/]+\/\.ssh\/id_[a-z]+/g,severity:"medium",description:"SSH private key path exposed"},{name:"Env Variable with Secret",pattern:/(?:process\.env\.)((?=[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|CREDENTIAL|AUTH))[A-Z_]+)\s*(?:===?\s*['"]([^'"]+)['"])?/g,severity:"medium",description:"Environment variable containing secret may be exposed"}],MC=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".vue",".svelte",".html",".htm",".css",".scss",".less",".json",".yaml",".yml",".toml",".xml",".env",".config",".conf"],LC=["node_modules",".git",".svn",".hg","dist","build","coverage",".nyc_output","__pycache__",".pytest_cache","vendor",".idea",".vscode",".turbo",".next",".nuxt","framework.bak","pantry",".pantry","tests","test","__tests__","spec","__mocks__",".github",".gitlab",".circleci"],BC=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","*.min.js","*.min.css","*.map","*.d.ts","*.test.ts","*.test.js","*.spec.ts","*.spec.js",".env",".env.*"];class Hs{patterns;excludeDirs;excludeFiles;maxFileSize;constructor(e){this.patterns=[...Cf,...e?.customPatterns||[]],this.excludeDirs=[...LC,...e?.excludeDirs||[]],this.excludeFiles=[...BC,...e?.excludeFiles||[]],this.maxFileSize=e?.maxFileSize||1048576}async scan(e){let t=Date.now(),r=[],n=0,{directory:i,exclude:o=[],include:s,skipPatterns:c=[]}=e,u=e.failOnSeverity||"critical";if(!PC(i))throw Error(`Directory not found: ${i}`);let a=this.getFilesToScan(i,[...this.excludeDirs,...o],s);for(let C of a){let T=$C(i,C);if(this.shouldExcludeFile(T))continue;try{if(OC(C).size>this.maxFileSize)continue;let x=DC(C,"utf-8"),L=this.scanContent(x,T,c);r.push(...L),n++}catch{continue}}let p={critical:r.filter((C)=>C.pattern.severity==="critical").length,high:r.filter((C)=>C.pattern.severity==="high").length,medium:r.filter((C)=>C.pattern.severity==="medium").length,low:r.filter((C)=>C.pattern.severity==="low").length},f=["low","medium","high","critical"],y=f.indexOf(u),b=!0;for(let C=y;C<f.length;C++)if(p[f[C]]>0){b=!1;break}return{passed:b,findings:r,scannedFiles:n,duration:Date.now()-t,summary:p}}scanContent(e,t,r){let n=[],i=e.split(`
|
|
143
|
-
`);for(let o of this.patterns){if(r.includes(o.name))continue;o.pattern.lastIndex=0;let s;while((s=o.pattern.exec(e))!==null){let c=e.substring(0,s.index),u=c.split(`
|
|
144
|
-
`).length,a=c.lastIndexOf(`
|
|
145
|
-
`),p=s.index-a,f=i[u-1]||"";if(this.isLikelyPlaceholder(s[0],f))continue;let y=s[1]||s[0];if(o.name==="AWS Secret Key (Generic)"&&/^[a-f0-9]{40}$/i.test(y))continue;if(o.name==="AWS Secret Key (Generic)"&&!this.hasSecretCharacterDiversity(y))continue;if(o.name==="AWS Secret Key (Generic)"&&/^(?:Actions|Commands|Controllers|Handlers|Jobs|Listeners|Middleware|Models|Resources|Services)\//.test(y))continue;if(this.isLowEntropy(y))continue;n.push({file:t,line:u,column:p,match:this.maskSecret(s[0]),pattern:o,context:this.maskSecret(f.trim())})}}return n}isLikelyPlaceholder(e,t){let r=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],n=e.toLowerCase(),i=t.toLowerCase();for(let s of r)if(n.includes(s.toLowerCase())||i.includes(s.toLowerCase()))return!0;let o=t.trim();if(o.startsWith("//")||o.startsWith("#")||o.startsWith("*")||o.startsWith("/*")){if(i.includes("example")||i.includes("format:")||i.includes("e.g."))return!0}return!1}isLowEntropy(e){if(e.length<8)return!1;if(new Set(e).size<8)return!0;if(/(.)\1{3,}/.test(e))return!0;return!1}hasSecretCharacterDiversity(e){let t=/[\d+=]/.test(e),r=[/[a-z]/.test(e),/[A-Z]/.test(e),/\d/.test(e),/[/+=]/.test(e)];return t&&r.filter(Boolean).length>=3}maskSecret(e){if(e.length<=8)return"*".repeat(e.length);let t=Math.min(4,Math.floor(e.length*0.2));return e.substring(0,t)+"*".repeat(e.length-t*2)+e.substring(e.length-t)}getFilesToScan(e,t,r){let n=[],i=r||MC,o=(s)=>{let c=xC(s,{withFileTypes:!0});for(let u of c){let a=NC(s,u.name);if(u.isDirectory()){if(!t.includes(u.name))o(a)}else if(u.isFile()){let p=_C(u.name).toLowerCase();if(i.includes(p)||u.name.startsWith(".env")||u.name.endsWith(".config"))n.push(a)}}};return o(e),n}shouldExcludeFile(e){let t=e.split("/").pop()||"";for(let r of this.excludeFiles)if(r.startsWith("*")){let n=r.substring(1);if(t.endsWith(n))return!0}else if(r.endsWith("*")){let n=r.substring(0,r.length-1);if(t.startsWith(n))return!0}else if(t===r)return!0;return!1}addPattern(e){this.patterns.push(e)}getPatterns(){return[...this.patterns]}}function jC(e,t){return{status:"unavailable",findings:[],error:`${e.id} exceeded its ${t}ms timeout`,metadata:{timeoutMs:t}}}class xn{posture;defaultTimeoutMs;nowFn;constructor(e,t={}){this.posture=e;this.defaultTimeoutMs=t.defaultTimeoutMs??60000,this.nowFn=t.now??(()=>new Date)}async run(e,t){let r=this.nowFn(),n=Math.max(100,e.timeoutMs??this.defaultTimeoutMs),i=new AbortController,o,s=new Promise((p)=>{o=setTimeout(()=>{i.abort(),p(jC(e,n))},n)}),c;try{c=await Promise.race([e.scan({...t,signal:i.signal}),s])}catch(p){c={status:"unavailable",findings:[],error:p instanceof Error?p.message:String(p)}}finally{if(o)clearTimeout(o)}let u=this.nowFn(),a={...t,scannerId:e.id,scannerVersion:e.version,status:c.status,findings:c.findings,metadata:c.metadata,error:c.error,startedAt:r.toISOString(),completedAt:u.toISOString(),durationMs:Math.max(0,u.getTime()-r.getTime())};return this.posture.recordScan(a)}async runAll(e,t){return Promise.all(e.map((r)=>this.run(r,t)))}}class to{scanner;id="source-secrets";version="1.0.0";timeoutMs=30000;constructor(e=new Hs){this.scanner=e}async scan(e){if(!e.artifactRoot)return{status:"skipped",findings:[],error:"No artifact root was supplied"};let t=await this.scanner.scan({directory:e.artifactRoot,failOnSeverity:"critical"});return{status:t.passed?"passed":"failed",findings:t.findings.map((r)=>({...e,ruleId:r.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:r.pattern.severity,title:r.pattern.name,description:r.pattern.description,subject:`${r.file}:${r.line}`,evidence:{file:r.file,line:r.line,column:r.column,match:r.match,context:r.context},remediation:"Remove the credential, rotate it at its issuer, and use a managed secret or environment reference."})),metadata:{scannedFiles:t.scannedFiles,summary:t.summary}}}}function FC(e){let t=e?.toLowerCase();return t==="critical"||t==="high"||t==="medium"||t==="low"?t:"info"}class ou{id="trivy-image";version;timeoutMs;constructor(e={}){this.version=e.version??"local",this.timeoutMs=e.timeoutMs??120000,this.executable=e.executable??"trivy"}executable;async scan(e){if(!e.imageRef)return{status:"skipped",findings:[],error:"No image reference was supplied"};let t;try{t=Bun.spawn([this.executable,"image","--format","json","--quiet","--scanners","vuln",e.imageRef],{stdout:"pipe",stderr:"pipe",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",TRIVY_NO_PROGRESS:"true"}})}catch(u){return{status:"unsupported",findings:[],error:u instanceof Error?u.message:String(u)}}let r=()=>t.kill();e.signal.addEventListener("abort",r,{once:!0});let[n,i,o]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);if(e.signal.removeEventListener("abort",r),n!==0)return{status:/not found|enoent/i.test(o)?"unsupported":"unavailable",findings:[],error:o.slice(0,2000)||`Trivy exited with ${n}`};let s=JSON.parse(i),c=[];for(let u of s.Results??[])for(let a of u.Vulnerabilities??[]){let p=a.VulnerabilityID??"unknown-vulnerability";c.push({...e,ruleId:p,severity:FC(a.Severity),title:a.Title||p,description:a.Description||`${p} affects ${a.PkgName??"an image package"}.`,subject:`${e.imageRef}:${a.PkgName??"unknown"}:${a.InstalledVersion??"unknown"}`,evidence:{image:e.imageRef,target:u.Target??"",cve:p,package:a.PkgName??"",installedVersion:a.InstalledVersion??"",fixedVersion:a.FixedVersion??"",reference:a.PrimaryURL??""},remediation:a.FixedVersion?`Upgrade ${a.PkgName} to ${a.FixedVersion} or later.`:"Remove or replace the affected package and rescan the image."})}return{status:c.length?"failed":"passed",findings:c,metadata:{imageRef:e.imageRef,vulnerabilityCount:c.length,localOnly:!0}}}}import{createHash as UC,createVerify as y$}from"node:crypto";import{existsSync as zC,readFileSync as VC}from"node:fs";import{basename as qC,join as JC,resolve as Ef}from"node:path";function ro(e){return UC("sha256").update(e).digest("hex")}function WC(e){let t=[["dependencies","required"],["optionalDependencies","optional"],["devDependencies","excluded"],["peerDependencies","required"]],r=new Map;for(let[n,i]of t){let o=e[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,c]of Object.entries(o)){let u=String(c).replace(/^[~^]/,""),a=`${s}@${u}`;if(!r.has(a))r.set(a,{type:"library",name:s,version:u,purl:`pkg:npm/${encodeURIComponent(s)}@${encodeURIComponent(u)}`,scope:i})}}return[...r.values()].sort((n,i)=>`${n.name}@${n.version}`.localeCompare(`${i.name}@${i.version}`))}function Tf(e,t={}){let r=JC(Ef(e),"package.json");if(!zC(r))throw Error(`Cannot generate an SBOM: ${r} was not found`);let n=VC(r,"utf8"),i=JSON.parse(n),o=String(i.name??qC(Ef(e))),s=String(i.version??"0.0.0"),c=ro(n);return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:t.serial??`urn:uuid:${crypto.randomUUID()}`,version:1,metadata:{timestamp:(t.now??new Date).toISOString(),component:{type:"application",name:o,version:s,purl:`pkg:npm/${encodeURIComponent(o)}@${encodeURIComponent(s)}`,hashes:[{alg:"SHA-256",content:c}]},tools:[{vendor:"ts-cloud",name:"security-posture",version:"1.0.0"}]},components:WC(i)}}async function Af(e,t={}){let r=Bun.spawn([t.executable??"syft",e,"-o","cyclonedx-json"],{stdout:"pipe",stderr:"pipe",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",SYFT_CHECK_FOR_APP_UPDATE:"false"}}),n=()=>r.kill();t.signal?.addEventListener("abort",n,{once:!0});let[i,o,s]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);if(t.signal?.removeEventListener("abort",n),i!==0)throw Error(s.slice(0,2000)||`Syft exited with ${i}`);return JSON.parse(o)}function su(e,t,r){let n=JSON.stringify(r);return e.addReleaseArtifact({...t,kind:"sbom",format:`cyclonedx-${r.specVersion}+json`,digest:`sha256:${ro(n)}`,summary:{component:r.metadata.component.name,version:r.metadata.component.version,components:r.components.length},content:n,sensitive:!0})}function kf(e,t,r){let n={total:r.length,critical:0,high:0,medium:0,low:0,info:0,fixable:0};for(let o of r){n[o.severity]++;let s=o.evidence;if(typeof s.fixedVersion==="string"&&s.fixedVersion)n.fixable++}let i=JSON.stringify({releaseId:t.releaseId,generatedAt:new Date().toISOString(),findings:r.map((o)=>({id:o.id,ruleId:o.ruleId,severity:o.severity,subject:o.subject,remediation:o.remediation}))});return e.addReleaseArtifact({...t,kind:"vulnerability_summary",format:"ts-cloud-vulnerability-summary+json",digest:`sha256:${ro(i)}`,summary:n,content:i,sensitive:!0})}function Rf(e){if(!e.artifact&&!e.artifactSha256)throw Error("Release provenance requires artifact content or a SHA-256 digest");return{_type:"https://in-toto.io/Statement/v1",subject:[{name:e.artifactName,digest:{sha256:e.artifactSha256?.replace(/^sha256:/,"")??ro(e.artifact)}}],predicateType:"https://slsa.dev/provenance/v1",predicate:{buildDefinition:{buildType:"https://ts-cloud.dev/build/v1",externalParameters:e.externalParameters??{},internalParameters:{},resolvedDependencies:e.resolvedDependencies??[]},runDetails:{builder:{id:"https://ts-cloud.dev/builders/local/v1"},metadata:{invocationId:e.invocationId,startedOn:e.startedAt,finishedOn:e.completedAt}}}}}function Pf(e,t,r){let n=JSON.stringify(r);return e.addReleaseArtifact({...t,kind:"provenance",format:"in-toto+slsa-v1+json",digest:`sha256:${ro(n)}`,summary:{subjects:r.subject.length,builder:r.predicate.runDetails.builder.id,buildType:r.predicate.buildDefinition.buildType},content:n,sensitive:!0})}function Kt(e,t){let r=e.environments.get(t);if(!r)throw Error(`Security scope for environment '${t}' was not found`);return{organizationId:e.organization.id,projectId:e.project.id,environmentId:r.id}}function xf(e,t){let r=new eo(e.store),n=r.listPolicies(e.organization.id);for(let[i,o]of e.environments){if(n.some((c)=>c.environmentId===o.id))continue;let s=i==="production"||o.kind==="production";n.push(r.createPolicy({organizationId:e.organization.id,environmentId:o.id,name:s?"Production baseline":"Environment baseline",scannerFailMode:s?"closed":"open",requiredScanners:["source-secrets"],rules:s?[{minimumSeverity:"critical",action:"block"},{minimumSeverity:"high",action:"block"},{minimumSeverity:"medium",action:"warn"},{minimumSeverity:"low",action:"record"}]:[{minimumSeverity:"critical",action:"warn"},{minimumSeverity:"high",action:"warn"},{minimumSeverity:"low",action:"record"}],actorId:t}))}return n}function I$(e,t,r,n={}){let i=r.findings.map((o)=>({...t,ruleId:o.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:o.pattern.severity,title:o.pattern.name,description:o.pattern.description,subject:`${o.file}:${o.line}`,evidence:{file:o.file,line:o.line,column:o.column,match:o.match,context:o.context},remediation:"Remove and rotate the credential, then reference it through a managed secret or environment variable."}));return e.recordScan({...t,scannerId:"source-secrets",scannerVersion:n.scannerVersion??"1.0.0",status:n.skipped?"skipped":r.passed?"passed":"failed",findings:n.skipped?[]:i,metadata:{scannedFiles:r.scannedFiles,durationMs:r.duration,summary:r.summary},durationMs:r.duration,error:n.skipped?"The operator explicitly skipped source-secret scanning.":void 0})}function C$(e,t,r="The operator explicitly skipped source-secret scanning."){return e.recordScan({...t,scannerId:"source-secrets",scannerVersion:"1.0.0",status:"skipped",findings:[],error:r})}function HC(e,t){let r=[],n=t.security;if(n?.firewall&&!["active","configured","ok"].includes(String(n.firewall.status)))r.push({...e,ruleId:"host-firewall-disabled",severity:"high",title:"Host firewall is not active",description:String(n.firewall.summary??"The host firewall did not report an active configuration."),subject:"host:firewall",evidence:{status:String(n.firewall.status??"unknown"),rules:Array.isArray(n.firewall.rules)?n.firewall.rules.length:0},remediation:"Apply the declarative firewall policy and confirm only required listeners are public."});for(let i of n?.ports??[]){let o=String(i.listen??""),s=Number(o.match(/:(\d+)$/)?.[1]);if(i.exposure==="public"&&Number.isFinite(s)&&![22,80,443].includes(s))r.push({...e,ruleId:"unexpected-public-listener",severity:"medium",title:`Unexpected public listener on port ${s}`,description:`${String(i.processName??"A process")} is listening publicly outside the standard SSH/HTTP/HTTPS ports.`,subject:`host:port:${s}`,evidence:{protocol:String(i.proto??""),listen:o,process:String(i.processName??"")},remediation:"Bind the service to loopback/private networking or explicitly document and firewall the required public port."})}for(let i of n?.tlsCertificates??[]){let o=Number(i.daysRemaining);if(Number.isFinite(o)&&o<30)r.push({...e,ruleId:"tls-certificate-expiry",severity:o<14?"high":"medium",title:`TLS certificate expires in ${o} days`,description:`${String(i.domain??"A configured domain")} needs renewal.`,subject:`tls:${String(i.domain??"unknown")}`,evidence:{domain:String(i.domain??""),daysRemaining:o,expires:String(i.expires??"")},remediation:"Renew the certificate and verify automatic renewal can complete before expiry."})}for(let i of t.diagnostics??[]){if(i.status==="pass"||i.status==="ok")continue;r.push({...e,ruleId:`diagnostic-${String(i.name??"unknown").toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,severity:i.status==="fail"?"high":"medium",title:String(i.name??"Host security check"),description:String(i.detail??"The host security diagnostic did not pass."),subject:`diagnostic:${String(i.name??"unknown")}`,evidence:{status:String(i.status??"unknown")},remediation:"Follow the diagnostic guidance, rerun the check, and confirm the finding resolves."})}return r}function Gs(e,t,r){let n=!!r.security||Array.isArray(r.diagnostics),i=n?HC(t,r):[];return e.recordScan({...t,scannerId:"host-posture",scannerVersion:"1.0.0",status:!n?"unavailable":i.length?"failed":"passed",findings:i,metadata:{source:"dashboard-live-probe",checks:Array.isArray(r.diagnostics)?r.diagnostics.length:0},error:n?void 0:"Live host posture data was unavailable; source and provider checks remain usable."})}function Ks(e,t){let r=e.evaluateGate({...t.scope,operationId:t.operationId}),n=e.listFindings({...t.scope,limit:1000}).filter((i)=>i.status!=="resolved");return{decision:r,summary:{desiredConfigHash:t.desiredConfigHash??null,securityImpact:{critical:n.filter((i)=>i.severity==="critical").length,high:n.filter((i)=>i.severity==="high").length,waived:n.filter((i)=>i.status==="waived").length,assigned:n.filter((i)=>!!i.ownerActorId).length},blockingFindingIds:r.findingIds,policy:{id:r.policyId,version:r.policyVersion},scannerVersions:r.scannerVersions}}}async function k$(e,t){let r=t.scanner??new ou({timeoutMs:t.scannerTimeoutMs}),i=await new xn(e,{defaultTimeoutMs:t.scannerTimeoutMs??120000}).run(r,{...t.scope,releaseId:t.releaseId,imageRef:t.imageRef}),o={...t.scope,releaseId:t.releaseId};kf(e,o,i.findings);let s=t.generateImageSbom??Af,c=new AbortController,u=Math.max(100,t.sbomTimeoutMs??120000),a,p=new Promise((b,C)=>{a=setTimeout(()=>{c.abort(),C(Error(`syft-sbom exceeded its ${u}ms timeout`))},u)}),f="unavailable";try{let b=await Promise.race([s(t.imageRef,{signal:c.signal}),p]);su(e,o,b),e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"passed",metadata:{imageRef:t.imageRef,format:`cyclonedx-${b.specVersion}+json`,components:b.components.length,localOnly:!0}}),f="image"}catch(b){let C=b instanceof Error?b.message:String(b);try{let T=Tf(t.artifactRoot);su(e,o,T),e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unsupported",error:`Image inventory was unavailable; attached a package-manifest SBOM instead. ${C}`,metadata:{imageRef:t.imageRef,fallback:"package-manifest",components:T.components.length,localOnly:!0}}),f="manifest"}catch(T){e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unavailable",error:`Image and manifest SBOM generation were unavailable. ${C}; ${T instanceof Error?T.message:String(T)}`,metadata:{imageRef:t.imageRef,localOnly:!0}})}}finally{if(a)clearTimeout(a)}let y=Rf({artifactName:t.imageRef,artifact:t.imageSha256?void 0:t.imageRef,artifactSha256:t.imageSha256,invocationId:t.invocationId,startedAt:t.startedAt,completedAt:t.completedAt??new Date().toISOString(),externalParameters:t.externalParameters??{imageRef:t.imageRef}});return Pf(e,o,y),{scan:i,sbomSource:f}}import{randomBytes as Df,scryptSync as Of,timingSafeEqual as GC}from"node:crypto";function uu(e,t){if(e.role==="admin")return[...t];return t.filter((r)=>!!e.sites?.[r])}var au=32768,cu=8,du=1,KC=32,QC=16;function en(e){let t=Df(QC),r=Of(e,t,KC,{N:au,r:cu,p:du,maxmem:268435456});return`scrypt$${au}$${cu}$${du}$${t.toString("base64url")}$${r.toString("base64url")}`}function Qt(e,t){try{let r=t.split("$");if(r.length!==6||r[0]!=="scrypt")return!1;let[,n,i,o,s,c]=r,u=Number(n),a=Number(i),p=Number(o);if(!Number.isFinite(u)||!Number.isFinite(a)||!Number.isFinite(p))return!1;let f=Buffer.from(s,"base64url"),y=Buffer.from(c,"base64url");if(f.length===0||y.length===0)return!1;let b=Of(e,f,y.length,{N:u,r:a,p,maxmem:268435456});return GC(b,y)}catch{return!1}}function _f(e){let[t,r,n,i]=e.split("$");return t!=="scrypt"||Number(r)!==au||Number(n)!==cu||Number(i)!==du}function lu(){return Df(18).toString("base64url")}import{createHash as YC}from"node:crypto";function XC(e){return YC("sha256").update(Dn(e)).digest("hex")}function Dn(e){if(Array.isArray(e))return`[${e.map((t)=>Dn(t)).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,t])=>t!==void 0&&typeof t!=="function").sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Dn(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function He(e,t){let r=`dashboard:${t.username.toLowerCase()}`;return e.getActorByExternalId("user",r)??e.createActor({kind:"user",externalId:r,displayName:t.name??t.username,metadata:{source:"dashboard",role:t.role}})}function Lf(e,t){let r=new Mf({cwd:e}),n=XC(t),i=r.getProjectBySlug(t.project.slug),o=t.project.slug.length>=3?t.project.slug:`${t.project.slug}-org`,s=(i?.organizationId?r.getOrganization(i.organizationId):void 0)??r.getOrganizationBySlug(o)??r.createOrganization({id:i?.organizationId,slug:o,name:t.project.name}),c=i?i.name!==t.project.name||i.desiredConfigHash!==n||i.organizationId!==s.id?r.updateProject(i.id,i.version,{name:t.project.name,organizationId:s.id,desiredConfigHash:n}):i:r.createProject({organizationId:s.id,slug:t.project.slug,name:t.project.name,desiredConfigHash:n}),u=new Map;for(let[y,b]of Object.entries(t.environments??{})){let T=r.getEnvironmentBySlug(c.id,y)??r.createEnvironment({projectId:c.id,slug:y,name:y.replace(/(^|[-_])(\w)/g,(G,ae,Z)=>Z.toUpperCase()),kind:String(b?.type??y),region:b?.region??t.project.region,desiredState:$e(b)});u.set(y,T);let R=new Map(r.listResources(c.id,T.id).map((G)=>[`${G.kind}:${G.slug}`,G])),x=(G,ae,Z,Le)=>{let ue=`${G}:${ae}`,W=R.get(ue),ie=$e(Le);if(W){if(W.name!==Z||Dn(W.desiredState)!==Dn(ie))R.set(ue,r.updateResource(W.id,W.version,{name:Z,desiredState:ie}));return}let Ce=r.createResource({projectId:c.id,environmentId:T.id,kind:G,slug:ae,name:Z,provider:t.cloud?.provider,desiredState:ie,metadata:{source:"cloud-config"}});R.set(ue,Ce)};for(let[G,ae]of Object.entries(t.sites??{}))x("application",G,G,ae);let L=b?.app;if(L)for(let G of["http","queue","cli"])x("function",G,`${G.toUpperCase()} function`,{...$e(L),function:G});let P=t.infrastructure;for(let[G,ae]of Object.entries(P?.functions??{}))x("function",G,G,ae);if(P?.compute)x("server",`${c.slug}-server`,c.name,{...$e(P.compute),label:c.name});for(let[G,ae]of Object.entries(P?.databases??{}))x("database",G,G,ae);if(P?.appDatabase)x("database","application-database","Application database",P.appDatabase);else if(P?.database)x("database","application-database","Application database",{engine:P.database})}let a=new xe(r).recoverExpired(),p=r.reconcileOrphanedOperations({policy:"fail"}),f={requeued:a.requeued+p.requeued,failed:a.failed+a.cancelled+p.failed};return{store:r,organization:s,project:c,environments:u,reconciliation:f}}var ZC=["project:read","config:read","deployments:read","deployments:create","runtime:read","runtime:logs"];function Qs(e,t){let{store:r,organization:n,project:i}=e,o=new Set;for(let s of t){let c=He(r,s);o.add(c.id);let u=r.getMembershipForActor(n.id,c.id);if(u&&u.source!=="legacy")continue;let a=r.listResources(i.id).filter((C)=>C.kind==="application"&&Object.hasOwn(s.sites,C.slug)),p=s.role==="admin"?"owner":"viewer",f=s.role==="admin"||a.length===0?{type:"organization"}:{type:"resource",id:a[0].id},y=u?u.roleTemplate!==p||Dn(u.scope)!==Dn(f)?r.updateMembership({id:u.id,roleTemplate:p,scope:f,actorId:c.id}):u:r.createMembership({organizationId:n.id,actorId:c.id,roleTemplate:p,scope:f,source:"legacy"}),b=new Set;if(s.role==="member"&&a.length===0)for(let C of $f("viewer"))b.add(`deny|${C}|organization|`);for(let C of a){let T=s.sites[C.slug];for(let R of ZC)b.add(`allow|${R}|resource|${C.id}`);if(T==="owner")b.add(`allow|config:write|resource|${C.id}`)}for(let C of r.listGrants(y.id).filter((T)=>T.source==="legacy")){let T=`${C.effect}|${C.capability}|${C.scope.type}|${C.scope.id??""}`;if(!b.has(T))r.removeGrant(C.id,c.id)}for(let C of b){let[T,R,x,L]=C.split("|");r.upsertGrant({organizationId:n.id,membershipId:y.id,effect:T,capability:R,scope:x==="organization"?{type:"organization"}:{type:x,id:L},source:"legacy"})}}for(let s of r.listMemberships(n.id))if(s.source==="legacy"&&!o.has(s.actorId))r.revokeMembership(s.id)}async function Dr(e){let{controlPlane:t,environment:r,actor:n}=e,i=He(t.store,n),o=t.environments.get(r),s=e.resourceSlug&&o?t.store.listResources(t.project.id,o.id).find((p)=>p.slug===e.resourceSlug):void 0,c=new xe(t.store,{workerId:`dashboard:${process.pid}`}),u=c.enqueue({projectId:t.project.id,environmentId:o?.id,resourceId:s?.id,actorId:i.id,kind:e.kind,input:e.input??{},lockKey:s?`resource:${s.id}`:o?`environment:${o.id}`:`project:${t.project.id}`,providerKey:s?.provider??"dashboard",buildSlot:e.kind.includes("deploy"),maxAttempts:1,timeoutSeconds:3600,resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;if(!c.claim(u.id)?.operation)throw Error(`Could not claim control-plane operation ${u.id}`);try{let p=await e.execute(),f=typeof p.stdout==="string"?String(p.stdout):"",y=typeof p.stderr==="string"?String(p.stderr):"";if(f)c.appendLog(u.id,f,{stream:"stdout"});if(y)c.appendLog(u.id,y,{stream:"stderr"});let b=p.ok?c.complete(u.id,Nf(p)):c.fail(u.id,eE(p),Nf(p));return{result:p,operation:b}}catch(p){throw c.fail(u.id,p instanceof Error?p.message:String(p),{ok:!1,threw:!0}),p}}function eE(e){let t=e;return String(t.error??t.stderr??"Operation failed")}function Nf(e){let t=e,r=typeof t.stdout==="string"?t.stdout:"",n=typeof t.stderr==="string"?t.stderr:"",i={ok:e.ok,stdoutBytes:Buffer.byteLength(r),stderrBytes:Buffer.byteLength(n)};if(typeof t.operation==="string")i.operation=t.operation;if(typeof t.error==="string")i.error=t.error;return $e(i)}var tE=new Set(["singlestore","vitess"]);function Zs(e){return tE.has(e)}var Xs={mysql:"/var/lib/pantry/mysql/mysqld.sock",mariadb:"/var/lib/pantry/mariadb/mariadbd.sock"};function Or(e){return/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e)}function rE(e){if(e==="postgres"||e==="pgsql")return"postgres";if(e==="mariadb")return"mariadb";if(e==="singlestore")return"singlestore";if(e==="vitess")return"vitess";return"mysql"}function _n(e){let t=e.infrastructure?.compute,r=it(e)?.engine;if(r)return rE(r);let n=t?.managedServices??{};if(n.postgres)return"postgres";if(n.mariadb)return"mariadb";return"mysql"}var pu=(e)=>e.replace(/`/g,"``"),dr=(e)=>e.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),On=(e)=>`"${e.replace(/"/g,'""')}"`,Ys=(e)=>`'${e.replace(/'/g,"''")}'`;function mu(e,t){return[`mysql --socket=${e==="mariadb"?Xs.mariadb:Xs.mysql} -u root <<'TS_CLOUD_SQL_EOF'`,...t,"TS_CLOUD_SQL_EOF"]}function fu(e,t){return[`${gu(t)} -tA <<'TS_CLOUD_PG_EOF'`,...e,"TS_CLOUD_PG_EOF"]}function nE(e,t){if(e==="vitess")return iE(t);if(e==="postgres")return fu(["SELECT 'DB=' || datname FROM pg_database WHERE datistemplate = false;","SELECT 'USER=' || usename FROM pg_user;"],t);return mu(e,["SELECT CONCAT('DB=', schema_name) FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys');","SELECT DISTINCT CONCAT('USER=', User) FROM mysql.user WHERE User NOT IN ('root', 'mysql.sys', 'mysql.session', 'mysql.infoschema', 'debian-sys-maint');"])}function hi(e,t,r){let n=t?.host??"127.0.0.1",i=t?.username??"root",o=t?.password??"",s=t?.ssl===!1?"":" --ssl-mode=PREFERRED",c=(a)=>`'${String(a).replace(/'/g,"'\\''")}'`;return[`${o?`MYSQL_PWD=${c(o)} `:""}mysql -h ${c(n)} -P ${t?.port??r} -u ${c(i)}${s} --batch --skip-column-names <<'TS_CLOUD_SQL_EOF'`,...e,"TS_CLOUD_SQL_EOF"]}var yi=15306;function iE(e){let t=hi(["SHOW KEYSPACES;"],e,yi);return t[0]=`${t[0]} | sed 's/^/DB=/'`,t}function oE(e){return hi(["SHOW KEYSPACES;","SHOW VITESS_SHARDS;","SHOW VITESS_TABLETS;"],e,yi)}function sE(e){let t=[],r=[],n=[];for(let i of e.split(`
|
|
146
|
-
`)){let o=i.trim();if(!o)continue;let s=o.split("\t").map((c)=>c.trim()).filter(Boolean);if(s.length>=6){let[c,u,a,p,f,y,b]=s;n.push({cell:c??"",keyspace:u??"",shard:a??"",type:p??"",state:f??"",alias:y??"",hostname:b??""});continue}if(s.length===1){let c=s[0];if(c.includes("/")){let[u,a]=c.split("/");if(u&&a)r.push({keyspace:u,shard:a})}else t.push(c)}}return{keyspaces:[...new Set(t)].filter(Boolean).sort(),shards:r,tablets:n}}function aE(e,t,r){if(e==="postgres")return fu([`SELECT 'CREATE DATABASE ${On(t)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${Ys(t)})\\gexec`],r);return mu(e,[`CREATE DATABASE IF NOT EXISTS \`${pu(t)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`])}function cE(e,t,r){let{username:n,password:i,database:o,access:s}=t;if(e==="postgres"){let a=["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${Ys(n)}) THEN CREATE ROLE ${On(n)} LOGIN PASSWORD ${Ys(i)};`,` ELSE ALTER ROLE ${On(n)} LOGIN PASSWORD ${Ys(i)}; END IF;`,"END $$;"];if(o)a.push(s==="readonly"?`GRANT CONNECT ON DATABASE ${On(o)} TO ${On(n)};`:`GRANT ALL PRIVILEGES ON DATABASE ${On(o)} TO ${On(n)};`);return fu(a,r)}let c=s==="readonly"?"SELECT":"ALL PRIVILEGES",u=[`CREATE USER IF NOT EXISTS '${dr(n)}'@'%' IDENTIFIED BY '${dr(i)}';`,`CREATE USER IF NOT EXISTS '${dr(n)}'@'localhost' IDENTIFIED BY '${dr(i)}';`,`ALTER USER '${dr(n)}'@'%' IDENTIFIED BY '${dr(i)}';`,`ALTER USER '${dr(n)}'@'localhost' IDENTIFIED BY '${dr(i)}';`];if(o)u.push(`GRANT ${c} ON \`${pu(o)}\`.* TO '${dr(n)}'@'%';`,`GRANT ${c} ON \`${pu(o)}\`.* TO '${dr(n)}'@'localhost';`);return u.push("FLUSH PRIVILEGES;"),mu(e,u)}function dE(e){let t=[],r=[];for(let n of e.split(`
|
|
147
|
-
`)){let i=n.trim();if(i.startsWith("DB="))t.push(i.slice(3));else if(i.startsWith("USER="))r.push(i.slice(5))}return{databases:[...new Set(t)].filter(Boolean).sort(),users:[...new Set(r)].filter(Boolean).sort()}}async function St(e,t,r,n){let i;try{i=xr({config:e})}catch(u){return{ok:!1,error:`Could not initialize the cloud driver: ${u?.message??u}`}}let o=e.project.slug,s=await i.findComputeTargets({slug:o,environment:t,role:"app"});if(!s.length)return{ok:!1,error:"No app server target was found for this environment."};let c=await i.runRemoteDeploy({targets:[s[0]],commands:["set -uo pipefail",...r],comment:n,tags:{Project:o,Environment:t,Role:"app"}});return{ok:c.success,stdout:c.perInstance?.[0]?.output??"",stderr:c.perInstance?.[0]?.error??c.error??""}}function ea(e,t){return{ok:!1,error:`${t} is not available for ${e}: it is an external cluster, so this box has no engine to administer. ${e==="vitess"?"Create a keyspace with `vtctldclient CreateKeyspace`, and manage vtgate credentials on the cluster.":"Use the provider console or the cluster's own admin connection."}`}}async function Bf(e,t){let r=_n(e);if(Zs(r)&&r!=="vitess")return{...ea(r,"Listing databases"),engine:r,databases:[],users:[]};let n=await St(e,t,nE(r,it(e)),"ts-cloud db:list"),i=n.ok&&n.stdout?dE(n.stdout):{databases:[],users:[]};return{...n,engine:r,...i}}async function jf(e,t,r){let n=_n(e);if(Zs(n))return ea(n,"Creating a database");return St(e,t,aE(n,r,it(e)),`ts-cloud db:create ${r}`)}async function Ff(e,t,r){let n=_n(e);if(Zs(n))return ea(n,"Creating a database user");return St(e,t,cE(n,r,it(e)),`ts-cloud db:user ${r.username}`)}var hu="/var/backups/ts-cloud/databases";function uE(e,t,r=hu,n){let o=`${r}/${t}-$TS_CLOUD_BACKUP_STAMP.sql.gz`,s=`mkdir -p ${r}`;if(e==="postgres")return[s,'TS_CLOUD_BACKUP_STAMP="$(date +%Y%m%d-%H%M%S)"',`${gu(n,"pg_dump")} ${t} | gzip > "${o}"`,`echo "BACKUP=${o}"`,`ls -l "${o}"`];let c=e==="mariadb"?Xs.mariadb:Xs.mysql;return[s,'TS_CLOUD_BACKUP_STAMP="$(date +%Y%m%d-%H%M%S)"',`mysqldump --socket=${c} -u root ${t} | gzip > "${o}"`,`echo "BACKUP=${o}"`,`ls -l "${o}"`]}function lE(e=hu){return[`ls -1t ${e}/*.sql.gz 2>/dev/null | head -50 | sed 's|^|BACKUP=|' || true`]}function pE(e){let t=[];for(let r of e.split(`
|
|
148
|
-
`)){let n=r.trim();if(!n.startsWith("BACKUP="))continue;let i=n.slice(7),s=(i.split("/").pop()??i).replace(/-\d{8}-\d{6}\.sql\.gz$/,"");if(i)t.push({file:i,database:s})}return t}async function Uf(e,t,r){if(!Or(r))return{ok:!1,error:"Database name must be a valid identifier.",database:r};let n=_n(e);if(Zs(n))return{...ea(n,"Backing up"),database:r};return{...await St(e,t,uE(n,r,hu,it(e)),`ts-cloud db:backup ${r}`),database:r}}async function zf(e,t){let r=await St(e,t,lE(),"ts-cloud db:backups"),n=r.ok&&r.stdout?pE(r.stdout):[];return{...r,backups:n}}async function Vf(e,t){let r=_n(e),n={keyspaces:[],shards:[],tablets:[]};if(r!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess.",engine:r,...n};let i=await St(e,t,oE(it(e)),"ts-cloud vitess:topology"),o=i.ok&&i.stdout?sE(i.stdout):n;return{...i,engine:r,...o}}function qf(e){return e.filter((t)=>t.state.toUpperCase()!=="SERVING")}function Jf(e){let t=new Set(e.tablets.filter((r)=>r.type.toUpperCase()==="PRIMARY"&&r.state.toUpperCase()==="SERVING").map((r)=>`${r.keyspace}/${r.shard}`));return e.shards.filter((r)=>!t.has(`${r.keyspace}/${r.shard}`))}var yu="/usr/local/bin/vtctldclient",gE="21.0.0";function ra(e){return`'${String(e).split("'").join("'\\''")}'`}function na(e){return it(e)?.vitess??{}}function Wf(e){return/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(e)}function mE(e){return/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/i.test(e)}function fE(e=gE){let t=ra(e);return[`if ${yu} --version 2>/dev/null | grep -q ${t}; then echo "vtctldclient ${e} already installed"; else`," command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)",' if [ "$(uname -m)" != "x86_64" ]; then',' echo "vtctldclient: Vitess publishes only an x86_64 release tarball; this box is $(uname -m). Build from source or install via pantry." >&2'," exit 1"," fi",' tmp="$(mktemp -d)"',` api="https://api.github.com/repos/vitessio/vitess/releases/tags/v${e}"`,` url="$(curl -fsSL "$api" | grep -oE '"browser_download_url"[[:space:]]*:[[:space:]]*"[^"]+vitess-[0-9][^"]*\\.tar\\.gz"' | head -1 | sed -E 's/.*"(https[^"]+)"/\\1/')"`,' if [ -z "$url" ]; then echo "vtctldclient: no release tarball found for v'+e+'" >&2; rm -rf "$tmp"; exit 1; fi',` curl -fsSL "$url" | tar -xz -C "$tmp" --strip-components=2 --wildcards --occurrence=1 '*/bin/vtctldclient' || true`,' if [ ! -s "$tmp/vtctldclient" ]; then',' echo "vtctldclient: could not extract the binary from $url" >&2',' rm -rf "$tmp"; exit 1'," fi",` install -m 0755 "$tmp/vtctldclient" ${yu}`,' rm -rf "$tmp"',` echo "installed vtctldclient ${e}"`,"fi"]}function Hf(e){if(!e.vtctldAddr)return null;return`${yu} --server ${ra(e.vtctldAddr)}`}function hE(e,t,r={}){let n=Hf(e);if(!n)return null;let i=r.sharded?" --sharded":"";return[`${n} CreateKeyspace${i} ${ra(t)}`]}function yE(e,t,r){let n=Hf(e);if(!n)return null;return['vschema_tmp="$(mktemp)"',`cat > "$vschema_tmp" <<'TS_CLOUD_VSCHEMA_EOF'`,r,"TS_CLOUD_VSCHEMA_EOF",`${n} ApplyVSchema --vschema-file "$vschema_tmp" ${ra(t)}`,'rm -f "$vschema_tmp"']}function bE(e,t,r="vitess"){return hi([`SET @@ddl_strategy='${r}';`,t.endsWith(";")?t:`${t};`],e,yi)}function SE(e,t){let r=t?[`USE ${t.replace(/[^A-Z0-9_]/gi,"")};`,"SHOW VITESS_MIGRATIONS;"]:["SHOW VITESS_MIGRATIONS;"],n=hi(r,e,yi);return n[0]=n[0].replace(" --skip-column-names",""),n}function vE(e){let t=e.split(`
|
|
149
|
-
`).map((s)=>s.trimEnd()).filter((s)=>s.trim().length>0);if(t.length===0)return[];let r=t[0].split("\t").map((s)=>s.trim()),n=(s)=>r.indexOf(s),i={uuid:n("migration_uuid"),keyspace:n("keyspace"),shard:n("shard"),table:n("mysql_table"),status:n("migration_status"),strategy:n("strategy"),added:n("added_timestamp"),completed:n("completed_timestamp"),progress:n("progress")};if(i.uuid===-1)return[];let o=[];for(let s of t.slice(1)){let c=s.split("\t"),u=(p)=>p>=0?(c[p]??"").trim():"",a=u(i.uuid);if(!a)continue;o.push({uuid:a,keyspace:u(i.keyspace),shard:u(i.shard),table:u(i.table),status:u(i.status),strategy:u(i.strategy),added:u(i.added),completed:u(i.completed),progress:u(i.progress)})}return o}function wE(e){return e.filter((t)=>t.status.toLowerCase()==="failed")}function IE(e){return e.filter((t)=>["running","queued","ready"].includes(t.status.toLowerCase()))}function CE(e,t,r){let n=r.toUpperCase();return hi([`ALTER VITESS_MIGRATION '${t}' ${n};`],e,yi)}function bi(e){if(_n(e)!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess."};return null}function ta(e){if(!e.vtctldAddr)return{ok:!1,error:"No vtctld address is configured. Creating keyspaces and applying a VSchema are topology operations that vtgate cannot perform. Set `infrastructure.appDatabase.vitess.vtctldAddr` (for example `vtctld.internal:15999`) and redeploy."};return null}async function Gf(e,t){let r=bi(e);if(r)return r;let n=na(e);return St(e,t,fE(n.clientVersion),"ts-cloud vitess:install-client")}async function Kf(e,t,r,n={}){let i=bi(e);if(i)return{...i,keyspace:r};if(!Wf(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};let o=na(e),s=ta(o);if(s)return{...s,keyspace:r};let c=hE(o,r,n);if(!c)return{...ta({}),keyspace:r};return{...await St(e,t,c,`ts-cloud vitess:create-keyspace ${r}`),keyspace:r}}async function Qf(e,t,r,n){let i=bi(e);if(i)return{...i,keyspace:r};if(!Wf(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};try{let a=JSON.parse(n);if(!a||typeof a!=="object")return{ok:!1,error:"The VSchema must be a JSON object.",keyspace:r}}catch(a){return{ok:!1,error:`The VSchema is not valid JSON: ${a?.message??a}`,keyspace:r}}let o=na(e),s=ta(o);if(s)return{...s,keyspace:r};let c=yE(o,r,n);if(!c)return{...ta({}),keyspace:r};return{...await St(e,t,c,`ts-cloud vitess:apply-vschema ${r}`),keyspace:r}}async function Yf(e,t,r){let n=bi(e);if(n)return n;if(!r.trim())return{ok:!1,error:"No SQL was provided."};let i=na(e);return St(e,t,bE(it(e),r,i.ddlStrategy??"vitess"),"ts-cloud vitess:apply-schema")}async function Xf(e,t,r){let n=bi(e);if(n)return{...n,migrations:[],failed:[],running:[]};let i=await St(e,t,SE(it(e),r),"ts-cloud vitess:migrations"),o=i.ok&&i.stdout?vE(i.stdout):[];return{...i,migrations:o,failed:wE(o),running:IE(o)}}async function Zf(e,t,r,n){let i=bi(e);if(i)return{...i,uuid:r};if(!mE(r))return{ok:!1,error:"Migration UUID is not in the expected format.",uuid:r};return{...await St(e,t,CE(it(e),r,n),`ts-cloud vitess:migration ${n} ${r}`),uuid:r}}function EE(e){let t=e.infrastructure?.appDatabase;if(t?.engine&&t.engine!=="vitess")return`This project already declares ${t.engine} as its application database.`;let r=e.infrastructure?.compute?.managedServices,n=r?["mysql","mariadb","postgres"].find((i)=>Boolean(r[i])):void 0;if(n)return`This server already declares the ${n} database service.`;return}function TE(e,t){let r=t.keyspace.trim(),n=t.username.trim(),i=t.password,o=EE(e);if(o)throw Error(o);if(!Or(r))throw Error("Keyspace must contain letters, numbers, or underscores and cannot start with a number.");if(!Or(n))throw Error("Username must contain letters, numbers, or underscores and cannot start with a number.");if(i.length<16)throw Error("Password must contain at least 16 characters.");if(t.confirm!==r)throw Error(`Type "${r}" to confirm Vitess provisioning.`);let s={mode:"cluster",cell:"zone1",keyspaces:[{name:r,sharded:t.sharded===!0}],vtgatePort:15306,username:n,password:i,bindAddress:"127.0.0.1"};return{service:s,appDatabase:{engine:"vitess",name:r,username:n,host:"127.0.0.1",port:15306,ssl:!1},commands:[...eh(),...th(s)]}}async function rh(e,t,r){let n=TE(e,r);return{...await St(e,t,n.commands,`ts-cloud vitess:provision ${n.appDatabase.name}`),database:n.appDatabase,service:Object.fromEntries(Object.entries(n.service).filter(([o])=>o!=="password"))}}var AE={capability:"runtime:terminal",scope:"organization"};var kE={"GET /api/health":{capability:"project:read",anyUser:!0},"GET /api/dashboard-data":{capability:"project:read",anyUser:!0},"GET /api/config":{capability:"config:read",anyUser:!0},"GET /api/me":{capability:"project:read",anyUser:!0},"GET /api/search":{capability:"project:read",anyUser:!0},"GET /api/search/preferences":{capability:"project:read",anyUser:!0},"POST /api/search/preferences":{capability:"project:read",anyUser:!0},"DELETE /api/search/preferences":{capability:"project:read",anyUser:!0},"GET /api/auth/security":{capability:"project:read",anyUser:!0},"GET /api/auth/sessions":{capability:"project:read",anyUser:!0},"DELETE /api/auth/sessions":{capability:"project:read",anyUser:!0},"POST /api/auth/sessions/revoke-others":{capability:"project:read",anyUser:!0},"POST /api/auth/password/change":{capability:"project:read",anyUser:!0},"POST /api/auth/mfa/enroll":{capability:"project:read",anyUser:!0},"POST /api/auth/mfa/verify":{capability:"project:read",anyUser:!0},"DELETE /api/auth/mfa":{capability:"project:read",anyUser:!0},"POST /api/auth/step-up":{capability:"project:read",anyUser:!0},"GET /api/auth/oidc/providers":{capability:"users:read",scope:"organization"},"POST /api/auth/oidc/providers":{capability:"users:manage",scope:"organization"},"PATCH /api/auth/oidc/providers":{capability:"users:manage",scope:"organization"},"GET /api/automation":{capability:"users:read",scope:"organization"},"POST /api/automation/service-accounts":{capability:"users:manage",scope:"organization"},"PATCH /api/automation/service-accounts":{capability:"users:manage",scope:"organization"},"POST /api/automation/tokens":{capability:"users:manage",scope:"organization"},"POST /api/automation/tokens/rotate":{capability:"users:manage",scope:"organization"},"DELETE /api/automation/tokens":{capability:"users:manage",scope:"organization"},"GET /api/security/posture":{capability:"security:read"},"GET /api/security/export":{capability:"security:read"},"POST /api/security/scan":{capability:"security:manage"},"POST /api/security/review":{capability:"deployments:create"},"POST /api/security/policies":{capability:"security:manage"},"PATCH /api/security/policies":{capability:"security:manage"},"POST /api/security/waivers":{capability:"security:waive"},"DELETE /api/security/waivers":{capability:"security:waive"},"PATCH /api/security/findings":{capability:"security:manage"},"POST /api/security/comments":{capability:"security:manage"},"GET /api/sources":{capability:"sources:read"},"POST /api/sources/connections":{capability:"sources:manage"},"PATCH /api/sources/connections":{capability:"sources:manage"},"DELETE /api/sources/connections":{capability:"sources:manage"},"POST /api/sources/deploy-keys":{capability:"sources:manage"},"DELETE /api/sources/deploy-keys":{capability:"sources:manage"},"POST /api/sources/repositories/sync":{capability:"sources:manage"},"GET /api/sources/references":{capability:"sources:read"},"POST /api/sources/bindings":{capability:"sources:manage"},"PATCH /api/sources/bindings":{capability:"sources:manage"},"POST /api/sources/webhooks":{capability:"sources:manage"},"PATCH /api/sources/webhooks":{capability:"sources:manage"},"DELETE /api/sources/webhooks":{capability:"sources:manage"},"GET /api/onboarding":{capability:"applications:read"},"POST /api/onboarding/detect":{capability:"applications:manage"},"POST /api/onboarding/plan":{capability:"applications:manage"},"POST /api/onboarding/drafts":{capability:"applications:manage"},"PATCH /api/onboarding/drafts":{capability:"applications:manage"},"POST /api/onboarding/artifacts":{capability:"applications:manage"},"POST /api/onboarding/registries":{capability:"applications:manage"},"PATCH /api/onboarding/registries":{capability:"applications:manage"},"DELETE /api/onboarding/registries":{capability:"applications:manage"},"POST /api/onboarding/apply":{capability:"applications:manage"},"GET /api/compose":{capability:"applications:read",anyUser:!0},"POST /api/compose/preview":{capability:"applications:manage",anyUser:!0},"POST /api/compose/import":{capability:"applications:manage",anyUser:!0},"POST /api/compose/template":{capability:"applications:manage",anyUser:!0},"POST /api/compose/action":{capability:"project:read",anyUser:!0},"POST /api/compose/logs":{capability:"runtime:logs",anyUser:!0},"POST /api/compose/shell":{capability:"runtime:terminal",scope:"organization"},"GET /api/compose/import":{capability:"applications:manage"},"GET /api/compose/template":{capability:"applications:manage"},"GET /api/compose/logs":{capability:"runtime:logs"},"GET /api/compose/shell":{capability:"runtime:terminal",scope:"organization"},"GET /api/organization":{capability:"users:read",scope:"organization"},"GET /api/organization/invitations":{capability:"users:read",scope:"organization"},"POST /api/organization/invitations":{capability:"users:manage",scope:"organization"},"DELETE /api/organization/invitations":{capability:"users:manage",scope:"organization"},"POST /api/organization/invitations/resend":{capability:"users:manage",scope:"organization"},"PATCH /api/organization/memberships":{capability:"users:manage",scope:"organization"},"DELETE /api/organization/memberships":{capability:"users:manage",scope:"organization"},"POST /api/organization/grants":{capability:"users:manage",scope:"organization"},"DELETE /api/organization/grants":{capability:"users:manage",scope:"organization"},"GET /api/control-plane/operations":{capability:"deployments:read"},"GET /api/control-plane/events":{capability:"audit:read"},"GET /api/queue":{capability:"deployments:read",anyUser:!0},"GET /api/queue/logs":{capability:"deployments:read",anyUser:!0},"GET /api/queue/stream":{capability:"deployments:read",anyUser:!0},"POST /api/queue/cancel":{capability:"deployments:cancel",anyUser:!0},"POST /api/queue/retry":{capability:"deployments:create",anyUser:!0},"GET /api/queue/settings":{capability:"deployments:read"},"PATCH /api/queue/settings":{capability:"automation:manage",scope:"organization"},"DELETE /api/queue/history":{capability:"automation:manage",scope:"organization"},"GET /api/previews":{capability:"deployments:read",anyUser:!0},"GET /api/releases":{capability:"deployments:read",anyUser:!0},"POST /api/releases/action":{capability:"deployments:create",anyUser:!0},"POST /api/previews/deploy":{capability:"deployments:create",anyUser:!0},"POST /api/previews/destroy":{capability:"deployments:cancel",anyUser:!0},"POST /api/previews/extend":{capability:"deployments:create",anyUser:!0},"POST /api/previews/rebuild":{capability:"deployments:create",anyUser:!0},"POST /api/previews/definitions":{capability:"config:write",anyUser:!0},"POST /api/previews/cleanup":{capability:"automation:manage",scope:"organization"},"GET /api/tags":{capability:"project:read"},"POST /api/tags":{capability:"tags:manage"},"DELETE /api/tags":{capability:"tags:manage"},"POST /api/sites/deploy":{capability:"deployments:create",scope:"site",siteFrom:"body"},"PATCH /api/sites":{capability:"config:write",scope:"site",siteFrom:"body"},"POST /api/sites":{capability:"config:write"},"DELETE /api/sites":{capability:"config:write"},"POST /api/env":{capability:"config:write"},"GET /api/ssh-keys":{capability:"fleet:read"},"POST /api/ssh-keys":{capability:"fleet:manage"},"DELETE /api/ssh-keys":{capability:"fleet:manage"},"GET /api/firewall":{capability:"fleet:read"},"POST /api/firewall":{capability:"fleet:manage"},"DELETE /api/firewall":{capability:"fleet:manage"},"GET /api/databases":{capability:"data:read"},"POST /api/databases":{capability:"data:admin"},"GET /api/databases/vitess":{capability:"data:read"},"GET /api/databases/vitess/migrations":{capability:"data:read"},"POST /api/databases/vitess/migrations/action":{capability:"data:admin"},"POST /api/databases/vitess/provision":{capability:"runtime:terminal",scope:"organization"},"POST /api/databases/vitess/keyspaces":{capability:"data:admin"},"POST /api/databases/vitess/vschema":{capability:"data:admin"},"POST /api/databases/vitess/schema":{capability:"data:admin"},"POST /api/databases/vitess/install-client":{capability:"data:admin"},"GET /api/databases/backups":{capability:"backups:read"},"POST /api/databases/backup":{capability:"backups:create"},"POST /api/databases/users":{capability:"data:admin"},"GET /api/data-services":{capability:"data:read"},"GET /api/data-services/capabilities":{capability:"data:read"},"GET /api/data-services/connections":{capability:"data:read"},"POST /api/data-services/preview":{capability:"data:read"},"POST /api/data-services":{capability:"data:admin"},"POST /api/data-services/action":{capability:"data:admin"},"POST /api/data-services/dependencies":{capability:"data:admin"},"POST /api/data-services/management":{capability:"data:admin"},"POST /api/data-services/reveal":{capability:"data:admin"},"GET /api/backups":{capability:"backups:read"},"POST /api/backups/destinations":{capability:"backups:create"},"POST /api/backups/destinations/test":{capability:"backups:create"},"POST /api/backups/policies":{capability:"backups:create"},"POST /api/backups/run":{capability:"backups:create"},"POST /api/backups/verify":{capability:"backups:create"},"POST /api/backups/restore":{capability:"backups:restore"},"POST /api/backups/recovery-points":{capability:"backups:create"},"POST /api/backups/retention":{capability:"backups:create"},"GET /api/configuration":{capability:"config:read"},"GET /api/configuration/export":{capability:"config:read"},"POST /api/configuration/plan":{capability:"config:read"},"POST /api/configuration":{capability:"config:write"},"POST /api/configuration/import":{capability:"config:write"},"POST /api/configuration/dependencies":{capability:"config:write"},"POST /api/configuration/transfer":{capability:"config:write"},"POST /api/configuration/bulk":{capability:"config:write"},"POST /api/configuration/reveal":{capability:"secrets:read"},"DELETE /api/configuration":{capability:"config:write"},"GET /api/volumes":{capability:"data:read"},"POST /api/volumes":{capability:"data:admin"},"POST /api/volumes/attach":{capability:"data:admin"},"POST /api/volumes/detach":{capability:"data:admin"},"POST /api/volumes/resize":{capability:"data:admin"},"POST /api/volumes/snapshot":{capability:"backups:create"},"POST /api/volumes/restore":{capability:"backups:restore"},"POST /api/volumes/adopt":{capability:"data:admin"},"POST /api/volumes/discover":{capability:"data:read"},"DELETE /api/volumes":{capability:"data:admin"},"GET /api/fleet":{capability:"fleet:read"},"POST /api/fleet":{capability:"fleet:manage"},"POST /api/fleet/action":{capability:"fleet:manage"},"GET /api/capacity":{capability:"fleet:read"},"POST /api/capacity":{capability:"fleet:manage"},"POST /api/capacity/member":{capability:"fleet:manage"},"POST /api/capacity/explain":{capability:"fleet:read"},"POST /api/capacity/action":{capability:"fleet:manage"},"GET /api/regions":{capability:"config:read"},"POST /api/regions":{capability:"config:write"},"POST /api/regions/action":{capability:"config:write"},"GET /api/maintenance":{capability:"automation:read"},"POST /api/maintenance/cleanup-preview":{capability:"automation:manage"},"POST /api/maintenance/cleanup-apply":{capability:"automation:manage"},"POST /api/maintenance/drill":{capability:"automation:manage"},"POST /api/maintenance/drill-run":{capability:"automation:manage"},"GET /api/actions":{capability:"runtime:read"},"GET /api/runtime/workloads":{capability:"runtime:read"},"GET /api/runtime/logs":{capability:"runtime:logs"},"POST /api/runtime/log-sessions":{capability:"runtime:logs"},"GET /api/runtime/log-sessions":{capability:"runtime:logs"},"GET /api/runtime/log-stream":{capability:"runtime:logs"},"DELETE /api/runtime/log-sessions":{capability:"runtime:logs"},"POST /api/runtime/exec-sessions":{capability:"runtime:terminal",scope:"organization"},"GET /api/runtime/exec-sessions":{capability:"runtime:terminal",scope:"organization"},"GET /api/runtime/exec-stream":{capability:"runtime:terminal",scope:"organization"},"DELETE /api/runtime/exec-sessions":{capability:"runtime:terminal",scope:"organization"},"POST /api/runtime/files/read":{capability:"runtime:terminal",scope:"organization"},"POST /api/runtime/files/write":{capability:"runtime:terminal",scope:"organization"},"POST /api/runtime/operations":{capability:"runtime:restart"},"GET /api/telemetry/status":{capability:"runtime:read"},"GET /api/telemetry/settings":{capability:"runtime:read"},"PATCH /api/telemetry/settings":{capability:"config:write",scope:"organization"},"GET /api/telemetry/query":{capability:"runtime:logs"},"GET /api/telemetry/tail":{capability:"runtime:logs"},"GET /api/telemetry/series":{capability:"runtime:read"},"POST /api/telemetry/refresh":{capability:"runtime:logs"},"POST /api/telemetry/export":{capability:"runtime:logs"},"GET /api/telemetry/saved-queries":{capability:"runtime:logs"},"POST /api/telemetry/saved-queries":{capability:"runtime:logs"},"DELETE /api/telemetry/saved-queries":{capability:"runtime:logs"},"GET /api/health/checks":{capability:"runtime:read"},"POST /api/health/checks":{capability:"config:write"},"PATCH /api/health/checks":{capability:"config:write"},"POST /api/health/checks/test":{capability:"runtime:read"},"POST /api/health/checks/run":{capability:"runtime:restart"},"GET /api/protection":{capability:"security:read"},"POST /api/protection/attack-mode":{capability:"security:manage"},"POST /api/protection/pause":{capability:"security:manage"},"GET /api/protection/ip-rules":{capability:"security:read"},"POST /api/protection/ip-rules":{capability:"security:manage"},"DELETE /api/protection/ip-rules":{capability:"security:manage"},"GET /api/usage":{capability:"billing:read"},"GET /api/spend/budgets":{capability:"billing:read"},"POST /api/spend/budgets":{capability:"billing:manage"},"PATCH /api/spend/budgets":{capability:"billing:manage"},"DELETE /api/spend/budgets":{capability:"billing:manage"},"POST /api/spend/check":{capability:"billing:manage"},"GET /api/spend/enforcement":{capability:"billing:read"},"POST /api/spend/release":{capability:"billing:manage"},"GET /api/spend/anomalies":{capability:"billing:read"},"POST /api/spend/anomalies/acknowledge":{capability:"billing:manage"},"GET /api/alerts":{capability:"runtime:read"},"GET /api/alerts/rules":{capability:"runtime:read"},"POST /api/alerts/rules":{capability:"config:write"},"PATCH /api/alerts/rules":{capability:"config:write"},"POST /api/alerts/evaluate":{capability:"runtime:restart"},"POST /api/alerts/action":{capability:"runtime:restart"},"POST /api/alerts/silences":{capability:"config:write"},"GET /api/notifications/channels":{capability:"automation:read",scope:"organization"},"POST /api/notifications/channels":{capability:"automation:manage",scope:"organization"},"PATCH /api/notifications/channels":{capability:"automation:manage",scope:"organization"},"POST /api/notifications/channels/test":{capability:"automation:manage",scope:"organization"},"GET /api/notifications/routes":{capability:"automation:read",scope:"organization"},"POST /api/notifications/routes":{capability:"automation:manage",scope:"organization"},"PATCH /api/notifications/routes":{capability:"automation:manage",scope:"organization"},"POST /api/notifications/routes/preview":{capability:"automation:read",scope:"organization"},"GET /api/notifications/deliveries":{capability:"automation:read",scope:"organization"},"POST /api/notifications/deliveries/retry":{capability:"automation:manage",scope:"organization"},"GET /api/jobs":{capability:"automation:read"},"POST /api/jobs":{capability:"automation:manage"},"PATCH /api/jobs":{capability:"automation:manage"},"POST /api/jobs/preview":{capability:"automation:read"},"POST /api/jobs/action":{capability:"automation:manage"},"POST /api/jobs/reconcile":{capability:"automation:manage"},"GET /api/jobs/history":{capability:"automation:read"},"GET /api/workers":{capability:"automation:read"},"POST /api/workers/action":{capability:"automation:manage"},"POST /api/actions/run":{capability:"fleet:manage"},"GET /api/server/operations":{capability:"fleet:read"},"POST /api/server/operations/run":{capability:"fleet:manage"},"POST /api/server/command":{capability:"runtime:terminal",scope:"organization"},"GET /api/terminal":{capability:"runtime:terminal",scope:"organization"},"GET /api/users":{capability:"users:read",scope:"organization"},"POST /api/users":{capability:"users:manage",scope:"organization"},"DELETE /api/users":{capability:"users:manage",scope:"organization"},"GET /api/serverless/operations":{capability:"deployments:read"},"POST /api/serverless/operations/run":{capability:"deployments:create"},"POST /api/serverless/command":{capability:"runtime:terminal",scope:"organization"},"GET /api/serverless/dlq":{capability:"data:read"},"POST /api/serverless/dlq/redrive":{capability:"data:write"},"POST /api/serverless/dlq/purge":{capability:"data:admin"},"GET /api/serverless/secrets":{capability:"secrets:read"},"POST /api/serverless/secrets":{capability:"secrets:write"},"DELETE /api/serverless/secrets":{capability:"secrets:write"},"POST /api/serverless/functions/config":{capability:"config:write"},"GET /api/serverless/alarms":{capability:"runtime:read"},"POST /api/serverless/alarms":{capability:"config:write"},"DELETE /api/serverless/alarms":{capability:"config:write"},"GET /api/serverless/traces":{capability:"runtime:read"},"POST /api/serverless/scheduler":{capability:"automation:manage"}};function bu(e,t){return kE[`${e.toUpperCase()} ${t}`]??AE}import{createHmac as RE,randomBytes as PE,timingSafeEqual as xE}from"node:crypto";import{chmodSync as DE,existsSync as OE,mkdirSync as _E,readFileSync as NE,writeFileSync as $E}from"node:fs";import{dirname as ME}from"node:path";var no="ts_cloud_session";var LE=28800000;function nh(e){let t=process.env.TS_CLOUD_DASHBOARD_SECRET?.trim();if(t)return t;let r=at(e,"dashboard-secret");try{if(OE(r)){let i=NE(r,"utf8").trim();if(i)return i}}catch{}let n=PE(32).toString("base64url");try{_E(ME(r),{recursive:!0}),$E(r,`${n}
|
|
150
|
-
`),DE(r,384)}catch{}return n}function BE(e,t){return RE("sha256",t).update(e).digest("base64url")}function ih(e,t){if(!e)return null;let r=e.lastIndexOf(".");if(r<=0)return null;let n=e.slice(0,r),i=e.slice(r+1),o=BE(n,t),s=Buffer.from(i),c=Buffer.from(o);if(s.length!==c.length||!xE(s,c))return null;try{let u=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));if(typeof u?.u!=="string"||typeof u?.exp!=="number")return null;if(u.mv!==void 0&&(!u.mv||typeof u.mv!=="object"||Array.isArray(u.mv)||Object.values(u.mv).some((a)=>!Number.isInteger(a)||a<1)))return null;if(Date.now()>=u.exp)return null;return u}catch{return null}}function Su(e,t){if(!e)return;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;if(r.slice(0,n).trim()===t)return decodeURIComponent(r.slice(n+1).trim())}return}function Si(e,t={secure:!0}){let r=Math.floor((t.maxAgeMs??LE)/1000),n=[`${no}=${encodeURIComponent(e)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${r}`];if(t.secure)n.push("Secure");return n.join("; ")}function ia(e={secure:!0}){let t=[`${no}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];if(e.secure)t.push("Secure");return t.join("; ")}import{chmodSync as jE,existsSync as FE,mkdirSync as UE,readFileSync as zE,writeFileSync as VE}from"node:fs";import{dirname as qE}from"node:path";function oh(){return Bo("dashboard-users.json")}function oa(e){return/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(e)}function JE(e){if(!e||typeof e.username!=="string"||!oa(e.username)||typeof e.passwordHash!=="string")return null;let t=e.role==="admin"?"admin":"member",r={};if(e.sites&&typeof e.sites==="object"){for(let[n,i]of Object.entries(e.sites))if(i==="owner"||i==="collaborator")r[n]=i}return{username:e.username,passwordHash:e.passwordHash,role:t,sites:r,name:typeof e.name==="string"?e.name:void 0,email:typeof e.email==="string"?e.email.trim().toLowerCase():void 0,createdAt:typeof e.createdAt==="string"?e.createdAt:void 0}}function WE(e){try{let t=JSON.parse(e);if(!Array.isArray(t?.users))return[];return t.users.map(JE).filter((r)=>r!==null)}catch{return[]}}function sh(e){return at(e,"dashboard-users.json")}function vt(e){let t=sh(e);if(!FE(t))return[];try{return WE(zE(t,"utf8"))}catch{return[]}}function sa(e,t){let r=sh(e);UE(qE(r),{recursive:!0}),VE(r,`${JSON.stringify({users:t},null,2)}
|
|
151
|
-
`),jE(r,384)}function Bt(e,t){let r=t.trim().toLowerCase();return e.find((n)=>n.username.toLowerCase()===r)}function ah(e,t="admin"){let r=vt(e);if(r.some((s)=>s.role==="admin"))return{users:r};let n=process.env.TS_CLOUD_UI_PASSWORD?.trim()||lu(),i={username:t,passwordHash:en(n),role:"admin",sites:{},name:"Administrator",createdAt:new Date().toISOString()},o=[...r,i];return sa(e,o),{users:o,generated:{username:t,password:n}}}function io(e,t){let r=vt(e),n=Bt(r,t.username),i=t.password?.trim()||(n?void 0:lu()),o={username:n?.username??t.username,passwordHash:i?en(i):n.passwordHash,role:n?.role??"member",sites:t.sites,name:t.name??n?.name,email:t.email?.trim().toLowerCase()??n?.email,createdAt:n?.createdAt??new Date().toISOString()},s=n?r.map((c)=>c.username.toLowerCase()===o.username.toLowerCase()?o:c):[...r,o];return sa(e,s),{user:o,password:i}}function aa(e,t,r){let n=vt(e),i=Bt(n,t);if(!i)throw Error("Authentication user was not found");let o={...i,passwordHash:r};return sa(e,n.map((s)=>s.username.toLowerCase()===i.username.toLowerCase()?o:s)),o}function vu(e,t){let r=vt(e),n=Bt(r,t);if(!n)return{ok:!1,error:`No such user: ${t}`};if(n.role==="admin"&&r.filter((i)=>i.role==="admin").length===1)return{ok:!1,error:"Cannot remove the last admin."};return sa(e,r.filter((i)=>i.username.toLowerCase()!==n.username.toLowerCase())),{ok:!0}}function vi(e){return{username:e.username,name:e.name??e.username,role:e.role,email:e.email,sites:e.sites,siteCount:Object.keys(e.sites).length,createdAt:e.createdAt}}var HE={username:"local",passwordHash:"",role:"admin",sites:{},name:"Local (auth disabled)"};function ch(e){let{cwd:t,enabled:r,secret:n,authorization:i,authentication:o}=e,s=(u)=>{if(!o)return;let a=Su(u.headers.get("cookie"),no);return a?.startsWith("v2.")?o.verifySessionToken(a):void 0},c=(u)=>{let a=i.store.getActorByExternalId("user",`dashboard:${u.username.toLowerCase()}`),p=a?i.store.getMembershipForActor(i.organizationId,a.id):void 0;return{actor:a,membership:p}};return{enabled:r,resolveUser(u){if(!r)return HE;let a=Su(u.headers.get("cookie"),no),p=s(u),f=p?void 0:ih(a,n),y=p?.identity.username??f?.u;if(!y)return null;let b=Bt(vt(t),y);if(!b)return null;let{membership:C}=c(b);if(!C||C.status!=="active"||!p&&f?.mv?.[i.organizationId]!==C.sessionVersion)return null;if(!C.lastActiveAt||Date.now()-new Date(C.lastActiveAt).getTime()>300000)i.store.touchMembership(C.id);return b},resolveSession(u){return s(u)?.session??null},check(u,a,p,f){if(!r)return{ok:!0};if(!p)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let y=bu(u.method,a);if(y.anyUser)return{ok:!0};if(y.siteFrom==="body"&&!f)return{ok:!1,status:400,error:"This request must name a site."};let{membership:b}=c(p);if(!b)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let C=y.scope==="organization"?{organizationId:i.organizationId}:i.store.resolveAuthorizationTarget(i.organizationId,{type:"project",id:i.projectId});if(y.scope==="site"){let R=new URL(u.url).searchParams.get("env")??i.defaultEnvironment,x=i.store.getEnvironmentBySlug(i.projectId,R),L=i.store.listResources(i.projectId,x?.id).find((P)=>P.kind==="application"&&P.slug===f);C=L?i.store.resolveAuthorizationTarget(i.organizationId,{type:"resource",id:L.id}):void 0}if(!(C?zt({membership:b,grants:i.store.listGrants(b.id),capability:y.capability,target:C}):{allowed:!1}).allowed)return{ok:!1,status:403,error:"You do not have access to this."};return{ok:!0}}}}async function dh(e,t){if(bu(e.method,t).siteFrom!=="body")return;try{let n=await e.clone().json();return String(n?.name??"").trim()||void 0}catch{return}}import{createHash as GE}from"node:crypto";function uh(e,t,r){for(let n of r){let i=He(t.store,n);if(e.getIdentityByActor(i.id))continue;e.createIdentity({actorId:i.id,username:n.username,email:n.email,emailVerified:!!n.email,passwordHash:n.passwordHash,requiresPasswordUpgrade:!0})}}function KE(e,t,r){let n=r.split("@")[0].toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/^[^a-z0-9]+/,"").slice(0,24),i=/^[a-z0-9][a-z0-9._-]{1,31}$/.test(n)?n:"sso-user";if(!e.getIdentityByUsername(i)&&!Bt(t,i))return i;let o=GE("sha256").update(r).digest("hex").slice(0,7);return`${i.slice(0,24)}-${o}`}function lh(e,t,r,n){if(n.provider.organizationId!==t.organization.id)throw Error("OIDC provider is not configured for this organization");let i=e.getOidcSubject(n.provider.id,n.subject),o=i?e.getIdentity(i.identityId):e.getIdentityByEmail(n.email);if(o?.disabledAt)throw Error("OIDC identity is disabled");if(!i&&o&&!o.emailVerifiedAt)throw Error("OIDC cannot automatically link an unverified local email address");let s=vt(r),c=!1,u=o?Bt(s,o.username):void 0;if(o&&!u)throw Error("OIDC identity has no dashboard user");if(!o){let f=KE(e,s,n.email);u=io(r,{username:f,name:n.name,email:n.email,sites:{}}).user;let b=He(t.store,u);o=e.createIdentity({actorId:b.id,username:u.username,email:n.email,emailVerified:!0,passwordHash:u.passwordHash}),c=!0}else if(o.email!==n.email)o=e.setVerifiedEmail(o.id,n.email);let a=t.store.getActor(o.actorId);if(!a)throw Error("OIDC identity actor was not found");let p=t.store.getMembershipForActor(t.organization.id,a.id);if(p?.status==="revoked")throw Error("OIDC organization membership is revoked");if(!p)t.store.createMembership({organizationId:t.organization.id,actorId:a.id,roleTemplate:n.provider.defaultRole,scope:{type:"organization"},source:"manual"});return e.linkOidcSubject(n.provider.id,o.id,n.subject,n.email),{identity:o,user:u,provisioned:c}}function ph(e,t,r){let n=t.store.getMembershipForActor(t.organization.id,r.actorId);if(!n||n.status!=="active"||n.roleTemplate==="owner"||!r.emailVerifiedAt||!r.email)return!1;let i=r.email.split("@")[1]?.toLowerCase();return e.listOidcProviders(t.organization.id).some((o)=>o.enforceSso&&!!i&&o.allowedDomains.includes(i))}function QE(e){return e.replace(/[&<>"']/g,(t)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function gh(e=!1,t=[]){let r=e?"/serverless":"/",n=t.map((o)=>`<a class="sso-button" href="/auth/oidc/${encodeURIComponent(o.slug)}/start?return=${encodeURIComponent(r)}">Continue with ${QE(o.name)}</a>`).join("");return`<!doctype html>
|
|
152
|
-
<html lang="en">
|
|
153
|
-
<head>
|
|
154
|
-
<meta charset="UTF-8">
|
|
155
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
156
|
-
<title>Sign in · ts-cloud</title>
|
|
157
|
-
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E">
|
|
158
|
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
159
|
-
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
|
160
|
-
<style>${`
|
|
161
|
-
:root {
|
|
162
|
-
--bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
|
|
163
|
-
--txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
|
|
164
|
-
--accent: #5a8be0; --accent-ink: #061019;
|
|
165
|
-
--bad: #f0736e; --badbg: rgba(240,115,110,0.11);
|
|
166
|
-
}
|
|
167
|
-
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
168
|
-
html { background: var(--bg); min-height: 100%; }
|
|
169
|
-
body {
|
|
170
|
-
font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
|
|
171
|
-
background:
|
|
172
|
-
radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
|
|
173
|
-
linear-gradient(175deg, var(--bg), var(--bg2));
|
|
174
|
-
-webkit-font-smoothing: antialiased;
|
|
175
|
-
display: grid; place-items: center; padding: 24px;
|
|
176
|
-
}
|
|
177
|
-
.card {
|
|
178
|
-
width: 100%; max-width: 380px;
|
|
179
|
-
background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
|
|
180
|
-
padding: 32px; backdrop-filter: blur(6px);
|
|
181
|
-
animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
182
|
-
}
|
|
183
|
-
@keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
|
|
184
|
-
@media (prefers-reduced-motion: reduce) { .card { animation: none } }
|
|
185
|
-
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
|
|
186
|
-
.brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
|
|
187
|
-
h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
|
|
188
|
-
.sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
|
|
189
|
-
form { margin-top: 24px; display: grid; gap: 14px; }
|
|
190
|
-
.field { display: flex; flex-direction: column; gap: 7px; }
|
|
191
|
-
label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
|
|
192
|
-
input {
|
|
193
|
-
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
|
|
194
|
-
padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
|
|
195
|
-
}
|
|
196
|
-
input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
|
|
197
|
-
button {
|
|
198
|
-
margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
|
|
199
|
-
padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
|
|
200
|
-
transition: filter .12s, transform .12s;
|
|
201
|
-
}
|
|
202
|
-
button:hover { filter: brightness(1.06); }
|
|
203
|
-
button:active { transform: translateY(1px); }
|
|
204
|
-
button[disabled] { opacity: 0.6; cursor: default; }
|
|
205
|
-
.msg {
|
|
206
|
-
display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
|
|
207
|
-
background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
|
|
208
|
-
font-size: 13px; line-height: 1.45;
|
|
209
|
-
}
|
|
210
|
-
.msg.shown { display: block; }
|
|
211
|
-
.hidden { display: none !important; }
|
|
212
|
-
.note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
|
|
213
|
-
.note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
|
|
214
|
-
a { color: var(--accent); text-decoration: none; }
|
|
215
|
-
a:hover { text-decoration: underline; }
|
|
216
|
-
.sso { display: grid; gap: 10px; margin-top: 22px; }
|
|
217
|
-
.sso-button { display: block; border: 1px solid var(--panel-br); border-radius: 10px; padding: 11px 14px; color: var(--txt); text-align: center; font-size: 13.5px; font-weight: 700; background: rgba(255,255,255,0.04); }
|
|
218
|
-
.sso-button:hover { border-color: var(--accent); text-decoration: none; }
|
|
219
|
-
.separator { display: flex; align-items: center; gap: 10px; margin: 18px 0 -6px; color: var(--txt3); font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; }
|
|
220
|
-
.separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
|
|
221
|
-
`}</style>
|
|
222
|
-
</head>
|
|
223
|
-
<body>
|
|
224
|
-
<main class="card">
|
|
225
|
-
<div class="brand"><span class="dot"></span> ts-cloud</div>
|
|
226
|
-
<h1>Sign in</h1>
|
|
227
|
-
<p class="sub">Manage the sites you have been given access to.</p>
|
|
228
|
-
|
|
229
|
-
${t.length>0?`<div class="sso" aria-label="Single sign-on">${n}</div><div class="separator"><span>or use local recovery</span></div>`:""}
|
|
230
|
-
|
|
231
|
-
<form id="login" autocomplete="on">
|
|
232
|
-
<div class="field">
|
|
233
|
-
<label for="username">Username</label>
|
|
234
|
-
<input id="username" name="username" autocomplete="username" required autofocus>
|
|
235
|
-
</div>
|
|
236
|
-
<div class="hidden field" id="mfa-field">
|
|
237
|
-
<label for="mfa-code">Authenticator or recovery code</label>
|
|
238
|
-
<input id="mfa-code" name="mfa-code" autocomplete="one-time-code">
|
|
239
|
-
</div>
|
|
240
|
-
<div class="field">
|
|
241
|
-
<label for="password">Password</label>
|
|
242
|
-
<input id="password" name="password" type="password" autocomplete="current-password" required>
|
|
243
|
-
</div>
|
|
244
|
-
<button type="submit" id="submit">Sign in</button>
|
|
245
|
-
</form>
|
|
246
|
-
|
|
247
|
-
<p class="msg" id="msg" role="alert" aria-live="polite"></p>
|
|
248
|
-
<p class="note"><a href="/forgot-password">Forgot your password?</a></p>
|
|
249
|
-
</main>
|
|
250
|
-
|
|
251
|
-
<script>
|
|
252
|
-
const form = document.getElementById('login')
|
|
253
|
-
const msg = document.getElementById('msg')
|
|
254
|
-
const submit = document.getElementById('submit')
|
|
255
|
-
const mfaField = document.getElementById('mfa-field')
|
|
256
|
-
const mfaCode = document.getElementById('mfa-code')
|
|
257
|
-
let challengeToken = ''
|
|
258
|
-
|
|
259
|
-
if (new URLSearchParams(location.search).has('sso_error')) {
|
|
260
|
-
msg.textContent = 'Single sign-on could not be completed. Try again or use the local recovery path.'
|
|
261
|
-
msg.classList.add('shown')
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
form.addEventListener('submit', async (event) => {
|
|
265
|
-
event.preventDefault()
|
|
266
|
-
msg.classList.remove('shown')
|
|
267
|
-
submit.disabled = true
|
|
268
|
-
submit.textContent = 'Signing in...'
|
|
269
|
-
try {
|
|
270
|
-
const res = await fetch(challengeToken ? '/api/auth/mfa/complete' : '/api/login', {
|
|
271
|
-
method: 'POST',
|
|
272
|
-
headers: { 'content-type': 'application/json' },
|
|
273
|
-
body: JSON.stringify(challengeToken
|
|
274
|
-
? { challengeToken, code: mfaCode.value }
|
|
275
|
-
: { username: document.getElementById('username').value, password: document.getElementById('password').value }),
|
|
276
|
-
})
|
|
277
|
-
const body = await res.json().catch(() => ({}))
|
|
278
|
-
if (!res.ok || !body.ok) throw new Error(body.error || 'Could not sign in.')
|
|
279
|
-
if (body.mfaRequired) {
|
|
280
|
-
challengeToken = body.challengeToken
|
|
281
|
-
mfaField.classList.remove('hidden')
|
|
282
|
-
mfaCode.required = true
|
|
283
|
-
document.getElementById('username').readOnly = true
|
|
284
|
-
document.getElementById('password').readOnly = true
|
|
285
|
-
submit.disabled = false
|
|
286
|
-
submit.textContent = 'Verify and sign in'
|
|
287
|
-
mfaCode.focus()
|
|
288
|
-
return
|
|
289
|
-
}
|
|
290
|
-
location.href = ${JSON.stringify(r)}
|
|
291
|
-
} catch (error) {
|
|
292
|
-
msg.textContent = (error && error.message) || String(error)
|
|
293
|
-
msg.classList.add('shown')
|
|
294
|
-
submit.disabled = false
|
|
295
|
-
submit.textContent = 'Sign in'
|
|
296
|
-
if (challengeToken) {
|
|
297
|
-
mfaCode.value = ''
|
|
298
|
-
mfaCode.focus()
|
|
299
|
-
}
|
|
300
|
-
else {
|
|
301
|
-
document.getElementById('password').value = ''
|
|
302
|
-
document.getElementById('password').focus()
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
})
|
|
306
|
-
</script>
|
|
307
|
-
</body>
|
|
308
|
-
</html>`}function mh(e){let t=e==="reset";return`<!doctype html>
|
|
309
|
-
<html lang="en">
|
|
310
|
-
<head>
|
|
311
|
-
<meta charset="UTF-8">
|
|
312
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
313
|
-
<title>${t?"Choose a new password":"Recover your account"} · ts-cloud</title>
|
|
314
|
-
<style>${`
|
|
315
|
-
:root {
|
|
316
|
-
--bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
|
|
317
|
-
--txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
|
|
318
|
-
--accent: #5a8be0; --accent-ink: #061019;
|
|
319
|
-
--bad: #f0736e; --badbg: rgba(240,115,110,0.11);
|
|
320
|
-
}
|
|
321
|
-
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
322
|
-
html { background: var(--bg); min-height: 100%; }
|
|
323
|
-
body {
|
|
324
|
-
font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
|
|
325
|
-
background:
|
|
326
|
-
radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
|
|
327
|
-
linear-gradient(175deg, var(--bg), var(--bg2));
|
|
328
|
-
-webkit-font-smoothing: antialiased;
|
|
329
|
-
display: grid; place-items: center; padding: 24px;
|
|
330
|
-
}
|
|
331
|
-
.card {
|
|
332
|
-
width: 100%; max-width: 380px;
|
|
333
|
-
background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
|
|
334
|
-
padding: 32px; backdrop-filter: blur(6px);
|
|
335
|
-
animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
336
|
-
}
|
|
337
|
-
@keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
|
|
338
|
-
@media (prefers-reduced-motion: reduce) { .card { animation: none } }
|
|
339
|
-
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
|
|
340
|
-
.brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
|
|
341
|
-
h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
|
|
342
|
-
.sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
|
|
343
|
-
form { margin-top: 24px; display: grid; gap: 14px; }
|
|
344
|
-
.field { display: flex; flex-direction: column; gap: 7px; }
|
|
345
|
-
label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
|
|
346
|
-
input {
|
|
347
|
-
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
|
|
348
|
-
padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
|
|
349
|
-
}
|
|
350
|
-
input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
|
|
351
|
-
button {
|
|
352
|
-
margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
|
|
353
|
-
padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
|
|
354
|
-
transition: filter .12s, transform .12s;
|
|
355
|
-
}
|
|
356
|
-
button:hover { filter: brightness(1.06); }
|
|
357
|
-
button:active { transform: translateY(1px); }
|
|
358
|
-
button[disabled] { opacity: 0.6; cursor: default; }
|
|
359
|
-
.msg {
|
|
360
|
-
display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
|
|
361
|
-
background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
|
|
362
|
-
font-size: 13px; line-height: 1.45;
|
|
363
|
-
}
|
|
364
|
-
.msg.shown { display: block; }
|
|
365
|
-
.hidden { display: none !important; }
|
|
366
|
-
.note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
|
|
367
|
-
.note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
|
|
368
|
-
a { color: var(--accent); text-decoration: none; }
|
|
369
|
-
a:hover { text-decoration: underline; }
|
|
370
|
-
.sso { display: grid; gap: 10px; margin-top: 22px; }
|
|
371
|
-
.sso-button { display: block; border: 1px solid var(--panel-br); border-radius: 10px; padding: 11px 14px; color: var(--txt); text-align: center; font-size: 13.5px; font-weight: 700; background: rgba(255,255,255,0.04); }
|
|
372
|
-
.sso-button:hover { border-color: var(--accent); text-decoration: none; }
|
|
373
|
-
.separator { display: flex; align-items: center; gap: 10px; margin: 18px 0 -6px; color: var(--txt3); font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; }
|
|
374
|
-
.separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
|
|
375
|
-
`}</style>
|
|
376
|
-
</head>
|
|
377
|
-
<body>
|
|
378
|
-
<main class="card">
|
|
379
|
-
<div class="brand"><span class="dot"></span> ts-cloud</div>
|
|
380
|
-
<h1>${t?"Choose a new password":"Recover your account"}</h1>
|
|
381
|
-
<p class="sub">${t?"This one-time link expires after one hour.":"Enter your username or verified email. The response is the same whether or not an account exists."}</p>
|
|
382
|
-
<form id="recovery" autocomplete="on">
|
|
383
|
-
${t?'<div class="field"><label for="password">New password</label><input id="password" name="password" type="password" autocomplete="new-password" minlength="12" required></div><div class="field"><label for="confirmation">Confirm new password</label><input id="confirmation" name="confirmation" type="password" autocomplete="new-password" minlength="12" required></div>':'<div class="field"><label for="identifier">Username or email</label><input id="identifier" name="identifier" autocomplete="username" required autofocus></div>'}
|
|
384
|
-
<button type="submit" id="submit">${t?"Change password":"Send reset link"}</button>
|
|
385
|
-
</form>
|
|
386
|
-
<p class="msg" id="msg" role="status" aria-live="polite"></p>
|
|
387
|
-
<p class="note"><a href="/login">Return to sign in</a></p>
|
|
388
|
-
</main>
|
|
389
|
-
<script>
|
|
390
|
-
const form = document.getElementById('recovery')
|
|
391
|
-
const msg = document.getElementById('msg')
|
|
392
|
-
const submit = document.getElementById('submit')
|
|
393
|
-
const reset = ${JSON.stringify(t)}
|
|
394
|
-
const token = new URLSearchParams(location.search).get('token') || ''
|
|
395
|
-
if (reset && !token) {
|
|
396
|
-
msg.textContent = 'This reset link is missing its token. Request a new link.'
|
|
397
|
-
msg.classList.add('shown')
|
|
398
|
-
submit.disabled = true
|
|
399
|
-
}
|
|
400
|
-
form.addEventListener('submit', async (event) => {
|
|
401
|
-
event.preventDefault()
|
|
402
|
-
if (reset && document.getElementById('password').value !== document.getElementById('confirmation').value) {
|
|
403
|
-
msg.textContent = 'The passwords do not match.'
|
|
404
|
-
msg.classList.add('shown')
|
|
405
|
-
return
|
|
406
|
-
}
|
|
407
|
-
submit.disabled = true
|
|
408
|
-
msg.textContent = reset ? 'Changing password…' : 'Requesting reset link…'
|
|
409
|
-
msg.classList.add('shown')
|
|
410
|
-
const response = await fetch(reset ? '/api/auth/password-reset/complete' : '/api/auth/password-reset/request', {
|
|
411
|
-
method: 'POST',
|
|
412
|
-
headers: { 'content-type': 'application/json' },
|
|
413
|
-
body: JSON.stringify(reset
|
|
414
|
-
? { token, password: document.getElementById('password').value }
|
|
415
|
-
: { identifier: document.getElementById('identifier').value }),
|
|
416
|
-
})
|
|
417
|
-
const result = await response.json().catch(() => ({}))
|
|
418
|
-
msg.textContent = result.message || result.error || 'The request could not be completed.'
|
|
419
|
-
if (!response.ok) {
|
|
420
|
-
submit.disabled = false
|
|
421
|
-
return
|
|
422
|
-
}
|
|
423
|
-
if (reset)
|
|
424
|
-
setTimeout(() => location.assign('/login'), 1200)
|
|
425
|
-
})
|
|
426
|
-
</script>
|
|
427
|
-
</body>
|
|
428
|
-
</html>`}var YE=["restart","reload","start","stop","enable","disable"],fh=65536;function wi(e){return e.length<=fh?e:`${e.slice(0,fh)}
|
|
429
|
-
|
|
430
|
-
[output truncated]`}function XE(e){return/^[A-Za-z0-9_.@:-]+$/.test(e)}function wu(e){return/^[A-Za-z0-9_-]+$/.test(e)}function ZE(e){return e.charAt(0).toUpperCase()+e.slice(1)}function da(e,t){let r=[],n=t.servicesDetail??t.services??[];for(let s of n){let c=String(s?.name??"");if(!c||!XE(c))continue;for(let u of YE)r.push({id:`${u}:${c}`,label:`${ZE(u)} ${c}`,group:"service",target:c,mutates:!0,confirm:c,danger:u==="stop"||u==="disable"})}for(let[s,c]of Object.entries(e.sites??{})){if(!c||!wu(s))continue;let u=bh(c);if(u==="server-app"||u==="server-php")r.push({id:`rollback:${s}`,label:`Rollback ${s}`,group:"deploy",target:s,mutates:!0,confirm:s,danger:!0})}let i=new Set;for(let s of t.workers??[]){let c=String(s?.name??"").split(":")[0];if(c&&wu(c))i.add(c)}for(let s of i)r.push({id:`worker:restart:${s}`,label:`Restart workers (${s})`,group:"worker",target:s,mutates:!0,confirm:s});for(let[s,c]of Object.entries(e.sites??{})){if(!c||!wu(s))continue;if(c.scheduler||c.schedule){let u=ca(c)==="laravel";r.push({id:`scheduler:run:${s}`,label:`${u?"Run":"Restart"} scheduler (${s})`,group:"scheduler",target:s,mutates:!0,confirm:s})}}if(e.infrastructure?.compute?.backups?.enabled){if(r.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),it(e))r.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return r}function Cu(e,t,r){return da(t,r).find((n)=>n.id===e)}function eT(e,t){let r=e==="enable"||e==="disable"?`systemctl is-enabled ${t} 2>/dev/null || true`:`systemctl is-active ${t} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${e} ${t}`,r]}function tT(){return`eval "$(cd ${Sh} && pantry env 2>/dev/null)"`}function Ih(e,t,r){let n=`${yh(e,t)}/current`;return["set -uo pipefail",`[ -d ${n} ] || { echo "site ${t} has no current release" >&2; exit 1; }`,`cd ${n} && ${tT()} && php artisan ${r}`]}function rT(e,t,r){if(e==="laravel")return Ih(t,r,"queue:restart");let n=`${t}-${r}-queue-*.service`;return["set -uo pipefail",`units=$(systemctl list-units --type=service --all --no-legend '${n}' 2>/dev/null | awk '{print $1}')`,`[ -n "$units" ] || { echo "no queue-worker units found for ${r} (${n})" >&2; exit 1; }`,"systemctl restart $units",`systemctl --no-legend --type=service list-units '${n}' 2>/dev/null || true`]}function nT(e,t,r){if(e==="laravel")return Ih(t,r,"schedule:run");let n=`${t}-${r}-scheduler.service`;return["set -uo pipefail",`systemctl restart ${n}`,`systemctl is-active ${n} 2>/dev/null || true`]}function iT(){return["set -uo pipefail",`[ -x ${Iu} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,Iu]}function hh(e,t,r){return{operation:e,command:t,ok:r.success,stdout:wi(r.perInstance?.[0]?.output??""),stderr:wi(r.perInstance?.[0]?.error??r.error??"")}}async function ua(e,t,r,n={}){let i=e.project.slug,o;try{o=xr({config:e})}catch(f){return{operation:r.id,ok:!1,error:`Could not initialize the cloud driver: ${f?.message??f}`}}let s={driver:o,slug:i,environment:t,role:"app"};if(r.group==="deploy"){let f=n.to&&/^[A-Za-z0-9._-]+$/.test(n.to)?n.to:void 0,y=await vh(s,{siteName:r.target,to:f});return hh(r.id,`rollback ${r.target}${f?` → ${f}`:""}`,y)}if(r.id==="backup:restore"){let f=await wh(s,{database:it(e)});return hh(r.id,"db restore",f)}let c=await o.findComputeTargets({slug:i,environment:t,role:"app"});if(!c.length)return{operation:r.id,ok:!1,error:"No app server target was found for this environment."};let u,a;if(r.group==="service"){let[f,...y]=r.id.split(":");u=eT(f,y.join(":")),a=`systemctl ${f} ${r.target}`}else if(r.group==="worker"){let f=ca(e.sites?.[r.target]??{});u=rT(f,i,r.target),a=f==="laravel"?`queue:restart (${r.target})`:`restart queue units (${r.target})`}else if(r.group==="scheduler"){let f=ca(e.sites?.[r.target]??{});u=nT(f,i,r.target),a=f==="laravel"?`schedule:run (${r.target})`:`restart scheduler (${r.target})`}else if(r.id==="backup:run")u=iT(),a="ts-cloud backup";else return{operation:r.id,ok:!1,error:"Unknown operation."};let p=await o.runRemoteDeploy({targets:[c[0]],commands:u,comment:`ts-cloud dashboard:${r.id}`,tags:{Project:i,Environment:t,Role:"app"}});return{operation:r.id,command:a,ok:p.success,stdout:wi(p.perInstance?.[0]?.output??""),stderr:wi(p.perInstance?.[0]?.error??p.error??"")}}async function oo(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};let i;try{i=xr({config:e})}catch(u){return{operation:"command",ok:!1,error:`Could not initialize the cloud driver: ${u?.message??u}`}}let o=e.project.slug,s=await i.findComputeTargets({slug:o,environment:t,role:"app"});if(!s.length)return{operation:"command",ok:!1,error:"No app server target was found for this environment."};let c=await i.runRemoteDeploy({targets:[s[0]],commands:["set -o pipefail",n],comment:"ts-cloud dashboard:command",tags:{Project:o,Environment:t,Role:"app"}});return{operation:"command",command:n,ok:c.success,stdout:wi(c.perInstance?.[0]?.output??""),stderr:wi(c.perInstance?.[0]?.error??c.error??"")}}var oT=[{id:"server.overview",path:"/",label:"Dashboard",group:"overview",modes:["server"],adminOnly:!0,legacyPaths:["/server"]},{id:"server.activity",path:"/server/activity",label:"Activity",group:"overview",modes:["server"],adminOnly:!0,legacyPaths:["/activity"]},{id:"services.list",path:"/server/sites",label:"Services",group:"applications",modes:["server"],adminOnly:!1,legacyPaths:["/sites","/services"]},{id:"deployments.list",path:"/server/deployments",label:"Deployments",group:"applications",modes:["server"],adminOnly:!1,legacyPaths:["/deployments"]},{id:"logs.list",path:"/server/logs",label:"Logs",group:"applications",modes:["server"],adminOnly:!1,legacyPaths:["/logs"]},{id:"sources.integrations",path:"/integrations",label:"Git integrations",group:"applications",modes:["server","serverless"],adminOnly:!1},{id:"applications.create",path:"/applications/new",label:"Create application",group:"applications",modes:["server","serverless"],adminOnly:!1},{id:"applications.compose",path:"/applications/compose",label:"Compose applications",group:"applications",modes:["server"],adminOnly:!1},{id:"operations.queue",path:"/operations/queue",label:"Deployment queue",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"operations.previews",path:"/operations/previews",label:"Preview environments",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"operations.releases",path:"/operations/releases",label:"Releases & promotion",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"runtime.workloads",path:"/operations/workloads",label:"Workloads",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"observability.overview",path:"/operations/observability",label:"Observability",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"alerts.overview",path:"/operations/alerts",label:"Alerts & health",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"spend.overview",path:"/operations/spend",label:"Spend & budgets",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"automation.jobs",path:"/operations/jobs",label:"Workers & schedules",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/server/workers","/serverless/scheduler"]},{id:"configuration.entries",path:"/operations/configuration",label:"Environment & secrets",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/serverless/secrets"]},{id:"metrics.overview",path:"/server/metrics",label:"Metrics",group:"operations",modes:["server"],adminOnly:!0},{id:"runtime.services",path:"/server/services",label:"Runtime services",group:"operations",modes:["server"],adminOnly:!0},{id:"backups.list",path:"/data/backups",label:"Backups & recovery",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/server/backups"]},{id:"volumes.list",path:"/data/volumes",label:"Persistent volumes",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:[]},{id:"fleet.list",path:"/server/fleet",label:"Fleet inventory",group:"operations",modes:["server"],adminOnly:!1,legacyPaths:[]},{id:"operations.run",path:"/server/actions",label:"Run operations",group:"operations",modes:["server"],adminOnly:!0},{id:"infrastructure.topology",path:"/infrastructure/topology",label:"Infrastructure map",group:"infrastructure",modes:["server","serverless"],adminOnly:!0,legacyPaths:["/topology"]},{id:"data.services",path:"/data/services",label:"Data services",group:"infrastructure",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/database","/databases","/server/database","/serverless/data"]},{id:"network.firewall",path:"/server/firewall",label:"Network & firewall",group:"infrastructure",modes:["server"],adminOnly:!0},{id:"security.posture",path:"/security",label:"Security posture",group:"infrastructure",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/server/security"]},{id:"access.ssh",path:"/server/ssh-keys",label:"SSH keys",group:"infrastructure",modes:["server"],adminOnly:!0},{id:"runtime.terminal",path:"/server/terminal",label:"Terminal",group:"infrastructure",modes:["server"],adminOnly:!0},{id:"organization.people",path:"/server/team",label:"People & access",group:"organization",modes:["server","serverless"],adminOnly:!0,legacyPaths:["/team"]},{id:"organization.automation",path:"/account/automation",label:"API & automation",group:"organization",modes:["server","serverless"],adminOnly:!0},{id:"serverless.overview",path:"/serverless",label:"Dashboard",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.deployments",path:"/serverless/deployments",label:"Deployments",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.logs",path:"/serverless/logs",label:"Logs",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.metrics",path:"/serverless/metrics",label:"Metrics",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.traces",path:"/serverless/traces",label:"Traces",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.functions",path:"/serverless/functions",label:"Functions",group:"compute-data",modes:["serverless"],adminOnly:!0},{id:"serverless.queues",path:"/serverless/queues",label:"Queues",group:"compute-data",modes:["serverless"],adminOnly:!0},{id:"serverless.assets",path:"/serverless/assets",label:"Assets",group:"compute-data",modes:["serverless"],adminOnly:!0},{id:"serverless.network",path:"/serverless/firewall",label:"Network",group:"settings",modes:["serverless"],adminOnly:!0},{id:"serverless.alerts",path:"/serverless/alarms",label:"Alerts",group:"settings",modes:["serverless"],adminOnly:!0},{id:"serverless.cost",path:"/serverless/cost",label:"Costs",group:"settings",modes:["serverless"],adminOnly:!0}],sT=new Map(oT.flatMap((e)=>(e.legacyPaths??[]).map((t)=>[t,e.path])));function Ch(e){return sT.get(e)}function aT(e,t){return[`${e}-${t}`,`${e}-${t}-queues`,`${e}-${t}-daemons`]}function Eh(e,t,r){return r.some((n)=>aT(t,n).includes(e))}function Eu(e,t){let{user:r,slug:n}=t;if(r.role==="admin")return e;let i=(e.sites??[]).map((C)=>C.name).filter(Boolean),o=uu(r,i),s=new Set(o),c=(e.sites??[]).filter((C)=>s.has(C.name)),u=(e.sitesDetail??[]).filter((C)=>s.has(C.name)),a=new Set(u.map((C)=>C.domain).filter(Boolean)),p=(e.serverDeploymentsDetail??e.serverDeployments??[]).filter((C)=>s.has(C.site)),f=(e.serverLogs??[]).filter((C)=>Eh(C.source,n,o)),y=(e.security?.tlsCertificates??[]).filter((C)=>a.has(C.domain)),b=(e.activity??[]).filter((C)=>{if(C.type==="deploy")return o.some((T)=>String(C.title??"").startsWith(`${T} `));if(C.type==="log")return Eh(String(C.title??"").split(" ")[0],n,o);return!1});return{mode:e.mode,environment:e.environment,environments:e.environments,scoped:!0,server:{name:""},sites:c,sitesDetail:u,workers:(e.workers??[]).filter((C)=>s.has(C.site)),serverDeployments:p.slice(0,5),serverDeploymentsDetail:p.slice(0,50),deploymentsEmptyReason:p.length?void 0:"No deployments have been recorded for your sites yet.",serverLogs:f,serverLogsEmptyReason:f.length?void 0:"No recent log entries for your sites.",security:{tlsCertificates:y,ports:[],firewall:null,authEvents:[]},diagnostics:(e.diagnostics??[]).filter((C)=>["Route conflicts","TLS certificates"].includes(C.name)),activity:b}}function Th(e,t){if(t.role==="admin")return e;let r=new Set(uu(t,Object.keys(e.sites??{})));return{project:{name:e.project?.name},environment:e.environment,environments:e.environments,sites:Object.fromEntries(Object.entries(e.sites??{}).filter(([n])=>r.has(n)))}}var cT=new Set(["name","ssl","env","redirects","aliases","domain","path"]),Ah={build:"build runs as a shell command on the server",start:"start runs as a shell command on the server",root:"root is a filesystem path on the shared server",port:"ports are allocated by the server owner",type:"the deploy type is set by the server owner",php:"the PHP runtime is set by the server owner"};function Rh(e){let t=Object.keys(e).filter((i)=>e[i]!==void 0),r=t.filter((i)=>(i in Ah));if(r.length)return{ok:!1,error:`Only the server owner can change ${r.map((o)=>`${o} (${Ah[o]})`).join(", ")}.`};let n=t.filter((i)=>!cT.has(i));if(n.length)return{ok:!1,error:`Only the server owner can change ${n.join(", ")}.`};return{ok:!0}}function la(e){return String(e??"").trim().toLowerCase().replace(/\.$/,"")}function kh(e){let t=String(e??"/").trim();if(!t||t==="/")return"/";return(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")||"/"}function dT(e){let t=[la(e?.domain)];if(Array.isArray(e?.aliases))t.push(...e.aliases.map(la));return t.filter(Boolean)}function Ph({siteName:e,body:t,sites:r,ownSites:n}){let i=r[e]??{},o=new Set(n),s=new Set;if(t.domain!==void 0)s.add(la(t.domain));if(Array.isArray(t.aliases))for(let u of t.aliases)s.add(la(u));if(s.delete(""),s.size===0)return{ok:!0};let c=kh(t.path!==void 0?t.path:i.path);for(let[u,a]of Object.entries(r)){if(u===e||o.has(u))continue;let p=kh(a?.path);for(let f of dT(a)){if(!s.has(f))continue;if(p===c)return{ok:!1,error:`${f}${c==="/"?"":c} is already served by another site on this server.`}}}return{ok:!0}}class so{maxAttempts;lockoutMs;windowMs;attempts=new Map;constructor(e=8,t=900000,r=900000){this.maxAttempts=e;this.lockoutMs=t;this.windowMs=r}key(e,t){return`${e.trim().toLowerCase()}\x00${t}`}check(e,t,r=Date.now()){let n=this.attempts.get(this.key(e,t));if(!n?.until)return{allowed:!0};if(r>=n.until)return this.attempts.delete(this.key(e,t)),{allowed:!0};return{allowed:!1,retryAfterSeconds:Math.ceil((n.until-r)/1000)}}recordFailure(e,t,r=Date.now()){let n=this.key(e,t),i=this.attempts.get(n),s=!i||r-i.last>this.windowMs?1:i.count+1,c={count:s,last:r};if(s>=this.maxAttempts)c.until=r+this.lockoutMs;this.attempts.set(n,c)}recordSuccess(e,t){this.attempts.delete(this.key(e,t))}prune(e=Date.now()){for(let[t,r]of this.attempts)if(r.until?e>=r.until:e-r.last>this.windowMs)this.attempts.delete(t)}get size(){return this.attempts.size}}var Dh=new Set([22,80,443]);function ao(e){return Number.isInteger(e)&&e>=1&&e<=65535}function Nn(e){return[...new Set(e.filter((t)=>ao(t)&&!Dh.has(t)))].sort((t,r)=>t-r)}function Oh(e,t,r=[]){if(!ao(t))throw Error("Port must be an integer between 1 and 65535.");if(Dh.has(t))throw Error(`Port ${t} (SSH/HTTP/HTTPS) is always open and is not managed here.`);return Nh({configText:e,ports:Nn([...r,t])})}function _h(e,t,r=[]){return Nh({configText:e,ports:Nn(r.filter((n)=>n!==t))})}function xh(e,t,r,n,i){let o=e.slice(t,r),s=new RegExp(`\\b${n}\\s*:\\s*\\${i}`).exec(o);if(!s)return null;let c=t+s.index,u=e.indexOf(i,c);return{propStart:c,open:u,close:Au(e,u,i,i==="{"?"}":"]")}}function Tu(e){return`allowedPorts: [${e.join(", ")}]`}function Nh(e){let{configText:t}=e,r=Nn(e.ports),n=/\bcompute\s*:\s*{/.exec(t);if(!n)throw Error("Could not find infrastructure.compute in the cloud config.");let i=t.indexOf("{",n.index),o=Au(t,i,"{","}"),s=xh(t,i+1,o,"firewall","{");if(s){let p=xh(t,s.open+1,s.close,"allowedPorts","[");if(p){let C=p.propStart;while(C>0&&t[C-1]!==`
|
|
431
|
-
`&&/\s/.test(t[C-1]))C--;let T=t.slice(C,p.propStart);return`${t.slice(0,C)}${T}${Tu(r)}${t.slice(p.close+1)}`}let f=t.slice(0,s.close).trimEnd(),y=t.slice(s.close),b=f.endsWith(",")||f.endsWith("{")?"":",";return`${f}${b}
|
|
432
|
-
${Tu(r)},
|
|
433
|
-
${y}`}let c=t.slice(0,o).trimEnd(),u=t.slice(o),a=c.endsWith(",")||c.endsWith("{")?"":",";return`${c}${a}
|
|
434
|
-
firewall: {
|
|
435
|
-
enabled: true,
|
|
436
|
-
${Tu(r)},
|
|
437
|
-
},
|
|
438
|
-
${u}`}class ku{client;region;constructor(e="us-east-1"){this.region=e,this.client=new pe}async getTraceSummaries(e){let t={StartTime:Math.floor(e.startTime.getTime()/1000),EndTime:Math.floor(e.endTime.getTime()/1000),TimeRangeType:"Event",Sampling:!1};if(e.filterExpression)t.FilterExpression=e.filterExpression;if(e.nextToken)t.NextToken=e.nextToken;let r=await this.client.request({service:"xray",region:this.region,method:"POST",path:"/TraceSummaries",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return{summaries:r?.TraceSummaries??[],nextToken:r?.NextToken}}async batchGetTraces(e){if(!e.length)return[];return(await this.client.request({service:"xray",region:this.region,method:"POST",path:"/Traces",headers:{"Content-Type":"application/json"},body:JSON.stringify({TraceIds:e.slice(0,5)})}))?.Traces??[]}}var $h=65536;function pt(e){return e.length<=$h?e:`${e.slice(0,$h)}
|
|
439
|
-
|
|
440
|
-
[output truncated]`}function Ou(e,t){return e.environments?.[t]?.app}function _u(e,t,r){let n=[],i=Ou(e,t);n.push({id:"redeploy",label:"Redeploy current build",group:"deploy",target:"app",mutates:!0,confirm:"redeploy"}),n.push({id:"rollback",label:"Roll back to previous build",group:"deploy",target:"app",mutates:!0,confirm:"rollback",danger:!0});let o=r.maintenance?.enabled;if(o!==!0)n.push({id:"maintenance:on",label:"Enable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"maintenance",danger:!0});if(o!==!1)n.push({id:"maintenance:off",label:"Disable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"live"});if(i?.assets||r.assetsInfo)n.push({id:"assets:invalidate",label:"Invalidate CDN cache",group:"assets",target:"assets",mutates:!0,confirm:"invalidate"});if(i?.database?.connection==="aurora-serverless")n.push({id:"db:scale",label:"Scale Aurora capacity",group:"database",target:"database",mutates:!0,confirm:"scale",inputs:[{name:"min",label:"Min ACUs",placeholder:String(i.database.minCapacity??0.5)},{name:"max",label:"Max ACUs",placeholder:String(i.database.maxCapacity??4)}]});for(let s of r.queues??[]){let c=String(s?.name??"").trim();if(c&&/^[A-Za-z0-9_-]+$/.test(c))n.push({id:`queue:purge:${c}`,label:`Purge queue (${c})`,group:"queue",target:c,mutates:!0,confirm:c,danger:!0})}return n}function zh(e,t,r,n){return _u(t,r,n).find((i)=>i.id===e)}async function uT(e,t,r){try{let n=new Bh(r),{Stacks:i}=await n.describeStacks({stackName:Mh(e,t)}),o={};for(let u of i?.[0]?.Outputs??[])if(u.OutputKey)o[u.OutputKey]=u.OutputValue??"";let s=o.AssetsCdnDomain;if(!s)return null;return(await new Du(r).findDistributionByDomain(s))?.Id??null}catch{return null}}async function Vh(e,t,r,n={}){try{if(r.id==="redeploy")return await jh(e,t),{operation:r.id,command:"serverless redeploy",ok:!0,stdout:"Redeploy complete."};if(r.id==="rollback")return await Fh(e,t),{operation:r.id,command:"serverless rollback",ok:!0,stdout:"Rollback complete."};if(r.id==="maintenance:on")return await Ru(e,t,!0),{operation:r.id,command:"maintenance on",ok:!0,stdout:"Application is now in maintenance mode."};if(r.id==="maintenance:off")return await Ru(e,t,!1),{operation:r.id,command:"maintenance off",ok:!0,stdout:"Application is live."};if(r.id==="db:scale"){let i=Number(n.min),o=Number(n.max);if(!Number.isFinite(i)||!Number.isFinite(o)||i<=0||o<i)return{operation:r.id,ok:!1,error:"Provide valid Aurora capacities (0 < min ≤ max)."};return await Uh(e,t,i,o),{operation:r.id,command:`db:scale ${i}-${o} ACU`,ok:!0,stdout:`Scaling applied (${i}-${o} ACUs); takes effect shortly.`}}if(r.id==="assets:invalidate"){let i=await lt(e,t),o=await uT(e,t,i.region);if(!o)return{operation:r.id,ok:!1,error:"Could not resolve the asset CloudFront distribution for this environment."};let c=await new Du(i.region).invalidateAll(o);return{operation:r.id,command:`cloudfront invalidate ${o} /*`,ok:!0,stdout:`Invalidation ${c?.Id??"created"} for ${o} (/*).`}}if(r.group==="queue"&&r.id.startsWith("queue:purge:")){let i=r.target,o=await lt(e,t),s=new uo(o.region),c=`${o.slug}-${t}-${i}`,{QueueUrl:u}=await s.getQueueUrl(c);return await s.purgeQueue(u),{operation:r.id,command:`sqs purge ${c}`,ok:!0,stdout:`Purged queue ${c}.`}}return{operation:r.id,ok:!1,error:"Unknown or unavailable serverless operation."}}catch(i){return{operation:r.id,ok:!1,error:pt(i?.message??String(i))}}}async function qh(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};try{let i=await xu(e,t,n);return{operation:"command",command:n,ok:!0,stdout:pt(i||"(no output)")}}catch(i){return{operation:"command",command:n,ok:!1,error:pt(i?.message??String(i))}}}var Nu="No dead-letter queue is provisioned for this environment.";async function $u(e,t,r){try{let{QueueUrl:n}=await e.getQueueUrl(`${t}-${r}-dlq`);return n}catch{return null}}async function Jh(e,t,r=10){try{let n=await lt(e,t),i=new uo(n.region),o=await $u(i,n.slug,t);if(!o)return{ok:!1,messages:[],error:Nu};return{ok:!0,messages:((await i.receiveMessages({queueUrl:o,maxMessages:Math.min(10,Math.max(1,r)),waitTimeSeconds:1,visibilityTimeout:2})).Messages??[]).map((u)=>({id:u.MessageId,receiptHandle:u.ReceiptHandle,body:pt(String(u.Body??""))}))}}catch(n){return{ok:!1,messages:[],error:pt(n?.message??String(n))}}}async function Wh(e,t,r={}){try{let n=await lt(e,t),i=Ou(e,t),s=(i?Lh(i,n.slug,t):[]).map((b)=>b.name.replace(`${n.slug}-${t}-`,"")),c=r.targetQueue&&s.includes(r.targetQueue)?r.targetQueue:s[0];if(!c)return{operation:"dlq:redrive",ok:!1,error:"No source queue is configured to redrive into."};let u=new uo(n.region),a=await $u(u,n.slug,t);if(!a)return{operation:"dlq:redrive",ok:!1,error:Nu};let{QueueUrl:p}=await u.getQueueUrl(`${n.slug}-${t}-${c}`),f=Math.min(50,Math.max(1,r.max??10)),y=0;while(y<f){let C=(await u.receiveMessages({queueUrl:a,maxMessages:Math.min(10,f-y),waitTimeSeconds:1,visibilityTimeout:30})).Messages??[];if(!C.length)break;for(let T of C)await u.sendMessage({queueUrl:p,messageBody:String(T.Body??"")}),await u.deleteMessage(a,T.ReceiptHandle),y++}return{operation:"dlq:redrive",command:`redrive → ${c}`,ok:!0,stdout:`Moved ${y} message(s) from the DLQ to ${c}.`}}catch(n){return{operation:"dlq:redrive",ok:!1,error:pt(n?.message??String(n))}}}async function Hh(e,t){try{let r=await lt(e,t),n=new uo(r.region),i=await $u(n,r.slug,t);if(!i)return{operation:"dlq:purge",ok:!1,error:Nu};return await n.purgeQueue(i),{operation:"dlq:purge",command:"sqs purge dlq",ok:!0,stdout:"Dead-letter queue purged."}}catch(r){return{operation:"dlq:purge",ok:!1,error:pt(r?.message??String(r))}}}function Gh(e,t){let r=Ou(e,t);if(!r?.secrets)return[];return Array.isArray(r.secrets)?r.secrets.map((n)=>({key:n.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:n})):Object.entries(r.secrets).map(([n,i])=>({key:n,secretId:String(i)}))}async function Kh(e,t,r,n){if(!r.trim())return{operation:"secret:set",ok:!1,error:"A secret id is required."};try{let i=await lt(e,t),o=new co(i.region);try{await o.putSecretValue({SecretId:r,SecretString:n})}catch{await o.createSecret({Name:r,SecretString:n})}return{operation:"secret:set",command:`secret set ${r}`,ok:!0,stdout:`Secret ${r} updated. Redeploy to apply it to the functions.`}}catch(i){return{operation:"secret:set",ok:!1,error:pt(i?.message??String(i))}}}async function Qh(e,t,r){if(!r.trim())return{operation:"secret:delete",ok:!1,error:"A secret id is required."};try{let n=await lt(e,t);return await new co(n.region).deleteSecret({SecretId:r,RecoveryWindowInDays:7}),{operation:"secret:delete",command:`secret delete ${r}`,ok:!0,stdout:`Secret ${r} scheduled for deletion (recoverable for 7 days).`}}catch(n){return{operation:"secret:delete",ok:!1,error:pt(n?.message??String(n))}}}var lT=new Set(["http","queue","cli"]);async function Yh(e,t,r,n){if(!lT.has(r))return{operation:"function:config",ok:!1,error:`Unknown function mode '${r}'.`};let i=n.memory==null?void 0:Number(n.memory),o=n.timeout==null?void 0:Number(n.timeout);if(i!=null&&(!Number.isInteger(i)||i<128||i>10240))return{operation:"function:config",ok:!1,error:"Memory must be an integer between 128 and 10240 MB."};if(o!=null&&(!Number.isInteger(o)||o<1||o>900))return{operation:"function:config",ok:!1,error:"Timeout must be an integer between 1 and 900 seconds."};if(i==null&&o==null)return{operation:"function:config",ok:!1,error:"Provide a memory and/or timeout value."};try{let s=await lt(e,t),c=new Vs(s.region),u=`${s.slug}-${t}-${r}`;await c.updateFunctionConfiguration({FunctionName:u,...i!=null?{MemorySize:i}:{},...o!=null?{Timeout:o}:{}});let a=[i!=null?`${i} MB`:"",o!=null?`${o}s`:""].filter(Boolean).join(", ");return{operation:"function:config",command:`update ${u} (${a})`,ok:!0,stdout:`Updated ${u}: ${a}.`}}catch(s){return{operation:"function:config",ok:!1,error:pt(s?.message??String(s))}}}var Pu=[{key:"http-errors",label:"HTTP function errors",namespace:"AWS/Lambda",metricName:"Errors",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"errors / 5 min"},{key:"http-throttles",label:"HTTP function throttles",namespace:"AWS/Lambda",metricName:"Throttles",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"throttles / 5 min"},{key:"http-duration",label:"HTTP function duration (avg)",namespace:"AWS/Lambda",metricName:"Duration",statistic:"Average",comparison:"GreaterThanThreshold",fnMode:"http",unit:"ms"},{key:"http-concurrency",label:"HTTP concurrent executions",namespace:"AWS/Lambda",metricName:"ConcurrentExecutions",statistic:"Maximum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"concurrent"},{key:"queue-errors",label:"Queue function errors",namespace:"AWS/Lambda",metricName:"Errors",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"queue",unit:"errors / 5 min"}];function pT(e){return Pu.find((t)=>t.key===e)}async function Xh(e,t){try{let r=await lt(e,t);return{ok:!0,alarms:await new Ii(r.region).describeAlarms({AlarmNamePrefix:`${r.slug}-${t}-`,MaxRecords:100}),presets:Pu}}catch(r){return{ok:!1,alarms:[],presets:Pu,error:pt(r?.message??String(r))}}}async function Zh(e,t,r,n){let i=pT(r);if(!i)return{operation:"alarm:create",ok:!1,error:`Unknown alarm metric '${r}'.`};if(!Number.isFinite(n)||n<0)return{operation:"alarm:create",ok:!1,error:"Provide a non-negative threshold."};try{let o=await lt(e,t),s=new Ii(o.region),c=`${o.slug}-${t}-${i.key}`,u=i.fnMode?[{Name:"FunctionName",Value:`${o.slug}-${t}-${i.fnMode}`}]:[];return await s.putMetricAlarm({AlarmName:c,Namespace:i.namespace,MetricName:i.metricName,ComparisonOperator:i.comparison,Threshold:n,EvaluationPeriods:1,Period:300,Statistic:i.statistic,Dimensions:u,AlarmDescription:`ts-cloud: ${i.label} > ${n} ${i.unit}`}),{operation:"alarm:create",command:`alarm ${c}`,ok:!0,stdout:`Alarm ${c} armed at ${n} ${i.unit}.`}}catch(o){return{operation:"alarm:create",ok:!1,error:pt(o?.message??String(o))}}}async function ey(e,t,r){try{let n=await lt(e,t);if(!r.startsWith(`${n.slug}-${t}-`))return{operation:"alarm:delete",ok:!1,error:"Refusing to delete an alarm outside this environment."};return await new Ii(n.region).deleteAlarms([r]),{operation:"alarm:delete",command:`delete alarm ${r}`,ok:!0,stdout:`Alarm ${r} deleted.`}}catch(n){return{operation:"alarm:delete",ok:!1,error:pt(n?.message??String(n))}}}function gT(e){let t=e.HasFault?"fault":e.HasError?"error":e.HasThrottle?"throttle":"ok";return{id:String(e.Id??""),timestamp:Number.isFinite(Number(e.StartTime))?new Date(Number(e.StartTime)*1000).toISOString():void 0,durationMs:Math.round((e.Duration??0)*1000),responseMs:Math.round((e.ResponseTime??0)*1000),status:t,method:e.Http?.HttpMethod??"-",url:e.Http?.HttpURL??"-",httpStatus:e.Http?.HttpStatus??0}}async function pa(e,t,r=30){try{let n=await lt(e,t),i=new ku(n.region),o=new Date,s=new Date(o.getTime()-Math.min(360,Math.max(1,r))*60000),c=`${n.slug}-${t}-http`,u=await i.getTraceSummaries({startTime:s,endTime:o,filterExpression:`service("${c}")`});if(!u.summaries.length)u=await i.getTraceSummaries({startTime:s,endTime:o});return{ok:!0,traces:u.summaries.slice(0,100).map(gT)}}catch(n){return{ok:!1,traces:[],error:pt(n?.message??String(n))}}}async function Mu(e,t,r){try{let n=await lt(e,t),i=`${n.slug}-${t}-scheduler`;if(r==="run"){let s=await xu(e,t,"schedule:run");return{operation:"scheduler:run",command:"schedule:run",ok:!0,stdout:pt(s||"Scheduler run triggered.")}}let o=new Kd(n.region);if(r==="enable")await o.enableRule({Name:i});else await o.disableRule({Name:i});return{operation:`scheduler:${r}`,command:`${r} ${i}`,ok:!0,stdout:`Scheduler rule ${i} ${r}d.`}}catch(n){return{operation:`scheduler:${r}`,ok:!1,error:pt(n?.message??String(n))}}}function ty(e){let t=ga(e.name),r=Bu(e.configText);if(hT(e.configText,r.start,r.end,t))throw Error(`Site '${t}' already exists in cloud.config.ts`);let n=fT({...e,name:t}),i=e.configText.slice(0,r.end).trimEnd(),o=e.configText.slice(r.end),s=i.endsWith("{")?`
|
|
441
|
-
`:i.endsWith(",")?`
|
|
442
|
-
|
|
443
|
-
`:`,
|
|
444
|
-
|
|
445
|
-
`;return`${i}${s}${n}
|
|
446
|
-
${o}`}function ry(e){let t=ga(e.name),r=Bu(e.configText),n=dy(e.configText,r.start,r.end,t);if(!n)throw Error(`Site '${t}' does not exist in cloud.config.ts`);let i=e.configText,o=n.nameStart;while(o>0&&i[o-1]!==`
|
|
447
|
-
`&&/\s/.test(i[o-1]))o--;let s=n.end+1;if(i[s]===",")s++;while(s<i.length&&i[s]!==`
|
|
448
|
-
`&&/\s/.test(i[s]))s++;if(i[s]===`
|
|
449
|
-
`)s++;return i.slice(0,o)+i.slice(s)}function ny(e){let t=ga(e.siteName);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.key))throw Error(`Invalid property key '${e.key}'`);let r=Bu(e.configText),n=dy(e.configText,r.start,r.end,t);if(!n)throw Error(`Site '${t}' does not exist in cloud.config.ts`);let i=e.configText,o=i.indexOf("{",n.nameStart),s=n.end,c=i.slice(o+1,s),u=new RegExp(`(^|[\\s,{])(${ju(e.key)})\\s*:`,"m").exec(c);if(u){let f=o+1+u.index+u[1].length,y=i.indexOf(":",f),b=mT(i,y+1,s);return`${i.slice(0,f)}${e.key}: ${e.valueText}${i.slice(b)}`}let a=i.slice(0,s).trimEnd(),p=a.endsWith("{")||a.endsWith(",")?"":",";return`${a}${p}
|
|
450
|
-
${e.key}: ${e.valueText},
|
|
451
|
-
${i.slice(s)}`}function iy(e){if(e===!1)return"false";if(e===!0)return"true";return`{ provider: '${rn(e.provider||"letsencrypt")}' }`}function oy(e){return`'${rn(e)}'`}function sy(e){let t=Object.entries(e).filter(([r])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(r));if(t.length===0)return"{}";return`{
|
|
452
|
-
${t.map(([r,n])=>` ${r}: '${rn(String(n))}',`).join(`
|
|
453
|
-
`)}
|
|
454
|
-
}`}function Lu(e){return/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(e.trim())}function ay(e){let t=[...new Set(e.map((r)=>r.trim().toLowerCase()).filter(Boolean))];for(let r of t)if(!Lu(r))throw Error(`Alias '${r}' is not a valid hostname.`);if(t.length===0)return"[]";return`[${t.map((r)=>`'${rn(r)}'`).join(", ")}]`}function cy(e){let t=Object.entries(e).map(([r,n])=>[r.trim(),String(n).trim()]).filter(([r,n])=>r&&n);if(t.length===0)return"{}";return`{
|
|
455
|
-
${t.map(([r,n])=>` '${rn(r)}': '${rn(n)}',`).join(`
|
|
456
|
-
`)}
|
|
457
|
-
}`}function mT(e,t,r){let n=t;while(n<r&&/\s/.test(e[n]))n++;let i=0,o,s=!1;for(;n<r;n++){let c=e[n];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}if(c===o)o=void 0;continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="{"||c==="["||c==="("){i++;continue}if(c==="}"||c==="]"||c===")"){if(i===0)return n;i--;continue}if(c===","&&i===0)return n}return r}function dy(e,t,r,n){let i=e.slice(t+1,r),o=new RegExp(`(^|[\\s,{])(${ju(n)})\\s*:\\s*\\{`,"m").exec(i);if(!o)return null;let s=t+1+o.index+o[1].length,c=e.indexOf("{",s);return{nameStart:s,end:uy(e,c)}}function fT(e){let r=[` ${ga(e.name)}: {`];if(tn(r,"deploy",e.deploy),tn(r,"root",e.root),tn(r,"path",e.path),tn(r,"domain",e.domain),tn(r,"type",e.type),tn(r,"build",e.build),tn(r,"start",e.start),e.port!==void 0)r.push(` port: ${e.port},`);if(tn(r,"pathRewriteStyle",e.pathRewriteStyle),e.ssl!==void 0)if(e.ssl===!1)r.push(" ssl: false,");else if(e.ssl===!0)r.push(" ssl: true,");else r.push(` ssl: { provider: '${rn(e.ssl.provider||"letsencrypt")}' },`);if(e.env&&Object.keys(e.env).length>0){r.push(" env: {");for(let[n,i]of Object.entries(e.env)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))continue;r.push(` ${n}: '${rn(String(i))}',`)}r.push(" },")}return r.push(" },"),r.join(`
|
|
458
|
-
`)}function rn(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}function ga(e){let t=e.trim();if(!/^[A-Za-z_$][\w$]*$/.test(t))throw Error(`Invalid site name '${e}'. Use a valid JavaScript object key, e.g. docs or marketingSite.`);return t}function tn(e,t,r){if(r===void 0||r==="")return;let n=r.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'");e.push(` ${t}: '${n}',`)}function Bu(e){let t=/\bsites\s*:\s*{/g.exec(e);if(!t)throw Error("Could not find a top-level sites: { ... } block in cloud.config.ts");let r=e.indexOf("{",t.index),n=uy(e,r);return{start:r,end:n}}function hT(e,t,r,n){let i=e.slice(t+1,r);return new RegExp(`(^|[\\s,{])${ju(n)}\\s*:`,"m").test(i)}function ju(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uy(e,t){let r=0,n,i=!1,o=!1,s=!1;for(let c=t;c<e.length;c++){let u=e[c],a=e[c+1];if(o){if(u===`
|
|
459
|
-
`)o=!1;continue}if(s){if(u==="*"&&a==="/")s=!1,c++;continue}if(n){if(i){i=!1;continue}if(u==="\\"){i=!0;continue}if(u===n)n=void 0;continue}if(u==="/"&&a==="/"){o=!0,c++;continue}if(u==="/"&&a==="*"){s=!0,c++;continue}if(u==='"'||u==="'"||u==="`"){n=u;continue}if(u==="{")r++;if(u==="}"){if(r--,r===0)return c}}throw Error("Could not find the closing brace for sites: { ... } in cloud.config.ts")}function ly(e,t,r){let n=(Array.isArray(r)?r:String(r??"").split(",")).map(String).filter(Boolean);if(!n.length){if(t)return;let o=e.map((s)=>s.id);return o.length?o:["__no_authorized_telemetry_resources__"]}let i=n.map((o)=>e.find((s)=>s.id===o||s.slug===o)?.id).filter((o)=>!!o);if(i.length!==n.length)throw Error("One or more telemetry resources are outside your authorized scope.");return[...new Set(i)]}import{createHash as fy}from"node:crypto";function nn(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function yT(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;let t=Date.parse(`${e}T12:00:00.000Z`);return Number.isFinite(t)?new Date(t).toISOString():null}function bT(e,t){if(!e||typeof e!=="object")return[];let r={source:t.name},n=[],i=t.now,o=(a,p,f,y=i)=>{if(p!==null)n.push({name:a,value:p,unit:f,timestamp:y,attributes:r})};o("storage.egress.month",nn(e.monthBytes),"bytes"),o("storage.egress.today",nn(e.todayBytes),"bytes"),o("storage.egress.projected_month",nn(e.projectedMonthBytes),"bytes");let s=nn(e.budgetBytes);if(s!==null&&s>0){o("storage.egress.budget",s,"bytes");let a=e.budgetUsedPercent,p=typeof a==="number"&&Number.isFinite(a)?a:nn(e.monthBytes)!==null?Math.round(nn(e.monthBytes)/s*1000)/10:null;o("storage.egress.budget_used_percent",p,"percent")}let c=t.maxReplayDays??45,u=Array.isArray(e.days)?e.days.slice(-c):[];for(let a of u){let p=yT(String(a?.date??"")),f=nn(a?.bytes);if(!p||f===null)continue;n.push({name:"storage.egress.day",value:f,unit:"bytes",timestamp:p,attributes:r});let y=nn(a?.downloads);if(y!==null)n.push({name:"storage.egress.day_downloads",value:y,unit:"count",timestamp:p,attributes:r})}return n}async function ST(e,t=process.env,r=fetch){let n=e.tokenEnv?t[e.tokenEnv]:void 0,i=await r(e.url,{headers:n?{Authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(1e4)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function py(e,t){let r=[],n=[];if(!Array.isArray(e)||e.length===0)return{metrics:r,errors:n};let i=await Promise.all(e.map(async(o)=>{if(!o?.name||!o?.url)return{endpoint:o,error:"egress endpoint needs both a name and a url"};try{let s=await ST(o,t.env,t.fetchImpl);return{endpoint:o,report:s}}catch(s){return{endpoint:o,error:s instanceof Error?s.message:String(s)}}}));for(let o of i){let s=`egress:${o.endpoint?.name??"unnamed"}`;if("error"in o&&o.error){n.push({source:s,message:o.error});continue}r.push(...bT(o.report,{name:o.endpoint.name,now:t.now}))}return{metrics:r,errors:n}}class hy{now;entries=new Map;constructor(e=Date.now){this.now=e}async getOrCreate(e,t,r,n){let i=this.entries.get(e);if(!r&&i&&i.expiresAt>this.now())return{value:await i.promise,cached:!0};let o=n().catch((s)=>{throw this.entries.delete(e),s});return this.entries.set(e,{expiresAt:this.now()+t,promise:o}),{value:await o,cached:!1}}invalidate(e){for(let t of this.entries.keys())if(t.startsWith(e))this.entries.delete(t)}}class yy{now;lastRun=new Map;constructor(e=Date.now){this.now=e}shouldRun(e,t,r=!1){let n=this.now(),i=this.lastRun.get(e);if(!r&&i!=null&&n-i<t)return!1;return this.lastRun.set(e,n),!0}}var by=new hy,vT=new yy,wT=2000,IT=3600000;function CT(e,t){if(e.kind==="log"&&!t.collectLogs)return!1;if(e.kind==="trace"&&!t.collectTraces)return!1;if((e.kind==="request"||e.name.startsWith("request."))&&!t.collectRequestAnalytics)return!1;if(!["log","trace","request"].includes(e.kind)&&!e.name.startsWith("request."))return!0;let r=e.requestId??e.traceId??`${e.source}\x00${e.workloadId??""}\x00${e.timestamp}`;return Number.parseInt(fy("sha256").update(r).digest("hex").slice(0,8),16)/4294967295<=t.samplingRate}function gt(...e){return`telemetry:${fy("sha256").update(e.map((t)=>String(t??"")).join("\x00")).digest("hex").slice(0,40)}`}function lo(e,t,r,n){if(!n)return;return e.listResources(t,r).find((i)=>i.slug===n)?.id}function ET(e,t){let r=String(t??"").toLowerCase();if(["debug","info","warn","warning","error","fatal"].includes(r))return r==="fatal"?"error":r;return/fatal|panic|exception|error/i.test(e)?"error":/warn|timeout|throttl|retr(?:y|ies)/i.test(e)?"warning":"info"}function gy(e){let t=e.timestamp&&Number.isFinite(new Date(e.timestamp).getTime())?new Date(e.timestamp).toISOString():new Date().toISOString(),r={};try{let T=JSON.parse(e.message);if(T&&typeof T==="object"&&!Array.isArray(T))r=T}catch{}let n=Object.fromEntries(Object.entries(r).filter(([T])=>!/^(?:body|requestBody|responseBody|headers|authorization|cookie|cookies|query|queryString)$/i.test(T))),i=String(r.requestId??r.request_id??r["x-request-id"]??"")||void 0,o=String(r.traceId??r.trace_id??r["x-amzn-trace-id"]??"")||void 0,s=Number(r.durationMs??r.duration_ms??r.latencyMs??r.latency_ms),c=Number(r.statusCode??r.status_code??r.status),u=String(r.method??r.httpMethod??"")||void 0,a=my(String(r.pathTemplate??r.path??r.url??"")||void 0),p=String(r.releaseId??r.release_id??"")||void 0,f=String(r.deploymentId??r.deployment_id??"")||void 0,y={projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,source:e.source,timestamp:t,requestId:i,traceId:o,releaseId:p,deploymentId:f,workloadId:e.workloadId},b=Object.keys(r).length?JSON.stringify(n):e.message,C=[{...y,id:gt(e.source,e.name,t,b),kind:"log",name:e.name,level:ET(b,r.level),message:b,attributes:n}];if(u&&a&&Number.isFinite(c)){if(C.push({...y,id:gt("request",i,t,u,a,c),kind:"request",name:"http.request",method:u,pathTemplate:a,host:r.host,statusCode:c,durationMs:Number.isFinite(s)?s:void 0,bytesIn:Number(r.bytesIn)||void 0,bytesOut:Number(r.bytesOut)||void 0,region:r.region,cacheResult:r.cacheResult??r.cache,upstream:r.upstream,attributes:{userAgentFamily:r.userAgentFamily??"",protocol:r.protocol??""}}),Number.isFinite(s))C.push({...y,id:gt("request-duration",i,t),kind:"metric",name:"request.duration",value:s,unit:"ms",attributes:{method:u,pathTemplate:a,statusCode:c}});if(C.push({...y,id:gt("request-count",i,t),kind:"metric",name:"request.count",value:1,unit:"count",attributes:{method:u,pathTemplate:a,statusCode:c}}),c>=500)C.push({...y,id:gt("request-error",i,t),kind:"metric",name:"request.error",value:1,unit:"count",attributes:{method:u,pathTemplate:a,statusCode:c}})}return C}async function TT(e){let t=new ma(e.controlPlane),r=po(e.controlPlane,e.projectId),n=new Date,i=[],o=[],s={projectId:e.projectId,environmentId:e.environmentId},c=Pr(e.config);try{let y=(c==="serverless"?await fa(e.config,e.environment):await ha(e.config,e.environment,{includeSiteHealth:e.includeSiteHealth,telemetryOnly:e.lightweight}))??{};if(c==="serverless"){for(let C of y.functionsDetail??[]){let T=lo(e.controlPlane,e.projectId,e.environmentId,C.key),R={...s,resourceId:T,source:"cloudwatch",timestamp:n.toISOString(),workloadId:C.name,attributes:{provider:"aws",functionName:C.name,aggregationWindow:"24h"}};for(let[x,L,P]of[["snapshot.traffic.requests_24h",C.invocations,"count"],["snapshot.errors.count_24h",C.errors,"count"],["snapshot.latency.p50_24h",C.p50,"ms"],["snapshot.latency.p95_24h",C.p95,"ms"],["snapshot.latency.p99_24h",C.p99,"ms"],["snapshot.saturation.throttles_24h",C.throttles,"count"],["snapshot.memory.max_24h",C.maxMem,"MB"]])if(Number.isFinite(Number(L)))i.push({...R,id:gt("cloudwatch",C.name,x,n.toISOString()),kind:"metric",name:x,value:Number(L),unit:P})}try{let C=await lt(e.config,e.environment),T=new Ii(C.region),R=new Date(n.getTime()-3600000),x=300;for(let L of C.functions){let P=[{Name:"FunctionName",Value:L.name}],[G,ae,Z,Le,ue]=await Promise.all([T.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:P,StartTime:R,EndTime:n,Period:300,Statistics:["Sum"]}),T.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Errors",Dimensions:P,StartTime:R,EndTime:n,Period:300,Statistics:["Sum"]}),T.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:P,StartTime:R,EndTime:n,Period:300,ExtendedStatistics:["p50","p95","p99"]}),T.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Throttles",Dimensions:P,StartTime:R,EndTime:n,Period:300,Statistics:["Sum"]}),T.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"ConcurrentExecutions",Dimensions:P,StartTime:R,EndTime:n,Period:300,Statistics:["Maximum"]})]),W=lo(e.controlPlane,e.projectId,e.environmentId,L.mode),ie=(Ce,Yt,Nr,jt)=>{for(let Xt of Ce){let Zt=Xt.Timestamp&&Number.isFinite(new Date(Xt.Timestamp).getTime())?new Date(Xt.Timestamp).toISOString():void 0,er=Nr(Xt);if(Zt&&er!=null&&Number.isFinite(er))i.push({...s,resourceId:W,id:gt("cloudwatch-series",L.name,Yt,Zt),kind:"metric",source:"cloudwatch",name:Yt,timestamp:Zt,value:er,unit:jt,workloadId:L.name,region:C.region,attributes:{provider:"aws",functionName:L.name,aggregationWindow:"300s"}})}};ie(G,"traffic.requests",(Ce)=>Ce.Sum,"count"),ie(ae,"errors.count",(Ce)=>Ce.Sum,"count"),ie(Z,"latency.p50",(Ce)=>Ce.Percentiles?.p50,"ms"),ie(Z,"latency.p95",(Ce)=>Ce.Percentiles?.p95,"ms"),ie(Z,"latency.p99",(Ce)=>Ce.Percentiles?.p99,"ms"),ie(Le,"saturation.throttles",(Ce)=>Ce.Sum,"count"),ie(ue,"saturation.concurrency",(Ce)=>Ce.Maximum,"count")}}catch(C){o.push({source:"cloudwatch:series",message:C instanceof Error?C.message:String(C)})}for(let C of(y.serverlessLogs??[]).slice(0,wT))i.push(...gy({...s,source:`cloudwatch:${C.source}`,name:`${C.source}.log`,timestamp:C.timestamp,message:String(C.message),resourceId:lo(e.controlPlane,e.projectId,e.environmentId,C.source)}));for(let C of y.queuesDetail??[]){let T={...s,source:"cloudwatch",timestamp:n.toISOString(),attributes:{queue:C.name}};i.push({...T,id:gt("queue-depth",C.name,n.toISOString()),kind:"metric",name:"queue.depth",value:Number(C.visible??C.depth??0),unit:"count"}),i.push({...T,id:gt("queue-inflight",C.name,n.toISOString()),kind:"metric",name:"queue.inflight",value:Number(C.inFlight??0),unit:"count"})}let b=await pa(e.config,e.environment,30);if(!b.ok)o.push({source:"xray",message:b.error??"X-Ray traces are unavailable."});for(let C of b.traces)i.push({...s,id:gt("xray",C.id),kind:"trace",source:"xray",name:"http.trace",timestamp:C.timestamp??n.toISOString(),traceId:C.id,durationMs:C.durationMs,statusCode:C.httpStatus,method:C.method,pathTemplate:C.url,attributes:{status:C.status,responseMs:C.responseMs}})}else{let b=y.systemMetrics;if(y.metricsUnavailable||!b)o.push({source:"host",message:"The host metrics probe is unavailable."});else{let C=Number(b.memTotalMb)>0?Number(b.memUsedMb)/Number(b.memTotalMb)*100:0,T=Number(b.swapTotalMb)>0?Number(b.swapUsedMb)/Number(b.swapTotalMb)*100:0,R=[["host.load",Number(b.load),"load"],["host.load.5m",Number(b.load5),"load"],["host.load.15m",Number(b.load15),"load"],["host.cpu.capacity",Number(b.cpus),"count"],["host.cpu.used_percent",Number(b.cpuUsedPct),"percent"],["host.memory.used",Number(b.memUsedMb)*1024*1024,"bytes"],["host.memory.total",Number(b.memTotalMb)*1024*1024,"bytes"],["host.memory.available",Number(b.memAvailableMb)*1024*1024,"bytes"],["host.memory.cache",Number(b.memCacheMb)*1024*1024,"bytes"],["host.memory.used_percent",C,"percent"],["host.swap.used",Number(b.swapUsedMb)*1024*1024,"bytes"],["host.swap.total",Number(b.swapTotalMb)*1024*1024,"bytes"],["host.swap.used_percent",T,"percent"],["host.disk.used_percent",Number(b.diskUsedPct),"percent"],["host.disk.used",Number(b.diskUsedGb)*1073741824,"bytes"],["host.disk.total",Number(b.diskTotalGb)*1073741824,"bytes"],["host.disk.inode_used_percent",Number(b.inodeUsedPct),"percent"],["host.network.rx",Number(b.networkRxBytes),"bytes"],["host.network.tx",Number(b.networkTxBytes),"bytes"],["host.network.rx_rate",Number(b.networkRxBytesPerSec),"bytes_per_second"],["host.network.tx_rate",Number(b.networkTxBytesPerSec),"bytes_per_second"],["host.network.rx_today",Number(b.networkRxBytesToday),"bytes"],["host.network.tx_today",Number(b.networkTxBytesToday),"bytes"],["host.network.rx_month",Number(b.networkRxBytesMonth),"bytes"],["host.network.tx_month",Number(b.networkTxBytesMonth),"bytes"],["host.processes",Number(b.processes),"count"],["host.uptime",Number(b.uptimeSeconds),"seconds"]];for(let[x,L,P]of R)if(Number.isFinite(L))i.push({...s,id:gt("host",x,n.toISOString()),kind:"metric",source:"host",name:x,timestamp:n.toISOString(),value:L,unit:P});for(let x of y.siteHealth??[]){let L=String(x.project??e.config.project.slug),P=String(x.name),G=P.startsWith(`${L}:`)?P.slice(L.length+1):P,ae=`site:${L}:${G}`,Z=lo(e.controlPlane,e.projectId,e.environmentId,P),Le={...s,resourceId:Z,source:ae,timestamp:x.checkedAt||n.toISOString(),host:x.route,attributes:{project:L,site:G,route:String(x.route),status:String(x.status)}},ue=[["site.health.up",x.status==="live"?1:0,"boolean"],["site.http.status",Number(x.httpStatus),"status"],["site.response.time",Number(x.responseMs),"ms"]];if(x.tlsDaysRemaining!=null)ue.push(["site.tls.days_remaining",Number(x.tlsDaysRemaining),"days"]);for(let[W,ie,Ce]of ue)if(Number.isFinite(ie))i.push({...Le,id:gt(ae,W,Le.timestamp),kind:"metric",name:W,value:ie,unit:Ce})}}}}catch(y){o.push({source:c==="serverless"?"aws":"host",message:y instanceof Error?y.message:String(y)})}{let y=e.config.infrastructure?.compute?.monitoring,b=typeof y==="object"?y?.egressEndpoints:void 0,C=await py(b,{now:n.toISOString()});o.push(...C.errors);for(let T of C.metrics)i.push({...s,id:gt(T.attributes.source,T.name,T.timestamp),kind:"metric",source:`egress:${T.attributes.source}`,name:T.name,timestamp:T.timestamp,value:T.value,unit:T.unit,attributes:T.attributes})}if(!e.lightweight)try{let y=await Ht(e.config,e.environment),b=new cr(e.config,e.environment,{inventory:async()=>y});for(let C of y.workloads){let T=lo(e.controlPlane,e.projectId,e.environmentId,C.links.service),R={...s,resourceId:T,source:`runtime:${C.provider}`,timestamp:n.toISOString(),workloadId:C.id,releaseId:C.links.release,attributes:{status:C.status,provider:C.provider,service:C.links.service??""}};if(i.push({...R,id:gt(C.id,"health",n.toISOString()),kind:"metric",name:"health.up",value:C.status==="running"?1:0,unit:"boolean"}),i.push({...R,id:gt(C.id,"restarts",n.toISOString()),kind:"metric",name:"saturation.restarts",value:C.restartCount??0,unit:"count"}),C.resources?.memoryBytes!=null)i.push({...R,id:gt(C.id,"memory",n.toISOString()),kind:"metric",name:"runtime.memory.used",value:C.resources.memoryBytes,unit:"bytes"});if(!C.capabilities.logs.supported)continue;try{let x=await b.logs(C.id,{limit:100,since:new Date(n.getTime()-300000)});for(let L of x.lines)i.push(...gy({...s,resourceId:T,source:`runtime:${C.provider}`,name:`${C.links.service??C.name}.log`,timestamp:L.timestamp,message:L.message,workloadId:C.id}))}catch(x){o.push({source:`runtime:${C.provider}`,message:x instanceof Error?x.message:String(x)})}}for(let C of y.sources.filter((T)=>T.status!=="fresh"))o.push({source:C.id,message:C.message??`Runtime source is ${C.status}.`})}catch(y){o.push({source:"runtime",message:y instanceof Error?y.message:String(y)})}if(!e.lightweight)for(let y of e.controlPlane.listEvents({projectId:e.projectId,limit:1000})){let b=y.payload;i.push({...s,id:`telemetry:event:${y.id}`,resourceId:y.resourceId,kind:"event",source:"control-plane",name:y.type,timestamp:y.createdAt,level:y.level,message:y.type,deploymentId:y.operationId,releaseId:typeof b.releaseId==="string"?b.releaseId:void 0,traceId:y.correlationId,attributes:b})}let u=i.filter((y)=>CT(y,r)).map((y)=>({...y,sampled:r.samplingRate<1&&(y.kind==="log"||y.kind==="trace"||y.kind==="request"||y.name.startsWith("request."))})),a=t.appendMany(u).length;if(vT.shouldRun(e.projectId,IT,!e.lightweight))t.enforceRetention(r,e.projectId);let p=t.status(e.projectId,e.environmentId,r.rawDays,r.samplingRate);for(let y of o)if(!p.some((b)=>b.source===y.source))p.push({source:y.source,freshness:"unavailable",samplingRate:r.samplingRate,retentionDays:r.rawDays,estimatedDailyBytes:0,message:y.message});let f=n.toISOString();return e.controlPlane.setSetting(`telemetry.collection:${e.projectId}:${e.environmentId??"all"}`,{generatedAt:f,errors:o,statuses:p,policy:r}),{collected:a,cached:!1,generatedAt:f,statuses:p,errors:o,policy:r}}async function Fu(e){let r=`${`${e.projectId}:${e.environmentId??"all"}:${e.environment}`}:${e.lightweight?"lightweight":"full"}`,n=Pr(e.config)==="serverless"?300000:60000,i=await by.getOrCreate(r,n,!!e.force,()=>TT(e));return{...i.value,cached:i.cached}}function Sy(e){by.invalidate(`${e}:`)}function vy(e,t={}){let r=t.shell||(process.platform==="win32"?"powershell.exe":"bash"),n=Bun.spawn([r,"-i"],{stdin:"pipe",stdout:"pipe",stderr:"pipe",cwd:t.cwd,env:{...process.env,TERM:"xterm-256color",PS1:"\\w $ "}}),i=new TextDecoder,o=async(s)=>{if(!s)return;let c=s.getReader();try{for(;;){let{done:u,value:a}=await c.read();if(u)break;if(a)e(i.decode(a))}}catch{}};if(o(n.stdout),o(n.stderr),t.onExit)n.exited.then((s)=>t.onExit(s)).catch(()=>{});return{write(s){try{n.stdin.write(s),n.stdin.flush()}catch{}},close(){try{n.stdin.end()}catch{}try{n.kill()}catch{}}}}var _T="127.0.0.1",NT=7676,Iy=65536,cb="ts-cloud-dashboard-",Ti=kT(OT(import.meta.url));function $T(e){try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function MT(e=Sa(),t=$T){let r=0;for(let n of wy(e,{withFileTypes:!0})){if(!n.isDirectory()||!n.name.startsWith(cb))continue;let i=Ie(e,n.name),o=n.name.match(/^ts-cloud-dashboard-(\d+)-/);if(o){let s=Number(o[1]);if(s===process.pid||t(s))continue}else if(wy(i).length>0)continue;Ln(i,{recursive:!0,force:!0}),r+=1}return r}var LT={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".ico":"image/x-icon"};function g(e,t=200,r={}){return new Response(JSON.stringify(e,null,2),{status:t,headers:{"content-type":"application/json; charset=utf-8",...r}})}function BT(e,t,r,n){let i=new TextEncoder,o=Math.max(0,Math.floor(r)),s,c,u=!1,a=new ReadableStream({start(p){let f=()=>{if(u)return;if(u=!0,s?.(),c)clearInterval(c);n.removeEventListener("abort",f);try{p.close()}catch{}},y=(C)=>{if(u)return;if(C.reset)p.enqueue(i.encode(`event: reset
|
|
460
|
-
data: ${JSON.stringify({cursor:C.cursor,droppedBytes:C.droppedBytes})}
|
|
461
|
-
|
|
462
|
-
`));for(let T of C.chunks.filter((R)=>R.cursor>o))o=T.cursor,p.enqueue(i.encode(`id: ${T.cursor}
|
|
463
|
-
event: ${T.stream}
|
|
464
|
-
data: ${JSON.stringify(T)}
|
|
465
|
-
|
|
466
|
-
`));if(C.state!=="open")p.enqueue(i.encode(`event: state
|
|
467
|
-
data: ${JSON.stringify({state:C.state,error:C.error,cursor:C.cursor})}
|
|
468
|
-
|
|
469
|
-
`)),f()};s=e.subscribe(t.id,t.workloadId,(C)=>y(e.read(C.id,C.workloadId,o)??C));let b=e.read(t.id,t.workloadId,o);if(!b)return f();if(y(b),u)return;c=setInterval(()=>{if(!u)p.enqueue(i.encode(`event: heartbeat
|
|
470
|
-
data: ${JSON.stringify({cursor:o,at:new Date().toISOString()})}
|
|
471
|
-
|
|
472
|
-
`))},15000),c.unref?.(),n.addEventListener("abort",f,{once:!0})},cancel(){if(u=!0,s?.(),c)clearInterval(c)}});return new Response(a,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}var jT=new Set(["action","operation","site","name","username","database","secretId","port","key","resourceId","environmentId"]);function FT(e,t,r,n,i){let o={};if(r&&typeof r==="object"&&!Array.isArray(r))for(let[c,u]of Object.entries(r)){if(!jT.has(c)||!["string","number","boolean"].includes(typeof u))continue;o[c]=typeof u==="string"?u.slice(0,256):u}let s=String(o.resourceId||o.site||o.secretId||o.database||o.name||t);return{method:e.toUpperCase(),path:t,target:s,status:n,outcome:n<400?"succeeded":"failed",durationMs:Math.max(0,Math.round(i)),input:o}}var UT=en("ts-cloud-dummy-password");function va(e,t=200){return new Response(e,{status:t,headers:{"content-type":"text/plain; charset=utf-8"}})}function zT(e,t,r=process.env){let n=r.TS_CLOUD_DASHBOARD_ORIGIN?.trim()||(r.TS_CLOUD_UI_DOMAIN?.trim()?`https://${r.TS_CLOUD_UI_DOMAIN.trim().replace(/^https?:\/\//,"")}`:""),i=["0.0.0.0","::"].includes(e)?void 0:e,o=n||(i&&["127.0.0.1","localhost","::1"].includes(i)?`http://${i.includes(":")?`[${i}]`:i}:${t}`:"");if(!o)return;try{let s=new URL(o),c=["127.0.0.1","localhost","::1"].includes(s.hostname);if(s.protocol!=="https:"&&!(s.protocol==="http:"&&c)||s.username||s.password||s.search||s.hash||s.pathname!=="/"&&s.pathname!=="")return;return s.origin}catch{return}}function VT(e,t){if(t&&Object.hasOwn(e.environments??{},t))return t;return Object.keys(e.environments??{})[0]??"production"}function qT(e,t,r){return r&&e.includes(r)?r:t}function Cy(e,t,r){return e==null||t-e>=r}async function JT(e){let t=[Ie(Ti,"..","..","..","..",".env"),Ie(e,".env"),Ie(e,".env.local"),Ie(e,".env.production")];for(let r of t){if(!_r(r))continue;let n=await ur(r,"utf8").catch(()=>"");for(let i of n.split(`
|
|
473
|
-
`)){let o=i.trim();if(!o||o.startsWith("#")||!o.includes("="))continue;let s=o.indexOf("="),c=o.slice(0,s).trim(),u=o.slice(s+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(c)||process.env[c]!=null)continue;if(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))u=u.slice(1,-1);process.env[c]=u}}}function WT(e){return[Ie(e,"config","cloud.ts"),Ie(e,"config","cloud.js"),Ie(e,"cloud.config.ts"),Ie(e,"cloud.config.js")].find((r)=>_r(r))??null}function Ai(e){return e.infrastructure?.compute?.sshKeys??[]}function Ey(e,t){let r=e.infrastructure??(e.infrastructure={}),n=r.compute??(r.compute={});n.sshKeys=t}function HT(e,t,r){let n=e.sites??(e.sites={});n[t]=r}function Uu(e){return Nn(e.infrastructure?.compute?.firewall?.allowedPorts??[])}function Ty(e,t){let r=e.infrastructure??(e.infrastructure={}),n=r.compute??(r.compute={}),i=n.firewall??(n.firewall={});i.allowedPorts=t}async function D(e){return await e.json().catch(()=>({}))}function Ci(e,t){let r=String(e.scopeType??"environment");if(!["project","environment","service","function","preview"].includes(r))throw Error("Configuration scopeType must be project, environment, service, function, or preview.");let n=String(e.scopeId??(r==="project"?t.projectId:r==="environment"?t.environmentId??"":""));if(!n)throw Error("Configuration scopeId is required.");if(r==="project")return{type:r,id:n};if(r==="environment")return{type:r,id:n,environmentId:n};if(r==="service"||r==="function")return{type:r,id:n,environmentId:String(e.environmentId??t.environmentId??"")||void 0,resourceId:n};return{type:r,id:n,environmentId:String(e.environmentId??t.environmentId??"")||void 0,resourceId:String(e.resourceId??"")||void 0,previewId:n}}function GT(e){if(["GET","HEAD","OPTIONS"].includes(e.method.toUpperCase()))return!0;let t=e.headers.get("sec-fetch-site");if(t==="cross-site")return!1;let r=e.headers.get("origin");if(!r)return!0;let n=new URL(e.url);if(r===n.origin)return!0;if(t!=="same-origin")return!1;try{let i=new URL(r),o=(e.headers.get("x-forwarded-host")??e.headers.get("host")??n.host).split(",")[0].trim(),s=e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();if(!/^[A-Za-z0-9.-]+(?::\d{1,5})?$/.test(o)||i.host!==o)return!1;return!s||i.protocol===`${s}:`}catch{return!1}}var KT=new Set(["owner","admin","deployer","operator","viewer","auditor"]),QT=new Set(["organization","project","environment","resource"]),YT=new Set(["POST /api/organization/invitations","DELETE /api/organization/invitations","POST /api/organization/invitations/resend","PATCH /api/organization/memberships","DELETE /api/organization/memberships","POST /api/organization/grants","DELETE /api/organization/grants","POST /api/auth/oidc/providers","PATCH /api/auth/oidc/providers","POST /api/automation/service-accounts","PATCH /api/automation/service-accounts","POST /api/automation/tokens","POST /api/automation/tokens/rotate","DELETE /api/automation/tokens","POST /api/security/policies","PATCH /api/security/policies","POST /api/security/waivers","DELETE /api/security/waivers","POST /api/sources/connections","PATCH /api/sources/connections","DELETE /api/sources/connections","POST /api/sources/deploy-keys","DELETE /api/sources/deploy-keys","PATCH /api/telemetry/settings","POST /api/health/checks","PATCH /api/health/checks","POST /api/alerts/rules","PATCH /api/alerts/rules","POST /api/alerts/silences","POST /api/spend/budgets","PATCH /api/spend/budgets","DELETE /api/spend/budgets","POST /api/spend/check","POST /api/spend/release","POST /api/spend/anomalies/acknowledge","POST /api/protection/attack-mode","POST /api/protection/pause","POST /api/protection/ip-rules","DELETE /api/protection/ip-rules","POST /api/notifications/channels","PATCH /api/notifications/channels","POST /api/notifications/routes","PATCH /api/notifications/routes","POST /api/jobs","PATCH /api/jobs","POST /api/jobs/reconcile","POST /api/workers/action","POST /api/data-services","POST /api/data-services/action","POST /api/data-services/dependencies","POST /api/data-services/management","POST /api/data-services/reveal","POST /api/backups/destinations","POST /api/backups/destinations/test","POST /api/backups/policies","POST /api/backups/run","POST /api/backups/verify","POST /api/backups/restore","POST /api/backups/recovery-points","POST /api/backups/retention","POST /api/configuration/reveal","POST /api/configuration/transfer","POST /api/configuration/bulk","DELETE /api/configuration","POST /api/volumes","POST /api/volumes/attach","POST /api/volumes/detach","POST /api/volumes/resize","POST /api/volumes/snapshot","POST /api/volumes/restore","POST /api/volumes/adopt","POST /api/volumes/discover","DELETE /api/volumes","POST /api/fleet","POST /api/fleet/action","POST /api/capacity","POST /api/capacity/member","POST /api/capacity/action","POST /api/capacity/explain","POST /api/regions","POST /api/regions/action","POST /api/maintenance/cleanup-preview","POST /api/maintenance/cleanup-apply","POST /api/maintenance/drill","POST /api/maintenance/drill-run","POST /api/sources/webhooks","PATCH /api/sources/webhooks","DELETE /api/sources/webhooks","POST /api/onboarding/registries","PATCH /api/onboarding/registries","DELETE /api/onboarding/registries","POST /api/runtime/exec-sessions","POST /api/runtime/files/read","POST /api/runtime/files/write","POST /api/onboarding/apply","PATCH /api/queue/settings","DELETE /api/queue/history","POST /api/serverless/secrets","DELETE /api/serverless/secrets"]);function ya(e){let t=String(e??"");return KT.has(t)?t:void 0}function go(e){let t=String(e.scopeType??"organization");if(!QT.has(t))return;if(t==="organization")return{type:"organization"};let r=String(e.scopeId??"").trim();return r?{type:t,id:r}:void 0}async function Mn(e,t,r={}){let n=Pr(e),i={mode:n,environment:t,environments:Object.keys(e.environments??{}),project:{name:e.project.name,slug:e.project.slug,region:e.project.region}};try{return{...(n==="serverless"?await fa(e,t):await ha(e,t,{includeSiteHealth:r.includeSiteHealth}))??{},...i}}catch{return{...i}}}function XT(e,t){if(!e)return t;let r={...t,...Array.isArray(e.sites)?{sites:e.sites}:{},...Array.isArray(e.sitesDetail)?{sitesDetail:e.sitesDetail}:{},...Array.isArray(e.siteHealth)?{siteHealth:e.siteHealth}:{}};if(r.mode!=="serverless"&&Array.isArray(r.sites))r.topology=nb(r,{project:r.project?.name,environment:r.environment});return r}function ZT(e){let t=[Ie(e,"packages","ui"),Ie(Ti,"..","..","..","ui"),Ie(Ti,"..","..","ui"),Ie(Ti,"..","ui-src"),Ie(Ti,"..","..","ui-src"),Ie(Ti,"..","..","dist","ui-src")];for(let r of t)if(_r(Ie(r,"pages"))&&_r(Ie(r,"package.json")))return r;return null}async function eA(e,t){let r=ZT(e);if(!r)return null;let n;try{n=Vu(Ie(Sa(),`${cb}${process.pid}-`));let i=Ie(r,"node_modules",".bin","stx"),o=_r(i)?[i,"build","--pages","pages","--out",n,"--no-sitemap","--no-cache"]:["bunx","--bun","@stacksjs/stx","build","--pages","pages","--out",n,"--no-sitemap","--no-cache"],s=Bun.spawn(o,{cwd:r,stdout:"pipe",stderr:"pipe",env:{...process.env,TSCLOUD_DASHBOARD_DATA:sb(t)}}),[c,u,a]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]);if(a!==0){if(Ln(n,{recursive:!0,force:!0}),process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build failed; serving the pre-built UI.
|
|
474
|
-
${c}
|
|
475
|
-
${u}`);return null}return n}catch(i){if(n)Ln(n,{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 tA(e){let t=e.infrastructure?.compute?.managedServices?JSON.parse(JSON.stringify(e.infrastructure.compute.managedServices)):void 0;if(t?.vitess?.password)t.vitess.password="";return{project:{name:e.project?.name,slug:e.project?.slug,region:e.project?.region},provider:e.provider,environments:Object.keys(e.environments??{}),compute:e.infrastructure?.compute?{provider:e.infrastructure.compute.provider,runtime:e.infrastructure.compute.runtime,webServer:e.infrastructure.compute.webServer,proxy:e.infrastructure.compute.proxy?{engine:e.infrastructure.compute.proxy.engine,onDemandTls:e.infrastructure.compute.proxy.onDemandTls,cdn:!!e.infrastructure.compute.proxy.cdn}:void 0,managedServices:t,sshKeys:fo(Ai(e)).map((r)=>({name:r.name,type:r.type,fingerprint:r.fingerprint,added:r.added}))}:void 0,sites:Object.fromEntries(Object.entries(e.sites??{}).map(([r,n])=>[r,{domain:n.domain,path:n.path,type:n.type,deploy:n.deploy,root:n.root,port:n.port,ssl:n.ssl}]))}}function db(e){return[{id:"status",label:"Refresh Cloud Status",description:"Runs the local ts-cloud status checks against configured providers.",command:["status","--env",e],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",e,"--yes"],mutates:!0,confirm:"deploy"}]}function rA(e,t){return db(t).find((r)=>r.id===e)}function Ay(e){if(e.length<=Iy)return e;return`${e.slice(0,Iy)}
|
|
476
|
-
|
|
477
|
-
[output truncated]`}async function ky(e,t,r){let n=e.getReader(),i=new TextDecoder,o="";while(!0){let{done:c,value:u}=await n.read();if(c)break;let a=i.decode(u,{stream:!0});if(o+=a,a)r?.(t,a)}let s=i.decode();if(s)o+=s,r?.(t,s);return o}async function zu(e,t){let r=Bun.spawn([process.execPath,t.cliEntry,...e.command],{cwd:t.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,...t.env}}),n=()=>{try{r.kill()}catch{}};if(t.signal?.aborted)n();else t.signal?.addEventListener("abort",n,{once:!0});try{let[i,o,s]=await Promise.all([ky(r.stdout,"stdout",t.onOutput),ky(r.stderr,"stderr",t.onOutput),r.exited]);return{action:e.id,command:["cloud",...e.command].join(" "),exitCode:s,ok:s===0,stdout:Ay(i),stderr:Ay(o)}}finally{t.signal?.removeEventListener("abort",n)}}function nA(){return Object.entries(process.env).filter(([e,t])=>!!t&&t.length>=8&&/(?:secret|token|password|passwd|private|credential|api.?key|access.?key)/i.test(e)).map(([,e])=>e)}var iA=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 oA(e){let t=ho(e);if(t&&t!==".html")return!1;let r=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/")return!1;return!iA.has(r)}var sA={"/":"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 Ry(e,t){if(t.role==="admin")return!0;let r=ho(e);if(r&&r!==".html")return!0;if(t.organizationSource==="legacy")return!oA(e);let n=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/access-denied")return!0;let i=sA[n];return!!i&&!!t.capabilities?.includes(i)}function aA(e,t){let r=decodeURIComponent(t).replace(/^\/+/,""),i=RT(r===""?"index.html":r);if(i.startsWith("..")||i.includes("/../"))return null;let o=Ie(e,i);if(_r(o)&&!ab(o).isDirectory())return o;if(!ho(o)&&_r(`${o}.html`))return`${o}.html`;if(!ho(o)&&_r(Ie(o,"index.html")))return Ie(o,"index.html");return null}async function Py(e,t){let r=aA(e,t);if(!r){let o=Ie(e,"404.html");if(_r(o))return new Response(await ur(o),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return va("Not found",404)}if(ab(r).isDirectory())return va("Not found",404);let n=await ur(r),i=LT[ho(r)]??"application/octet-stream";return new Response(n,{headers:{"content-type":i}})}var ba=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],xy=new WeakMap;async function Dy(e){let t=xy.get(e);if(t)return t;let r=await import("./chunk-grepda40.js"),n=new r.SpendStore(e),i={store:n,service:new r.SpendService(n),gate:new r.SpendGate(e)};return xy.set(e,i),i}async function kB(e={}){MT();let t=e.cwd??process.cwd(),r=e.host??_T,n=e.port??NT,i=e.cliEntry??process.argv[1];if(e.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await JT(t);let o=e.config??await Pm(),s=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,c=it(o);if(s&&c&&!c.password)c.password=s;let u=o.infrastructure?.compute?.managedServices?.vitess;if(s&&u&&typeof u==="object"&&!u.password)u.password=s;let a=Lf(t,o);if(a.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${a.reconciliation.failed} orphaned operation(s) as failed after restart.`);let p=Object.keys(o.environments??{}),f=VT(o,e.environment),y=WT(t),b=await Mn(o,f),C=new Map([[f,b]]),T=new Map([[f,Date.now()]]),R=new Map([[f,Date.now()]]),x=new Map,L=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),P=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),G=Pr(o)!=="serverless",ae=(m)=>{let q=C.get(m);if(q&&!Cy(T.get(m),Date.now(),L))return Promise.resolve(q);let K=x.get(m);if(K)return K;let z=!G||Cy(R.get(m),Date.now(),P),te=Mn(o,m,{includeSiteHealth:z}).then((ye)=>{let v=C.get(m),st=z?ye:XT(v,ye);if(C.set(m,st),T.set(m,Date.now()),z)R.set(m,Date.now());if(v?._serverReachable!==st._serverReachable||v?._metricsStatus!==st._metricsStatus||(v?.sitesDetail?.length??0)!==(st.sitesDetail?.length??0))jt();return st}).finally(()=>x.delete(m));return x.set(m,te),te},Z=Qy(t),Le=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(e.box&&Le!=="0"&&(Le==="1"||!o.cloud?.attachTo)){let m=!1,q=Date.now()+300000,K=async()=>{if(m)return;m=!0;try{let te=Date.now(),ye=te>=q;if(ye)q=te+300000;let v=a.environments.get(f);await Fu({controlPlane:a.store,projectId:a.project.id,environmentId:v?.id,config:o,environment:f,force:!0,lightweight:!0,includeSiteHealth:ye})}catch(te){if(e.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${te instanceof Error?te.message:String(te)}`)}finally{m=!1}};K(),setInterval(()=>void K(),60000).unref?.()}let W=new Map,ie=new Map,Ce=new Set,Yt=0;function Nr(m,q){if(m.role==="admin"&&!a.store.getActorByExternalId("user",`dashboard:${m.username.toLowerCase()}`))return m;let K=a.store.getActorByExternalId("user",`dashboard:${m.username.toLowerCase()}`),z=K?a.store.getMembershipForActor(a.organization.id,K.id):void 0;if(!z||z.status!=="active")return{...m,role:"member",sites:{},capabilities:[]};let te=a.store.listGrants(z.id),ye=a.store.resolveAuthorizationTarget(a.organization.id,z.scope)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),v=mo({membership:z,grants:te,target:ye});if(z.roleTemplate==="owner"||z.roleTemplate==="admin")return{...m,role:"admin",sites:{},organizationRole:z.roleTemplate,organizationSource:z.source,capabilities:v};let st=a.environments.get(q),Fe={};for(let oe of a.store.listResources(a.project.id,st?.id).filter((de)=>de.kind==="application")){let de=a.store.resolveAuthorizationTarget(a.organization.id,{type:"resource",id:oe.id});if(!de||!zt({membership:z,grants:te,capability:"project:read",target:de}).allowed)continue;Fe[oe.slug]=zt({membership:z,grants:te,capability:"config:write",target:de}).allowed?"owner":"collaborator"}return{...m,role:"member",sites:Fe,organizationRole:z.roleTemplate,organizationSource:z.source,capabilities:v}}function jt(){Yt+=1,W.clear();for(let m of Ce)Ln(m,{recursive:!0,force:!0});Ce.clear()}let Xt=(m,q)=>`${q}:${m.role==="admin"?"admin":`member:${Object.entries(m.sites).sort(([K],[z])=>K.localeCompare(z)).map(([K,z])=>`${K}=${z}`).join(",")}`}:${[...m.capabilities??[]].sort().join(",")}`;async function Zt(m,q){let K=Nr(m,q),z=Xt(K,q),te=W.get(z);if(te)return te;let ye=ie.get(z);if(ye)return ye;let v=Yt,st=(async()=>{let Fe=C.get(q)??await Mn(o,q);C.set(q,Fe);let oe={...Eu(Fe,{user:K,slug:o.project.slug}),viewer:{role:K.role,organizationRole:K.organizationRole,organizationSource:K.organizationSource,capabilities:K.capabilities??[]}},de=await eA(t,oe);if(de&&v!==Yt)return Ln(de,{recursive:!0,force:!0}),Z?.uiRoot;if(de)Ce.add(de);let Xe=de??Z?.uiRoot;if(Xe)W.set(z,Xe);return Xe})();ie.set(z,st);try{return await st}finally{ie.delete(z)}}let er=await Zt({username:"",passwordHash:"",role:"admin",sites:{}},f);if(!er)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let E=new WeakMap,N=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",V=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(V&&e.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 H=!V,ke=nh(t),Be=H?ah(t,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,U=new Lo(a.store,{encryptionKey:Wr(t)}),ge=new Uo(a.store),ce=new eo(a.store),ee=new qa(a.store,{encryptionKey:Wr(t)}),ot=new Oa(a.store),Bn=new Ma(a.store,{cwd:t}),tr=new Na(a.store,{encryptionKey:Wr(t)}),Ee=new xe(a.store,{workerId:`dashboard:${process.pid}`}),Re=new Cc(a.store),lr=new _c(a.store,Wr(t)),$r=new _y(a.store),yo=new Yo(Re,Ee,lr),Mr=o.project?.region??"us-east-1",qu=Wr(t),wt=new jy($r,{encryptionKey:qu,backends:[new Ny(a.store,qu),new $y(new co(Mr),Mr),new My(new Oy(Mr),Mr),new Ly]});await Fy(wt,a,o);let wa=new Sn(Mr),ub={aws_rds:new Ec(new xc(wa)),aws_aurora:new Tc(new Dc(wa)),aws_elasticache:new Ac(new Oc(new ji(Mr))),server:new kc(new Zn),container:new Rc(new Zn)},Ju=(m)=>ub[m.provider],Ue=new Sc(a.store),on=new Go(Ue,Ee),Wu=new wc(lr),lb={managed_database:new Ic(Re,wa),logical_database:new Lc(Re,lr),volume:new jc,files:new Mc(t),control_plane:new Uc(a.store,t),infrastructure:new Vc(new Bi(Mr))},pb=(m)=>lb[m.resourceKind],gb=(m)=>m.provider==="aws_backup"?void 0:Wu,Ia=new qy(a.store),Ca=[new Hy,new Gy(at(t,"volumes"))],pr=new Jy(Ia,Ca,Ee),ki=new Od(a.store),rr=new _d(ki,[new Qi("aws"),new Qi("hetzner"),new Qi("ssh")],Ee),Lr=new Fd(a.store),Hu=new Ud(Lr,ki),sn=new Jd(a.store),Gu=new Wd(sn,Ee),gr=new Md(a.store),Ea=new Ld(gr,Ee),Ku=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((m)=>new jd(m,a.store,a.project.id,a.organization.id)),Qe=new fc(a.store),Qu=new gc(Qe,{queue:Ee}),je=new _o(a.store),Br=new Oo(a.store),xt=new ln(a.store),ne=new Yy(a.store,{encryptionKey:Wr(t)}),mb=()=>Dy(a.store);for(let m of a.environments.values())pc(Qe,o,{organization:a.organization,project:a.project,environment:m,resources:a.store.listResources(a.project.id,m.id)});let Dt=new Xy(ne,{emailImpl:async(m)=>{let{email:q}=await import("./chunk-43xj5cny.js");return q.send(m)}}),Yu=async(m)=>{let q=rb(ne,a.project.id,m),K=[];for(let z of q.filter((te)=>te.notify&&te.alert))K.push(...await Dt.deliverAll(Dt.enqueue(a.organization.id,z.alert,z.transition)));return K.push(...await Dt.deliverAll(Dt.enqueueRemindersAndEscalations(a.organization.id,ne.listAlerts(a.project.id,{environmentId:m,states:["firing"]})))),K.push(...await Dt.retryDue()),{evaluations:q,deliveries:K}},Ta=!1,fb=async()=>{if(Ta)return;Ta=!0;try{for(let m of a.environments.values())for(let q of ne.listHealthChecks(a.project.id,m.id).filter((K)=>K.enabled)){let K=ne.listHealthResults(q.id,1)[0];if(K&&Date.now()-new Date(K.checkedAt).getTime()<q.intervalSeconds*1000)continue;let z=await new Ei(ne).runAndEvaluate(q);for(let te of z.evaluations.filter((ye)=>ye.notify&&ye.alert))await Dt.deliverAll(Dt.enqueue(a.organization.id,te.alert,te.transition))}}finally{Ta=!1}},Xu=setInterval(()=>{for(let m of a.environments.values())Yu(m.id).catch((q)=>console.error("ts-cloud alert evaluation failed:",q))},60000);Xu.unref?.();let Zu=setInterval(()=>{fb().catch((m)=>console.error("ts-cloud health check evaluation failed:",m))},30000);Zu.unref?.();let el=setInterval(()=>{try{Qu.tick()}catch(m){console.error("ts-cloud scheduled job evaluation failed:",m)}},30000);el.unref?.();let tl=setInterval(()=>{try{on.enqueueDue(),on.enqueueRetention()}catch(m){console.error("ts-cloud backup policy evaluation failed:",m)}},30000);tl.unref?.(),je.cleanup();let rl=setInterval(()=>{try{je.cleanup()}catch(m){console.error("ts-cloud preview cleanup failed:",m)}},3600000);rl.unref?.();let hb=e.queueWorker??!0,yb=nA(),bb=async(m,q)=>{let z=(m.environmentId?a.store.listEnvironments(m.projectId).find((te)=>te.id===m.environmentId):void 0)?.slug??String(f);if(q.kind==="dashboard_operation"&&q.operationId){let te=C.get(z)??b,ye=Cu(q.operationId,o,te);if(!ye||ye.danger||!["scheduler","backup","worker"].includes(ye.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let v=await ua(o,z,ye);return{ok:v.ok,stdout:v.stdout,stderr:v.stderr??v.error,retryable:/temporar|unavailable|timeout|network/i.test(v.stderr??v.error??""),output:{command:v.command??null,operation:v.operation}}}if(q.kind==="serverless_scheduler"){let te=await Mu(o,z,"run");return{ok:te.ok,stdout:te.stdout,stderr:te.error,retryable:/temporar|unavailable|timeout|network/i.test(te.error??""),output:{command:te.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${q.kind}.`}},bo=hb?new Uy(Ee,{...Ky({store:a.store,execute:async(m,q)=>{let K=q.operation.input&&typeof q.operation.input==="object"&&!Array.isArray(q.operation.input)?q.operation.input:{},z=K.source&&typeof K.source==="object"?K.source:void 0,te=t,ye,v,st;try{if(z?.bindingId&&z?.connectionId&&z?.commitSha){let oe=ee.getBinding(String(z.bindingId)),de=ee.getConnection(String(z.connectionId));if(!oe||!de||oe.connectionId!==de.id)throw Error("Queued source binding is no longer available");let Ge=(oe.repositoryId?ee.getRepository(oe.repositoryId):ee.listRepositories(de.id).find((Un)=>Un.fullName.toLowerCase()===oe.repositoryFullName.toLowerCase()))?.cloneUrl;if(!Ge&&de.provider==="generic_ssh")Ge=`git@${new URL(de.host).hostname}:${oe.repositoryFullName}.git`;if(!Ge)Ge=new URL(`/${oe.repositoryFullName}.git`,de.host.endsWith("/")?de.host:`${de.host}/`).href;let B=oe.deployKeyId?ee.getDeployKey(oe.deployKeyId):void 0,Pe=B&&oe.deployKeyId?{...B,privateKey:ee.getDeployPrivateKey(oe.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(de.provider)&&m.target.previewId){let Un=Vr(de,ee.getCredential(de.id)),O=je.previews.getInstance(m.target.previewId);st=async(Ot,Co)=>{try{await Un.setCommitStatus(oe.repositoryFullName,String(z.commitSha),{state:Ot,url:O?.url,description:Co})}catch(zn){q.log(`Could not publish source status: ${zn instanceof Error?zn.message:String(zn)}`,{stream:"stderr"})}},await st("pending",`Preview deployment started for ${String(z.commitSha).slice(0,12)}`)}ye=Vu(Ie(Sa(),"ts-cloud-queued-source-")),q.log(`Checking out immutable source commit ${z.commitSha}.`,{stream:"system"}),te=(await Ha({remote:Ge,binding:oe,destination:Ie(ye,"checkout"),ref:String(z.branch??oe.defaultBranch),commitSha:String(z.commitSha)},{credential:ee.getCredential(de.id),deployKey:Pe})).directory}if(q.operation.kind!=="preview.destroy"){let oe=m.target.previewId?je.previews.getInstance(m.target.previewId):void 0,de=oe?je.previews.getDefinition(oe.definitionId):void 0,Xe=q.operation.resourceId?a.store.getResource(q.operation.resourceId):void 0;if(v=await wt.resolve({projectId:a.project.id,environmentId:q.operation.environmentId,resourceId:q.operation.resourceId,functionId:Xe?.kind==="function"?Xe.id:void 0,previewId:oe?.id,trustedPreview:!!oe&&!oe.fork,allowedPreviewSecrets:de?.inheritedSecrets}),v.warnings.some((Ge)=>Ge.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${v.warnings.filter((Ge)=>Ge.code==="missing_required").map((Ge)=>Ge.key).join(", ")}`);if(q.operation.resourceId)for(let Ge of Object.values(v.entries))$r.setDependency({entryId:Ge.id,resourceId:q.operation.resourceId,injectionTarget:"environment",required:Ge.required,requiresRedeploy:!0});q.log(`Resolved configuration ${v.configurationHash.slice(0,18)} for ${Object.keys(v.values).length} keys.`,{stream:"system"})}let Fe=await zu(m,{cwd:te,cliEntry:i,signal:q.signal,env:v?.values,onOutput:(oe,de)=>q.log(de,{stream:oe,step:"execute",secrets:[...yb,...Object.entries(v?.entries??{}).filter(([,Xe])=>Xe.kind==="secret").map(([Xe])=>v.values[Xe]).filter(Boolean)]})});if(Fe.ok&&q.operation.resourceId&&v)for(let oe of Object.values(v.entries))$r.setDependency({entryId:oe.id,resourceId:q.operation.resourceId,injectionTarget:"environment",required:oe.required,requiresRedeploy:!1,lastDeployedVersion:oe.version});return await st?.(Fe.ok?"success":"failure",Fe.ok?`Preview is ready at ${String(z?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(z?.commitSha).slice(0,12)}`),Fe}catch(Fe){throw await st?.("error",`Preview deployment could not complete at ${String(z?.commitSha).slice(0,12)}`),Fe}finally{if(ye)Ln(ye,{recursive:!0,force:!0})}}}),...Pp({store:Qe,executor:bb}),...Up({store:Re,secrets:lr,resolveAdapter:Ju}),..._m(ki,rr.drivers),...ef(sn,[new Hd("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...Wm({store:gr,cleanup:Ku}),...Wy(Ia,Ca),...Lp({store:Ue,queue:Ee,resolveSource:pb,resolveDestination:gb,validateHealth:async(m,q)=>{if(!m.healthCheckId)return{healthy:!0,mode:"adapter"};let K=ne.getHealthCheck(m.healthCheckId);if(!K||K.projectId!==m.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let z=await new Ei(ne).runAndEvaluate(K);return{healthy:z.result.status==="healthy",healthCheckId:K.id,healthResultId:z.result.id,target:q}}}),...Ol({store:a.store,resolveDriver:e.releaseDriver??((m)=>({name:`${a.store.getResource(m.resourceId)?.provider??"provider"} release driver`,capability:()=>({strategy:m.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(m,q)=>{let K=ne.listHealthChecks(q.projectId,q.environmentId).find((te)=>te.enabled&&te.name===m&&(!te.resourceId||te.resourceId===q.resourceId));if(!K)return{healthy:!1,message:`Named health gate ${m} was not found for this release.`};let z=await new Ei(ne).runAndEvaluate(K);return{healthy:z.result.status==="healthy",evidence:{healthCheckId:K.id,healthResultId:z.result.id,status:z.result.status,timings:z.result.timings},message:z.result.message}}})},{parallelism:e.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(m)=>console.error("ts-cloud deployment queue worker failed:",m)}):void 0;if(xf(a),Gs(ce,Kt(a,String(f)),b),Be)Qs(a,Be.users),uh(U,a,Be.users);let Oe=ch({cwd:t,enabled:H,secret:ke,authentication:U,authorization:{store:a.store,organizationId:a.organization.id,projectId:a.project.id,defaultEnvironment:String(f)}}),ze=new Zd,nl=setInterval(()=>ze.sweep(),60000);nl.unref?.();let So=new so,Aa=new so(3,900000,900000),vo=new so(8,900000,900000),il=setInterval(()=>So.prune(),300000),ol=setInterval(()=>Aa.prune(),300000),sl=setInterval(()=>vo.prune(),300000);if(il.unref?.(),ol.unref?.(),sl.unref?.(),H){if(Be?.generated)console.warn(`
|
|
478
|
-
ts-cloud dashboard: created the first admin.
|
|
479
|
-
username: ${Be.generated.username}
|
|
480
|
-
password: ${Be.generated.password}
|
|
481
|
-
Saved (hashed) to ${oh()}. This password is shown once.
|
|
482
|
-
`)}else console.warn(" ts-cloud dashboard: authentication is DISABLED (TS_CLOUD_DASHBOARD_AUTH=0). Every request runs as an admin.");let jr=r!=="127.0.0.1"&&r!=="localhost",ka=(m)=>AT("sha256").update(`${ke}:${m}`).digest("hex").slice(0,16),Sb=Ya({controlPlane:a.store,identities:ge,sources:ee,applications:{drafts:ot,artifacts:Bn,registries:tr}}),al=(m)=>m.headers.get("user-agent")?.trim().slice(0,256)||void 0,wo=(m,q,K,z="local")=>U.createSession({identityId:m,authMethod:z,userAgent:al(q),networkHint:ka(K)}),Q=(m)=>{let q=a.store.getActorByExternalId("user",`dashboard:${m.username.toLowerCase()}`),K=q?a.store.getMembershipForActor(a.organization.id,q.id):void 0;return{actor:q,membership:K,grants:K?a.store.listGrants(K.id):[]}},jn=(m,q,K)=>{if(m.role==="admin")return!0;let z=a.store.getOperation(q),te=Q(m);if(!z||!te.membership)return!1;let ye=z.resourceId?{type:"resource",id:z.resourceId}:z.environmentId?{type:"environment",id:z.environmentId}:z.projectId?{type:"project",id:z.projectId}:{type:"organization"},v=a.store.resolveAuthorizationTarget(a.organization.id,ye);return!!v&&zt({membership:te.membership,grants:te.grants,capability:K,target:v}).allowed},Ye=(m,q,K)=>{if(m.role==="admin")return!0;let z=Q(m);if(!z.membership)return!1;let te=a.store.resolveAuthorizationTarget(a.organization.id,{type:"resource",id:q});return!!te&&zt({membership:z.membership,grants:z.grants,capability:K,target:te}).allowed},Ri=(m,q,K)=>{if(m.role==="admin")return!0;let z=Q(m);if(!z.membership)return!1;let te=a.store.resolveAuthorizationTarget(a.organization.id,{type:"environment",id:q});return!!te&&zt({membership:z.membership,grants:z.grants,capability:K,target:te}).allowed},Io=(m,q)=>{if(m.role==="admin")return!0;let K=Q(m);if(!K.membership)return!1;let z=a.store.resolveAuthorizationTarget(a.organization.id,{type:"organization"});return!!z&&zt({membership:K.membership,grants:K.grants,capability:q,target:z}).allowed},Fn=Bun.serve({hostname:r,port:n,idleTimeout:30,websocket:{open(m){if(!N){m.send(`The web terminal is disabled (TS_CLOUD_DASHBOARD_TERMINAL=0).\r
|
|
483
|
-
`),m.close();return}let q=vy((K)=>m.send(K),{cwd:t,onExit:()=>{try{m.close()}catch{}}});E.set(m,q),m.send(`Connected to ${r==="127.0.0.1"?"localhost":r} shell. This is a line-oriented shell (no full-screen apps).\r
|
|
484
|
-
`)},message(m,q){E.get(m)?.write(typeof q==="string"?q:new TextDecoder().decode(q))},close(m){E.get(m)?.close(),E.delete(m)}},async fetch(m,q){let K=Date.now(),z=m.clone(),te=m.headers.get("x-request-id")?.slice(0,128)||crypto.randomUUID(),ye=!["GET","HEAD","OPTIONS"].includes(m.method.toUpperCase()),v=new URL(m.url),Fe=await(async()=>{let oe=q??Fn,de=zT(r,oe.port??n),Xe=await Sb(m,ka(oe.requestIP(m)?.address??"unknown"));if(Xe)return Xe;let Ge=v.searchParams.get("env"),B=qT(p,f,Ge),Pe=C.get(B);if(!Pe)Pe=await ae(B);try{if(!GT(m))return g({ok:!1,error:"Cross-site requests are not allowed."},403);let an=/^\/api\/source\/webhooks\/([A-Za-z0-9_-]{16,200})$/.exec(v.pathname);if(an&&m.method==="POST"){let d=await Gl({sources:ee,controlPlane:a.store,endpointToken:an[1],headers:m.headers,rawBody:new Uint8Array(await m.arrayBuffer())});return g({accepted:d.accepted,duplicate:d.duplicate,status:d.status,operationIds:d.operations.map((l)=>l.id),message:d.message},d.accepted?202:404)}let Un=/^\/auth\/oidc\/([a-z0-9-]+)\/(start|callback)$/.exec(v.pathname);if(Un&&m.method==="GET"){let[,d,l]=Un;if(!de)return new Response(null,{status:302,headers:{location:"/login?sso_error=configuration"}});if(l==="start")try{let h=await ac(U,d,de,v.searchParams.get("return")??void 0,e.oidcFetch);return new Response(null,{status:302,headers:{location:h.authorizationUrl,"cache-control":"no-store"}})}catch(h){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.start_failed",level:"warning",payload:{provider:d,reason:h instanceof Error?h.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=start","cache-control":"no-store"}})}try{if(v.searchParams.has("error")){let A=U.getOidcProviderBySlug(d),I=v.searchParams.get("state");if(A&&I)U.consumeOidcTransaction(A.id,I);throw Error("OIDC provider returned an authorization error")}let h=await cc(U,{providerSlug:d,state:v.searchParams.get("state")??"",code:v.searchParams.get("code")??"",origin:de},e.oidcFetch),S=lh(U,a,t,h.identity);U.recordLogin(S.identity.id);let w=wo(S.identity.id,m,oe.requestIP(m)?.address??"unknown","oidc");return jt(),a.store.appendEvent({organizationId:a.organization.id,actorId:S.identity.actorId,type:"auth.login.succeeded",payload:{method:"oidc",provider:d,provisioned:S.provisioned}}),new Response(null,{status:302,headers:{location:h.returnPath,"cache-control":"no-store","set-cookie":Si(w.token,{secure:jr,maxAgeMs:Jr})}})}catch(h){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.callback_failed",level:"warning",payload:{provider:d,reason:h instanceof Error?h.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=callback","cache-control":"no-store"}})}}if(v.pathname==="/api/invitations/accept"&&m.method==="POST"){let d=await D(m),l=String(d.token??"").trim(),h=String(d.username??"").trim(),S=String(d.password??"");if(!l||!oa(h)||S.length<12)return g({ok:!1,error:"Invitation token, valid username, and a password of at least 12 characters are required."},422);let w=a.store.inspectInvitationToken(l);if(!w||w.state!=="pending")return g({ok:!1,error:w?`Invitation is ${w.state}`:"Invitation is invalid"},w?409:404);let A=Bt(vt(t),h),I=U.getIdentityByUsername(h);if(A&&!Qt(S,I?.passwordHash??A.passwordHash))return g({ok:!1,error:"That username already exists; enter its current password to continue."},401);let k=U.getIdentityByEmail(w.email);if(k&&k.id!==I?.id)return g({ok:!1,error:"This invitation belongs to an existing account. Sign in with that account or ask an owner to resend it."},409);let M=io(t,{username:h,password:A?void 0:S,name:typeof d.name==="string"?d.name:void 0,email:w.email,sites:A?.sites??{}}),_=He(a.store,M.user);try{let re=a.store.acceptInvitation(l,_.id),j=I?U.setVerifiedEmail(I.id,re.invitation.email):U.createIdentity({actorId:_.id,username:M.user.username,email:re.invitation.email,emailVerified:!0,passwordHash:M.user.passwordHash}),Y=wo(j.id,m,oe.requestIP(m)?.address??"unknown");return jt(),g({ok:!0,user:vi(M.user),organization:a.organization,membership:re.membership},200,{"set-cookie":Si(Y.token,{secure:jr,maxAgeMs:Jr})})}catch(re){if(!A)vu(t,M.user.username);let j=re instanceof Error?re.message:"Invitation could not be accepted.";return g({ok:!1,error:j},j.includes("expired")||j.includes("revoked")||j.includes("accepted")?409:404)}}if(v.pathname==="/api/auth/password-reset/request"&&m.method==="POST"){let d=await D(m),l=String(d.identifier??"").trim().toLowerCase(),h=oe.requestIP(m)?.address??"unknown",S=Aa.check(l,h),w=l.includes("@")?U.getIdentityByEmail(l):U.getIdentityByUsername(l);if(S.allowed)Aa.recordFailure(l,h);if(S.allowed&&w?.email&&w.emailVerifiedAt&&!w.disabledAt){U.revokeActionTokens(w.id,"password_reset");let A=U.createActionToken(w.id,"password_reset"),I=`${v.origin}/reset-password?token=${encodeURIComponent(A.token)}`,k=await Li(o,{to:w.email,subject:"Reset your ts-cloud password",text:`Reset your ts-cloud password: ${I}
|
|
485
|
-
|
|
486
|
-
This link expires in one hour and can be used once.`});a.store.appendEvent({organizationId:a.organization.id,actorId:w.actorId,type:"auth.password_reset.requested",payload:{delivered:k}})}return g({ok:!0,message:"If that account has a verified email, a reset link has been sent."},202)}if(v.pathname==="/api/auth/password-reset/complete"&&m.method==="POST"){let d=await D(m),l=String(d.token??"").trim(),h=String(d.password??"");if(!l||h.length<12)return g({ok:!1,error:"A valid reset token and password of at least 12 characters are required."},422);try{let S=U.consumeActionToken(l,"password_reset"),w=en(h),A=U.updatePassword(S.identityId,w);return aa(t,A.username,w),a.store.appendEvent({organizationId:a.organization.id,actorId:A.actorId,type:"auth.password_reset.completed"}),g({ok:!0,message:"Password changed. Sign in again."},200,{"set-cookie":ia({secure:jr})})}catch(S){let w=S instanceof Error?S.message:"Password reset failed.";return g({ok:!1,error:w.replace("Action token","Reset link")},w.includes("consumed")||w.includes("expired")?409:404)}}if(v.pathname==="/api/login"&&m.method==="POST"){let d=await D(m),l=String(d.username??"").trim(),h=String(d.password??""),S=oe.requestIP(m)?.address??"unknown",w=So.check(l,S);if(!w.allowed)return g({ok:!1,error:`Too many failed attempts. Try again in ${Math.ceil((w.retryAfterSeconds??0)/60)} minute(s).`},429,{"retry-after":String(w.retryAfterSeconds??60)});let A=Bt(vt(t),l),I=U.getIdentityByUsername(l),k=I?.passwordHash??A?.passwordHash??UT;if(!(Qt(h,k)&&!!A&&!!I&&!I.disabledAt))return So.recordFailure(l,S),g({ok:!1,error:"Incorrect username or password."},401);if(ph(U,a,I))return g({ok:!1,error:"Single sign-on is required for this account."},403);So.recordSuccess(l,S);let _=I,re=_.requiresPasswordUpgrade||_f(_.passwordHash);if(re){let Y=en(h);_=U.rehashPassword(_.id,Y),aa(t,_.username,Y)}if(U.recordLogin(_.id),U.getMfaFactor(_.id)?.state==="active"){let Y=U.createMfaChallenge(_.id,"login");return a.store.appendEvent({organizationId:a.organization.id,actorId:_.actorId,type:"auth.mfa.challenge.created",payload:{purpose:"login"}}),g({ok:!0,mfaRequired:!0,challengeToken:Y.token,passwordUpgraded:re})}let j=wo(_.id,m,S);return a.store.appendEvent({organizationId:a.organization.id,actorId:_.actorId,type:"auth.login.succeeded",payload:{method:"local"}}),g({ok:!0,user:vi(A),passwordUpgraded:re},200,{"set-cookie":Si(j.token,{secure:jr,maxAgeMs:Jr})})}if(v.pathname==="/api/auth/mfa/complete"&&m.method==="POST"){let d=await D(m),l=String(d.challengeToken??"").trim(),h=String(d.code??"").trim(),S=oe.requestIP(m)?.address??"unknown",A=U.inspectMfaChallengeToken(l,"login")?.identityId??"unknown-mfa",I=vo.check(A,S);if(!I.allowed)return g({ok:!1,error:"Too many MFA attempts. Try again later."},429,{"retry-after":String(I.retryAfterSeconds??60)});try{let k=U.completeMfaChallenge(l,h,"login");vo.recordSuccess(A,S);let M=new Date().toISOString(),_=U.createSession({identityId:k.identity.id,userAgent:al(m),networkHint:ka(S),mfaAt:M,recentAuthAt:M});return a.store.appendEvent({organizationId:a.organization.id,actorId:k.identity.actorId,type:"auth.mfa.succeeded",payload:{purpose:"login",method:k.method}}),g({ok:!0},200,{"set-cookie":Si(_.token,{secure:jr,maxAgeMs:Jr})})}catch{return vo.recordFailure(A,S),g({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}}if(v.pathname==="/api/logout"&&m.method==="POST"){let d=Oe.resolveSession(m);if(d)U.revokeSession(d.identityId,d.id);let l=ia({secure:jr});if(m.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login","set-cookie":l}});return g({ok:!0},200,{"set-cookie":l})}if(v.pathname==="/login"){let d=U.listOidcProviders(a.organization.id).map((l)=>({slug:l.slug,name:l.name}));return new Response(gh(b?.mode==="serverless",d),{headers:{"content-type":"text/html; charset=utf-8"}})}if(v.pathname==="/forgot-password"||v.pathname==="/reset-password")return new Response(mh(v.pathname==="/reset-password"?"reset":"request"),{headers:{"content-type":"text/html; charset=utf-8"}});if(v.pathname==="/accept-invitation")return Py(er,v.pathname);let O=Oe.resolveUser(m);if(!O){if(!v.pathname.startsWith("/api/")&&m.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login"}});return g({ok:!1,error:"Sign in to continue."},401)}let Ot=Nr(O,B);if(v.pathname==="/api/me"){let d=a.store.getActorByExternalId("user",`dashboard:${O.username.toLowerCase()}`),l=d?a.store.getMembershipForActor(a.organization.id,d.id):void 0,h=a.store.resolveAuthorizationTarget(a.organization.id,l?.scope??{type:"project",id:a.project.id})??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id});return g({ok:!0,user:vi(O),authEnabled:H,organization:a.organization,membership:l,capabilities:mo({membership:l,grants:l?a.store.listGrants(l.id):[],target:h})})}if(v.pathname.startsWith("/api/")){let d=await dh(m,v.pathname),l=Oe.check(m,v.pathname,O,d);if(!l.ok)return g({ok:!1,error:l.error},l.status??403);if(H&&YT.has(`${m.method.toUpperCase()} ${v.pathname}`)){let h=Oe.resolveSession(m);if(!h||!U.isRecentlyAuthenticated(h))return g({ok:!1,error:"Recent authentication is required for this change.",stepUpRequired:!0},401)}}if(v.pathname==="/api/auth/security"&&m.method==="GET"){let d=Q(O),l=d.actor?U.getIdentityByActor(d.actor.id):void 0,h=Oe.resolveSession(m);return g({identity:l?{username:l.username,email:l.email,emailVerifiedAt:l.emailVerifiedAt,requiresPasswordUpgrade:l.requiresPasswordUpgrade,lastLoginAt:l.lastLoginAt}:void 0,currentSessionId:h?.id,sessions:l?U.listSessions(l.id,{includeInactive:!0}):[],mfa:l?{factor:U.getMfaFactor(l.id),recoveryCodesRemaining:U.remainingRecoveryCodes(l.id)}:void 0})}if(v.pathname==="/api/auth/oidc/providers"&&m.method==="GET")return g({providers:U.listOidcProviders(a.organization.id,{includeDisabled:!0}),callbackOrigin:de,callbackPattern:de?`${de}/auth/oidc/{slug}/callback`:void 0,localOwnerRecovery:!0});if(v.pathname==="/api/auth/oidc/providers"&&m.method==="POST"){let d=await D(m),l=Q(O),h=l.actor?U.getIdentityByActor(l.actor.id):void 0,S=d.enforceSso===!0;if(S&&(!h?.emailVerifiedAt||U.remainingRecoveryCodes(h.id)<1))return g({ok:!1,error:"Verify the owner email and generate MFA recovery codes before enforcing SSO."},409);try{let w=ya(d.defaultRole),A=U.upsertOidcProvider({id:typeof d.id==="string"?d.id:void 0,organizationId:a.organization.id,slug:String(d.slug??""),name:String(d.name??""),issuer:String(d.issuer??""),clientId:String(d.clientId??""),clientSecret:typeof d.clientSecret==="string"&&d.clientSecret?d.clientSecret:void 0,scopes:Array.isArray(d.scopes)?d.scopes.map(String):void 0,allowedDomains:Array.isArray(d.allowedDomains)?d.allowedDomains.map(String):[],defaultRole:w&&w!=="owner"?w:void 0,enabled:d.enabled!==!1,enforceSso:S});return a.store.appendEvent({organizationId:a.organization.id,actorId:l.actor?.id,type:"auth.oidc.provider.configured",payload:{providerId:A.id,issuer:A.issuer,enabled:A.enabled,enforceSso:A.enforceSso}}),g({ok:!0,provider:A})}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"OIDC provider could not be saved."},422)}}if(v.pathname==="/api/auth/oidc/providers"&&m.method==="PATCH"){let d=await D(m),l=U.getOidcProvider(String(d.id??""));if(!l||l.organizationId!==a.organization.id)return g({ok:!1,error:"OIDC provider was not found."},404);let h=Q(O),S=U.setOidcProviderEnabled(l.id,d.enabled===!0);return a.store.appendEvent({organizationId:a.organization.id,actorId:h.actor?.id,type:S.enabled?"auth.oidc.provider.enabled":"auth.oidc.provider.disabled",payload:{providerId:l.id}}),g({ok:!0,provider:S})}if(v.pathname==="/api/automation"&&m.method==="GET"){let d=ge.listServiceAccounts(a.organization.id,{includeDisabled:!0}).map((l)=>{let h=a.store.getMembershipForActor(a.organization.id,l.actorId),S=l.createdByActorId?a.store.getActor(l.createdByActorId):void 0,w=ge.listTokens(l.id,{includeInactive:!0}).map((A)=>({...A,createdBy:A.createdByActorId?a.store.getActor(A.createdByActorId):void 0}));return{account:l,createdBy:S,membership:h,tokens:w}});return g({accounts:d,apiBaseUrl:`${v.origin}/api/v1`,openApiUrl:`${v.origin}/api/v1/openapi.json`,tokenEnvironmentVariable:"TS_CLOUD_API_TOKEN"})}if(v.pathname==="/api/automation/service-accounts"&&m.method==="POST"){let d=await D(m),l=Q(O),h=ya(d.roleTemplate),S=go(d);if(!l.actor||!h||h==="owner"||!S)return g({ok:!1,error:"A non-owner role and valid organization scope are required."},422);try{let w=ge.createServiceAccount({organizationId:a.organization.id,slug:String(d.slug??""),name:String(d.name??""),description:typeof d.description==="string"?d.description:void 0,roleTemplate:h,scope:S,createdByActorId:l.actor.id});return g({ok:!0,...w},201)}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"Service account could not be created."},422)}}if(v.pathname==="/api/automation/service-accounts"&&m.method==="PATCH"){let d=await D(m),l=Q(O),h=ge.getServiceAccount(String(d.id??""));if(!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Service account was not found."},404);return g({ok:!0,account:ge.disableServiceAccount(h.id,l.actor?.id)})}if(v.pathname==="/api/automation/tokens"&&m.method==="POST"){let d=await D(m),l=Q(O),h=ge.getServiceAccount(String(d.serviceAccountId??"")),S=go(d);if(!l.actor||!h||h.organizationId!==a.organization.id||!S||!Array.isArray(d.capabilities))return g({ok:!1,error:"Service account, explicit capabilities, and valid scope are required."},422);try{let w=ge.createToken({serviceAccountId:h.id,name:String(d.name??"API token"),capabilities:d.capabilities.map(String),scope:S,expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,createdByActorId:l.actor.id});return g({ok:!0,token:w.token,secret:w.secret,revealOnce:!0},201)}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"API token could not be created."},422)}}if(v.pathname==="/api/automation/tokens/rotate"&&m.method==="POST"){let d=await D(m),l=Q(O),h=ge.getToken(String(d.id??"")),S=h?ge.getServiceAccount(h.serviceAccountId):void 0;if(!l.actor||!h||S?.organizationId!==a.organization.id)return g({ok:!1,error:"API token was not found."},404);try{let w=ge.rotateToken(h.id,l.actor.id);return g({ok:!0,token:w.token,secret:w.secret,revealOnce:!0,overlap:!0},201)}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"API token could not be rotated."},409)}}if(v.pathname==="/api/automation/tokens"&&m.method==="DELETE"){let d=await D(m),l=Q(O),h=ge.getToken(String(d.id??"")),S=h?ge.getServiceAccount(h.serviceAccountId):void 0;if(!h||S?.organizationId!==a.organization.id)return g({ok:!1,error:"API token was not found."},404);return g({ok:!0,token:ge.revokeToken(h.id,l.actor?.id)})}if(v.pathname==="/api/onboarding"&&m.method==="GET"){let d=ee.listConnections(a.organization.id);return g({drafts:ot.list(a.project.id),artifacts:Bn.list(a.project.id),registries:tr.list(a.organization.id),sourceConnections:d,repositories:d.flatMap((l)=>ee.listRepositories(l.id)),project:{id:a.project.id,slug:a.project.slug,name:a.project.name},environments:[...a.environments.values()].map((l)=>({id:l.id,slug:l.slug,name:l.name,kind:l.kind,region:l.region})),resources:a.store.listResources(a.project.id).filter((l)=>l.kind==="application").map((l)=>({id:l.id,slug:l.slug,name:l.name,environmentId:l.environmentId}))})}if(v.pathname==="/api/onboarding/detect"&&m.method==="POST"){let d=await D(m);try{if(d.source?.kind==="git"){let S=ee.getConnection(String(d.source.connectionId??"")),w=ee.getRepository(String(d.source.repositoryId??""));if(!S||S.organizationId!==a.organization.id||!w||w.connectionId!==S.id)throw Error("Authorized Git repository was not found");let A=typeof d.source.deployKeyId==="string"?ee.getDeployKey(d.source.deployKeyId):void 0;if(A&&A.connectionId!==S.id)throw Error("Deploy key does not belong to this connection");let I=Vu(Ie(Sa(),"ts-cloud-onboarding-git-"));try{let k=await Ha({remote:w.cloneUrl,destination:Ie(I,"checkout"),ref:String(d.source.ref??w.defaultBranch),sparsePaths:Array.isArray(d.source.sparsePaths)?d.source.sparsePaths.map(String):void 0,binding:{id:"detection",projectId:a.project.id,connectionId:S.id,repositoryId:w.id,repositoryFullName:w.fullName,defaultBranch:w.defaultBranch,monorepoRoot:String(d.source.monorepoRoot??"."),includePaths:[],excludePaths:[],submodules:d.source.submodules===!0,cloneDepth:1,deployKeyId:A?.id,autoDeploy:!1,pullRequestPreviews:!1,status:"active",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}},{credential:ee.getCredential(S.id),deployKey:A?{...A,privateKey:ee.getDeployPrivateKey(A.id)}:void 0,timeoutMs:120000});return g({ok:!0,commitSha:k.commitSha,candidates:qn(Pa(k.directory))})}finally{Ln(I,{recursive:!0,force:!0})}}if(Array.isArray(d.files)){if(d.files.length>1e4)throw Error("Detection file-count limit exceeded");let S=d.files.map((w)=>({path:String(w.path??""),size:Number(w.size??0),content:typeof w.content==="string"?w.content.slice(0,262144):void 0}));return g({ok:!0,candidates:qn(S)})}let l=xT(t,String(d.root??".")),h=PT(t,l);if(h===".."||h.startsWith(`..${DT}`))throw Error("Detection root must stay inside the project");return g({ok:!0,candidates:qn(Pa(l))})}catch(l){return g({ok:!1,error:l instanceof Error?l.message:"Application detection failed."},422)}}if(v.pathname==="/api/onboarding/plan"&&m.method==="POST"){let d=await D(m);try{return g({ok:!0,plan:Ft(d.draft,Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):[])})}catch(l){return g({ok:!1,error:l instanceof Error?l.message:"Application plan could not be generated."},422)}}if(v.pathname==="/api/onboarding/drafts"&&m.method==="POST"){let d=await D(m),l=Q(O);try{return g({ok:!0,draft:ot.create({organizationId:a.organization.id,projectId:a.project.id,name:String(d.name??d.draft?.name??"Application draft"),draft:{...d.draft,projectId:a.project.id},step:d.step,suppliedSecretNames:Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):[],actorId:l.actor?.id})},201)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Application draft could not be saved."},422)}}if(v.pathname==="/api/onboarding/drafts"&&m.method==="PATCH"){let d=await D(m),l=Q(O),h=ot.get(String(d.id??""));if(!h||h.projectId!==a.project.id)return g({ok:!1,error:"Application draft was not found."},404);try{return g({ok:!0,draft:ot.update(h.id,Number(d.version),{draft:{...d.draft,projectId:a.project.id},step:d.step,suppliedSecretNames:Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):void 0,actorId:l.actor?.id})})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Application draft could not be updated."},409)}}if(v.pathname==="/api/onboarding/artifacts"&&m.method==="POST"){let d=Q(O);if(Number(m.headers.get("content-length")??0)>104857600)return g({ok:!1,error:"Artifact exceeds the 100 MB upload limit."},413);try{let h=new Uint8Array(await m.arrayBuffer());return g({ok:!0,artifact:Bn.create({organizationId:a.organization.id,projectId:a.project.id,filename:m.headers.get("x-artifact-filename")??"application.zip",bytes:h,actorId:d.actor?.id})},201)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Artifact could not be inspected."},422)}}if(v.pathname==="/api/onboarding/registries"&&m.method==="POST"){let d=await D(m),l=Q(O);try{return g({ok:!0,registry:tr.create({organizationId:a.organization.id,provider:d.provider,name:String(d.name??"Container registry"),host:String(d.host??""),credential:d.token||d.password?{username:typeof d.username==="string"?d.username:void 0,password:typeof d.password==="string"?d.password:void 0,token:typeof d.token==="string"?d.token:void 0}:void 0,credentialExpiresAt:typeof d.credentialExpiresAt==="string"?d.credentialExpiresAt:void 0,actorId:l.actor?.id})},201)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Registry connection could not be created."},422)}}if(v.pathname==="/api/onboarding/registries"&&m.method==="PATCH"){let d=await D(m),l=Q(O),h=tr.get(String(d.id??""));if(!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Registry connection was not found."},404);try{if(d.action==="test")return g({ok:!0,registry:await tr.test(h.id,{image:typeof d.image==="string"?d.image:void 0})});if(d.action==="rotate")return g({ok:!0,registry:tr.rotate(h.id,{username:typeof d.username==="string"?d.username:void 0,password:typeof d.password==="string"?d.password:void 0,token:typeof d.token==="string"?d.token:void 0},{expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,actorId:l.actor?.id})});return g({ok:!1,error:"Registry action must be test or rotate."},422)}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Registry connection could not be updated."},422)}}if(v.pathname==="/api/onboarding/registries"&&m.method==="DELETE"){let d=await D(m),l=Q(O),h=tr.get(String(d.id??""));if(!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Registry connection was not found."},404);let S=ot.list(a.project.id).filter((w)=>w.input.source.kind==="image"&&w.input.source.registryConnectionId===h.id||w.input.build.kind==="prebuilt_image"&&w.input.build.registryConnectionId===h.id);if(d.preview===!0)return g({ok:!0,preview:!0,affectedDrafts:S});return g({ok:!0,registry:tr.disconnect(h.id,l.actor?.id),affectedDrafts:S})}if(v.pathname==="/api/onboarding/apply"&&m.method==="POST"){let d=await D(m),l=Q(O);try{let h=Eo({controlPlane:a.store,drafts:ot,draftId:String(d.id??""),expectedVersion:Number(d.version),confirmEnvironment:String(d.confirmEnvironment??""),actorId:l.actor?.id});return g({ok:!0,resource:h.resource,operation:h.operation,plan:h.plan},202)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Application plan could not be applied."},422)}}if(v.pathname==="/api/sources"&&m.method==="GET"){let d=ee.listConnections(a.organization.id);return g({connections:d,bindings:ee.listBindings({projectId:a.project.id}),repositories:d.flatMap((l)=>ee.listRepositories(l.id)),deployKeys:d.flatMap((l)=>ee.listDeployKeys(l.id)),webhooks:d.flatMap((l)=>ee.listWebhooks(l.id)).map((l)=>({...l,deliveries:ee.listDeliveries(l.id,20)})),project:{id:a.project.id,slug:a.project.slug},environment:Kt(a,String(B)),resources:a.store.listResources(a.project.id,Kt(a,String(B)).environmentId).filter((l)=>l.kind==="application").map((l)=>({id:l.id,slug:l.slug,name:l.name}))})}if(v.pathname==="/api/sources/connections"&&m.method==="POST"){let d=await D(m),l=Q(O),h=String(d.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(h))return g({ok:!1,error:"A supported Git provider is required."},422);try{let S=h==="github"&&(d.privateKey||d.appId)?{appId:typeof d.appId==="string"?d.appId:void 0,installationId:typeof d.installationId==="string"?d.installationId:void 0,privateKey:typeof d.privateKey==="string"?d.privateKey:void 0}:h!=="generic_ssh"&&d.token?{token:typeof d.token==="string"?d.token:void 0,username:typeof d.username==="string"?d.username:void 0}:void 0,w={github:"https://github.com",gitlab:"https://gitlab.com",bitbucket:"https://bitbucket.org",gitea:"https://gitea.com"},A,I,k;if(a.store.database.transaction(()=>{if(A=ee.createConnection({organizationId:a.organization.id,provider:h,name:String(d.name??h),host:String(d.host??w[h]??""),owner:typeof d.owner==="string"?d.owner:void 0,authKind:d.authKind,credential:S,grantedScopes:Array.isArray(d.grantedScopes)?d.grantedScopes.map(String):[],credentialExpiresAt:typeof d.credentialExpiresAt==="string"?d.credentialExpiresAt:void 0,createdByActorId:l.actor?.id}),typeof d.repositoryUrl==="string"&&typeof d.repositoryFullName==="string")I=ee.upsertRepository({connectionId:A.id,providerRepositoryId:`manual:${d.repositoryFullName}`,fullName:d.repositoryFullName,cloneUrl:d.repositoryUrl,defaultBranch:String(d.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"manual"}});if(h==="generic_ssh")k=ee.createDeployKey({connectionId:A.id,name:String(d.deployKeyName??"Repository deploy key"),publicKey:String(d.publicKey??""),privateKey:String(d.deployPrivateKey??""),host:String(d.sshHost??""),hostKey:String(d.hostKey??""),actorId:l.actor?.id})})(),d.test===!0)A=await Ga(ee,A.id,I?.id);return g({ok:!0,connection:A,repository:I,deployKey:k},201)}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Source connection could not be created."},422)}}if(v.pathname==="/api/sources/connections"&&m.method==="PATCH"){let d=await D(m),l=Q(O),h=ee.getConnection(String(d.id??""));if(!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{if(d.action==="test")return g({ok:!0,connection:await Ga(ee,h.id,typeof d.repositoryId==="string"?d.repositoryId:void 0)});if(d.action==="rotate")return g({ok:!0,connection:ee.rotateCredential(h.id,{token:typeof d.token==="string"?d.token:void 0,username:typeof d.username==="string"?d.username:void 0,appId:typeof d.appId==="string"?d.appId:void 0,installationId:typeof d.installationId==="string"?d.installationId:void 0,privateKey:typeof d.privateKey==="string"?d.privateKey:void 0},{expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,actorId:l.actor?.id})});return g({ok:!1,error:"Connection action must be test or rotate."},422)}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Source connection could not be updated."},422)}}if(v.pathname==="/api/sources/connections"&&m.method==="DELETE"){let d=await D(m),l=Q(O),h=ee.getConnection(String(d.id??""));if(!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);let S=ee.listBindings({connectionId:h.id,status:"active"});if(d.preview===!0)return g({ok:!0,preview:!0,affectedBindings:S});return g({ok:!0,...ee.disconnectConnection(h.id,l.actor?.id)})}if(v.pathname==="/api/sources/deploy-keys"&&m.method==="POST"){let d=await D(m),l=Q(O),h=ee.getConnection(String(d.connectionId??""));if(!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g({ok:!0,deployKey:ee.createDeployKey({connectionId:h.id,name:String(d.name??"Repository deploy key"),publicKey:String(d.publicKey??""),privateKey:String(d.privateKey??""),host:String(d.host??""),hostKey:String(d.hostKey??""),actorId:l.actor?.id})},201)}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Deploy key could not be stored."},422)}}if(v.pathname==="/api/sources/deploy-keys"&&m.method==="DELETE"){let d=await D(m),l=Q(O),h=ee.getDeployKey(String(d.id??"")),S=h?ee.getConnection(h.connectionId):void 0;if(!h||!S||S.organizationId!==a.organization.id)return g({ok:!1,error:"Deploy key was not found."},404);let w=ee.listBindings({connectionId:S.id}).filter((A)=>A.deployKeyId===h.id);if(d.preview===!0)return g({ok:!0,preview:!0,affectedBindings:w});return g({ok:!0,...ee.revokeDeployKey(h.id,l.actor?.id)})}if(v.pathname==="/api/sources/repositories/sync"&&m.method==="POST"){let d=await D(m),l=ee.getConnection(String(d.connectionId??""));if(!l||l.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g({ok:!0,repositories:await Ro(ee,String(d.connectionId??""),{search:typeof d.search==="string"?d.search:void 0})})}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Repositories could not be synchronized."},422)}}if(v.pathname==="/api/sources/references"&&m.method==="GET"){let d=ee.getConnection(String(v.searchParams.get("connectionId")??""));if(!d||d.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g(await Po(ee,{connectionId:String(v.searchParams.get("connectionId")??""),repository:String(v.searchParams.get("repository")??""),repositoryId:v.searchParams.get("repositoryId")??void 0,deployKeyId:v.searchParams.get("deployKeyId")??void 0,type:v.searchParams.get("type")==="tags"?"tags":"branches",cursor:v.searchParams.get("cursor")??void 0}))}catch(l){return g({ok:!1,error:l instanceof Error?l.message:"References could not be listed."},422)}}if(v.pathname==="/api/sources/bindings"&&m.method==="POST"){let d=await D(m),l=Q(O),h=Kt(a,String(B)),S=ee.getConnection(String(d.connectionId??""));if(!S||S.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g({ok:!0,binding:ee.createBinding({projectId:a.project.id,environmentId:h.environmentId,resourceId:typeof d.resourceId==="string"?d.resourceId:void 0,connectionId:String(d.connectionId??""),repositoryId:typeof d.repositoryId==="string"?d.repositoryId:void 0,repositoryFullName:String(d.repositoryFullName??""),defaultBranch:String(d.defaultBranch??"main"),branchRule:typeof d.branchRule==="string"?d.branchRule:void 0,tagRule:typeof d.tagRule==="string"?d.tagRule:void 0,monorepoRoot:String(d.monorepoRoot??"."),includePaths:Array.isArray(d.includePaths)?d.includePaths.map(String):[],excludePaths:Array.isArray(d.excludePaths)?d.excludePaths.map(String):[],submodules:d.submodules===!0,cloneDepth:d.cloneDepth?Number(d.cloneDepth):void 0,deployKeyId:typeof d.deployKeyId==="string"&&d.deployKeyId?d.deployKeyId:void 0,autoDeploy:d.autoDeploy!==!1,pullRequestPreviews:d.pullRequestPreviews!==!1,actorId:l.actor?.id})},201)}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"Source binding could not be created."},422)}}if(v.pathname==="/api/sources/bindings"&&m.method==="PATCH"){let d=await D(m),l=Q(O),h=ee.getBinding(String(d.id??""));if(!h||h.projectId!==a.project.id)return g({ok:!1,error:"Source binding was not found."},404);try{return g({ok:!0,binding:ee.updateBinding(h.id,Number(d.version),{defaultBranch:d.defaultBranch,branchRule:d.branchRule,tagRule:d.tagRule,monorepoRoot:d.monorepoRoot,includePaths:d.includePaths,excludePaths:d.excludePaths,submodules:d.submodules,cloneDepth:d.cloneDepth,deployKeyId:d.deployKeyId,autoDeploy:d.autoDeploy,pullRequestPreviews:d.pullRequestPreviews,status:d.status,disabledReason:d.disabledReason,actorId:l.actor?.id})})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Source binding could not be updated."},409)}}if(v.pathname==="/api/sources/webhooks"&&m.method==="POST"){let d=await D(m),l=ee.getConnection(String(d.connectionId??""));if(!l||l.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{let h=ee.createWebhook({connectionId:String(d.connectionId??""),repositoryId:typeof d.repositoryId==="string"?d.repositoryId:void 0,repositoryFullName:String(d.repositoryFullName??""),events:Array.isArray(d.events)?d.events.map(String):void 0,secret:typeof d.secret==="string"?d.secret:void 0}),S=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||de,w=S?Hn(S,h.webhook):void 0,A=d.reconcile!==!1&&S?await $i(ee,h.webhook.id,S):h.webhook;return g({ok:!0,webhook:A,endpoint:w,endpointRevealOnce:!0},201)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Source webhook could not be created."},422)}}if(v.pathname==="/api/sources/webhooks"&&m.method==="PATCH"){let d=await D(m),l=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||de,h=ee.getWebhook(String(d.id??"")),S=h?ee.getConnection(h.connectionId):void 0;if(!h||!S||S.organizationId!==a.organization.id)return g({ok:!1,error:"Source webhook was not found."},404);if(!l)return g({ok:!1,error:"Set TS_CLOUD_WEBHOOK_BASE_URL to reconcile provider webhooks."},422);try{return g({ok:!0,webhook:await $i(ee,String(d.id??""),l)})}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"Source webhook could not be reconciled."},422)}}if(v.pathname==="/api/sources/webhooks"&&m.method==="DELETE"){let d=await D(m),l=ee.getWebhook(String(d.id??"")),h=l?ee.getConnection(l.connectionId):void 0;if(!l||!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Source webhook was not found."},404);try{return g({ok:!0,webhook:await Zl(ee,String(d.id??""))})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Source webhook could not be removed."},422)}}if(v.pathname==="/api/security/posture"&&m.method==="GET"){let d=Kt(a,String(B)),l=ce.listFindings({...d,limit:500});return g({scope:d,summary:ce.summary(d.organizationId,d.projectId,d.environmentId),findings:l,scans:ce.listScanRuns({...d,limit:100}),policies:ce.listPolicies(d.organizationId).filter((h)=>!h.environmentId||h.environmentId===d.environmentId),waivers:l.flatMap((h)=>ce.listWaivers(h.id)),decisions:ce.listDecisions(d.environmentId,50),actors:a.store.listMemberships(a.organization.id).map((h)=>a.store.getActor(h.actorId)).filter(Boolean)})}if(v.pathname==="/api/security/export"&&m.method==="GET")return g(ce.exportPosture(a.organization.id));if(v.pathname==="/api/security/scan"&&m.method==="POST"){let d=Kt(a,String(B)),l=await new xn(ce).run(new to,{...d,artifactRoot:t}),h=Gs(ce,d,Pe??{});return g({ok:!0,source:l,host:h,summary:ce.summary(d.organizationId,d.projectId,d.environmentId)})}if(v.pathname==="/api/security/review"&&m.method==="POST")try{let d=Kt(a,String(B));return g({ok:!0,...Ks(ce,{scope:d,desiredConfigHash:a.project.desiredConfigHash})})}catch(d){return g({ok:!1,error:d instanceof Error?d.message:"Security change review failed."},409)}if(v.pathname==="/api/security/policies"&&m.method==="POST"){let d=await D(m),l=Q(O);if(!l.actor)return g({ok:!1,error:"An organization actor is required."},403);try{let h=ce.createPolicy({organizationId:a.organization.id,environmentId:d.environmentId===null?void 0:String(d.environmentId??Kt(a,String(B)).environmentId),name:String(d.name??""),scannerFailMode:d.scannerFailMode==="open"?"open":"closed",requiredScanners:Array.isArray(d.requiredScanners)?d.requiredScanners.map(String):[],rules:Array.isArray(d.rules)?d.rules.map((S)=>({minimumSeverity:String(S.minimumSeverity),action:String(S.action),scannerId:S.scannerId?String(S.scannerId):void 0})):[],actorId:l.actor.id});return g({ok:!0,policy:h},201)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Security policy could not be created."},422)}}if(v.pathname==="/api/security/policies"&&m.method==="PATCH"){let d=await D(m),l=Q(O),h=ce.getPolicy(String(d.id??""));if(!l.actor||!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Security policy was not found."},404);try{return g({ok:!0,policy:ce.updatePolicy(h.id,Number(d.version),{name:typeof d.name==="string"?d.name:void 0,scannerFailMode:d.scannerFailMode==="open"||d.scannerFailMode==="closed"?d.scannerFailMode:void 0,requiredScanners:Array.isArray(d.requiredScanners)?d.requiredScanners.map(String):void 0,rules:Array.isArray(d.rules)?d.rules.map((S)=>({minimumSeverity:String(S.minimumSeverity),action:String(S.action),scannerId:S.scannerId?String(S.scannerId):void 0})):void 0,enabled:typeof d.enabled==="boolean"?d.enabled:void 0,actorId:l.actor.id})})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Security policy could not be updated."},409)}}if(v.pathname==="/api/security/waivers"&&m.method==="POST"){let d=await D(m),l=Q(O);if(!l.actor)return g({ok:!1,error:"An organization actor is required."},403);try{return g({ok:!0,waiver:ce.createWaiver({findingId:String(d.findingId??""),policyId:typeof d.policyId==="string"?d.policyId:void 0,reason:String(d.reason??""),referenceUrl:typeof d.referenceUrl==="string"?d.referenceUrl:void 0,expiresAt:String(d.expiresAt??""),actorId:l.actor.id})},201)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Security waiver could not be created."},422)}}if(v.pathname==="/api/security/waivers"&&m.method==="DELETE"){let d=await D(m),l=Q(O);if(!l.actor)return g({ok:!1,error:"An organization actor is required."},403);try{return g({ok:!0,waiver:ce.revokeWaiver(String(d.id??""),l.actor.id)})}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Security waiver could not be revoked."},404)}}if(v.pathname==="/api/security/findings"&&m.method==="PATCH"){let d=await D(m),l=Q(O),h=ce.getFinding(String(d.id??""));if(!l.actor||!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Security finding was not found."},404);try{let S=d.action==="acknowledge"?ce.acknowledgeFinding(h.id,l.actor.id):ce.assignFinding(h.id,typeof d.ownerActorId==="string"&&d.ownerActorId?d.ownerActorId:void 0,l.actor.id);return g({ok:!0,finding:S})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Security finding could not be updated."},422)}}if(v.pathname==="/api/security/comments"&&m.method==="POST"){let d=await D(m),l=Q(O);if(!l.actor)return g({ok:!1,error:"An organization actor is required."},403);try{return g({ok:!0,comment:ce.addComment({findingId:String(d.findingId??""),actorId:l.actor.id,body:String(d.body??""),referenceUrl:typeof d.referenceUrl==="string"?d.referenceUrl:void 0})},201)}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Comment could not be saved."},422)}}if(v.pathname==="/api/auth/sessions"&&m.method==="GET"){let d=Oe.resolveSession(m);return g({currentSessionId:d?.id,sessions:d?U.listSessions(d.identityId,{includeInactive:!0}):[]})}if(v.pathname==="/api/auth/sessions"&&m.method==="DELETE"){let d=await D(m),l=Oe.resolveSession(m);if(!l)return g({ok:!1,error:"Sign in again to manage sessions."},401);let h=String(d.id??""),S=U.revokeSession(l.identityId,h),w=h===l.id&&S?{"set-cookie":ia({secure:jr})}:void 0;return g({ok:S,signedOut:h===l.id&&S},S?200:404,w)}if(v.pathname==="/api/auth/sessions/revoke-others"&&m.method==="POST"){let d=Oe.resolveSession(m);if(!d)return g({ok:!1,error:"Sign in again to manage sessions."},401);return g({ok:!0,revoked:U.revokeOtherSessions(d.identityId,d.id)})}if(v.pathname==="/api/auth/password/change"&&m.method==="POST"){let d=await D(m),l=String(d.currentPassword??""),h=String(d.password??""),S=Q(O),w=S.actor?U.getIdentityByActor(S.actor.id):void 0;if(!w||!Qt(l,w.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);if(h.length<12)return g({ok:!1,error:"New password must be at least 12 characters."},422);if(Qt(h,w.passwordHash))return g({ok:!1,error:"Choose a different password."},409);let A=en(h),I=U.updatePassword(w.id,A);aa(t,I.username,A);let k=wo(I.id,m,oe.requestIP(m)?.address??"unknown");return a.store.appendEvent({organizationId:a.organization.id,actorId:I.actorId,type:"auth.password.changed"}),g({ok:!0,message:"Password changed and other sessions were signed out."},200,{"set-cookie":Si(k.token,{secure:jr,maxAgeMs:Jr})})}if(v.pathname==="/api/auth/mfa/enroll"&&m.method==="POST"){let d=await D(m),l=Oe.resolveSession(m),h=Q(O),S=h.actor?U.getIdentityByActor(h.actor.id):void 0;if(!l||!S)return g({ok:!1,error:"Sign in again before enabling MFA."},401);if(!Qt(String(d.password??""),S.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);try{let w=U.beginTotpEnrollment(S.id,{issuer:a.organization.name});return a.store.appendEvent({organizationId:a.organization.id,actorId:S.actorId,type:"auth.mfa.enrollment.started"}),g({factor:w.factor,secret:w.secret,uri:w.uri})}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"MFA enrollment failed."},409)}}if(v.pathname==="/api/auth/mfa/verify"&&m.method==="POST"){let d=await D(m),l=Oe.resolveSession(m),h=Q(O),S=h.actor?U.getIdentityByActor(h.actor.id):void 0;if(!l||!S)return g({ok:!1,error:"Sign in again before enabling MFA."},401);try{let w=U.verifyTotpEnrollment(S.id,String(d.code??""));return U.markSessionStepUp(l.id,!0),a.store.appendEvent({organizationId:a.organization.id,actorId:S.actorId,type:"auth.mfa.enabled",payload:{recoveryCodeCount:w.recoveryCodes.length}}),g(w)}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"MFA enrollment failed."},422)}}if(v.pathname==="/api/auth/mfa"&&m.method==="DELETE"){let d=await D(m),l=Oe.resolveSession(m),h=Q(O),S=h.actor?U.getIdentityByActor(h.actor.id):void 0;if(!l||!S||!Qt(String(d.password??""),S.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);let w=U.verifyMfaCode(S.id,String(d.code??""));if(!w.valid||!w.method)return g({ok:!1,error:"Authenticator or recovery code is incorrect."},401);return U.disableMfa(S.id),U.revokeOtherSessions(S.id,l.id),U.markSessionStepUp(l.id),a.store.appendEvent({organizationId:a.organization.id,actorId:S.actorId,type:"auth.mfa.disabled",payload:{method:w.method}}),g({ok:!0})}if(v.pathname==="/api/auth/step-up"&&m.method==="POST"){let d=await D(m),l=Oe.resolveSession(m),h=Q(O),S=h.actor?U.getIdentityByActor(h.actor.id):void 0;if(!l||!S||!Qt(String(d.password??""),S.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);let w=U.getMfaFactor(S.id);if(w?.state==="active"){if(!U.verifyMfaCode(S.id,String(d.code??"")).valid)return g({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}let A=U.markSessionStepUp(l.id,w?.state==="active");return a.store.appendEvent({organizationId:a.organization.id,actorId:S.actorId,type:"auth.step_up.succeeded",payload:{mfa:w?.state==="active"}}),g({ok:!0,recentAuthAt:A.recentAuthAt})}if(v.pathname==="/api/terminal"){if(!N)return g({ok:!1,error:"The web terminal is disabled."},403);if(oe.upgrade(m))return;return va("WebSocket upgrade failed",400)}if(v.pathname==="/api/health"){let d=a.store.health();return g({ok:!0,cwd:t,environment:B,environments:p,uiRoot:await Zt(O,B),liveData:W.size>0,terminal:N,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/"),controlPlane:{schemaVersion:d.schemaVersion,supportedSchemaVersion:d.supportedSchemaVersion,integrity:d.integrity,pendingRetryableOperations:d.pendingRetryableOperations}})}if(v.pathname==="/api/control-plane/operations"){let d=v.searchParams.get("state"),l=d&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(d)?d:void 0;return g({operations:a.store.listOperations({projectId:a.project.id,state:l,kind:v.searchParams.get("kind")??void 0,limit:Number(v.searchParams.get("limit"))||100})})}if(v.pathname==="/api/queue"&&m.method==="GET"){let d=v.searchParams.get("state"),l=d&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(d)?d:void 0,h=Ee.list({projectId:a.project.id,state:l,limit:Number(v.searchParams.get("limit"))||250}).filter((S)=>jn(O,S.operation.id,"deployments:read")).map((S)=>{let w=S.operation.resourceId?a.store.getResource(S.operation.resourceId):void 0,A=S.operation.environmentId?a.store.listEnvironments(a.project.id).find((M)=>M.id===S.operation.environmentId):void 0,I=S.operation.actorId?a.store.getActor(S.operation.actorId):void 0,k=S.operation.input;return{...S,target:w?{id:w.id,name:w.name,slug:w.slug,kind:w.kind}:A?{id:A.id,name:A.name,slug:A.slug,kind:"environment"}:{id:a.project.id,name:a.project.name,slug:a.project.slug,kind:"project"},actor:I?{id:I.id,name:I.displayName,kind:I.kind}:void 0,commit:k.revision??k.source?.commitSha??null}});return g({operations:h,concurrency:Ee.limits})}if(v.pathname==="/api/queue/logs"&&m.method==="GET"){let d=String(v.searchParams.get("id")??"");if(!jn(O,d,"deployments:read"))return g({ok:!1,error:"Operation was not found in this scope."},404);let l=Ee.logs(d,{after:Number(v.searchParams.get("after"))||0,limit:Number(v.searchParams.get("limit"))||500});return g({entries:l,cursor:l.at(-1)?.sequence??(Number(v.searchParams.get("after"))||0),operation:a.store.getOperation(d)})}if(v.pathname==="/api/queue/stream"&&m.method==="GET"){let d=String(v.searchParams.get("id")??"");if(!jn(O,d,"deployments:read"))return g({ok:!1,error:"Operation was not found in this scope."},404);let l=m.headers.get("last-event-id")?.trim(),h=Number(l||v.searchParams.get("after")||0),S=new TextEncoder,w,A=!1,I=new ReadableStream({start(k){let M=()=>{if(A)return;let _=Oe.resolveUser(m);if(!_||!jn(_,d,"deployments:read")){if(A=!0,w)clearInterval(w);k.close();return}let re=Ee.logs(d,{after:h,limit:500});for(let Y of re)h=Y.sequence,k.enqueue(S.encode(`id: ${Y.sequence}
|
|
487
|
-
event: log
|
|
488
|
-
data: ${JSON.stringify(Y)}
|
|
489
|
-
|
|
490
|
-
`));let j=a.store.getOperation(d);if(j&&["succeeded","failed","cancelled","timed_out"].includes(j.state)&&Ee.logs(d,{after:h,limit:1}).length===0){if(A=!0,w)clearInterval(w);k.enqueue(S.encode(`event: complete
|
|
491
|
-
data: ${JSON.stringify({state:j.state,cursor:h})}
|
|
492
|
-
|
|
493
|
-
`)),k.close()}};if(M(),!A)w=setInterval(M,500);m.signal.addEventListener("abort",()=>{if(A=!0,w)clearInterval(w);try{k.close()}catch{}},{once:!0})},cancel(){if(A=!0,w)clearInterval(w)}});return new Response(I,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no"}})}if(v.pathname==="/api/queue/cancel"&&m.method==="POST"){let d=await D(m),l=String(d.id??"");if(!jn(O,l,"deployments:cancel"))return g({ok:!1,error:"Operation was not found or cannot be cancelled in this scope."},404);let h=He(a.store,O);try{return g({ok:!0,operation:Ee.requestCancellation(l,h.id)})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Cancellation failed."},409)}}if(v.pathname==="/api/queue/retry"&&m.method==="POST"){let d=await D(m),l=String(d.id??"");if(!jn(O,l,"deployments:create"))return g({ok:!1,error:"Operation was not found or cannot be retried in this scope."},404);let h=He(a.store,O);try{return g({ok:!0,operation:Ee.retry(l,String(d.errorClass??"manual"),{delayMs:Number(d.delayMs)||0,actorId:h.id})})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Retry failed."},409)}}if(v.pathname==="/api/queue/settings"&&m.method==="GET")return g({concurrency:Ee.limits});if(v.pathname==="/api/queue/settings"&&m.method==="PATCH"){let d=await D(m);if(d.confirm!=="update queue limits")return g({ok:!1,error:'Type "update queue limits" to confirm production concurrency changes.'},409);let l=He(a.store,O);return g({ok:!0,concurrency:Ee.configureConcurrency(d.concurrency??{},{organizationId:a.organization.id,actorId:l.id})})}if(v.pathname==="/api/queue/history"&&m.method==="DELETE"){let d=await D(m);if(d.confirm!=="clear completed")return g({ok:!1,error:'Type "clear completed" to confirm retained history cleanup.'},409);let l=He(a.store,O);return g({ok:!0,deleted:Ee.clearCompleted({projectId:a.project.id,before:typeof d.before==="string"?d.before:void 0,actorId:l.id})})}if(v.pathname==="/api/previews"&&m.method==="GET"){let d=je.previews.listInstances({projectId:a.project.id}).filter((S)=>Ye(O,S.resourceId,"deployments:read")),l=je.previews.listDefinitions(a.project.id).filter((S)=>Ye(O,S.resourceId,"project:read")),h=a.store.listResources(a.project.id).filter((S)=>S.kind==="application"&&Ye(O,S.id,"project:read")).map((S)=>({id:S.id,slug:S.slug,name:S.name,environmentId:S.environmentId}));return g({previews:d,definitions:l,resources:h,environments:[...a.environments.values()]})}if(v.pathname==="/api/releases"&&m.method==="GET"){let d=[...a.environments.values()],l=a.store.listResources(a.project.id).filter((w)=>Ye(O,w.id,"deployments:read")),h=new Set(l.map((w)=>w.id)),S=xt.releases.list({projectId:a.project.id}).filter((w)=>h.has(w.resourceId)).map((w)=>{let A=l.find((M)=>M.id===w.resourceId),I=d.find((M)=>M.id===w.environmentId),k=w.previousReleaseId?xt.releases.get(w.previousReleaseId):void 0;return{...w,resource:A?{id:A.id,name:A.name,slug:A.slug,provider:A.provider}:void 0,environment:I?{id:I.id,name:I.name,slug:I.slug,kind:I.kind}:void 0,artifact:xt.releases.getArtifact(w.artifactId),transitions:xt.releases.transitions(w.id),approvals:xt.releases.approvals(w.id),previous:k,comparison:k?xt.releases.compare(k.id,w.id):void 0,capabilities:Di({kind:w.kind,provider:A?.provider,hasHealthGate:!!w.healthGate,replicas:Number(w.manifest?.replicas)||1})}});return g({releases:S,resources:l.map((w)=>({id:w.id,name:w.name,slug:w.slug,environmentId:w.environmentId,provider:w.provider})),environments:d})}if(v.pathname==="/api/releases/action"&&m.method==="POST"){let d=await D(m),l=xt.releases.get(String(d.id??"")),h=String(d.action??"");if(!l||!Ye(O,l.resourceId,"deployments:create"))return g({ok:!1,error:"Release was not found in this scope."},404);let S=He(a.store,O);try{if(h==="activate")return g({ok:!0,operation:xt.enqueueActivation(l,{actorId:S.id})});if(h==="rollback"){let w=a.store.getResource(l.resourceId);if(d.confirm!==w?.slug)return g({ok:!1,error:`Type "${w?.slug??""}" to confirm rollback.`},409);return g({ok:!0,operation:xt.enqueueRollback(l,{actorId:S.id,targetReleaseId:typeof d.targetReleaseId==="string"?d.targetReleaseId:void 0})})}if(h==="approve"){let w=a.store.listEnvironments(l.projectId).find((A)=>A.id===l.environmentId);if(d.confirm!==w?.slug)return g({ok:!1,error:`Type "${w?.slug??""}" to confirm the environment gate.`},409);return g({ok:!0,release:xt.releases.approve(l.id,{actorId:S.id,decision:d.decision==="rejected"?"rejected":"approved",comment:typeof d.comment==="string"?d.comment:void 0})})}if(h==="pin")return g({ok:!0,release:xt.releases.pin(l.id,d.pinned!==!1,typeof d.reason==="string"?d.reason:void 0)});if(h==="promote"){let w=a.store.getResource(String(d.targetResourceId??"")),A=w?a.store.listEnvironments(l.projectId).find((I)=>I.id===w.environmentId):void 0;if(!w||!A||!Ye(O,w.id,"deployments:create"))return g({ok:!1,error:"Promotion target was not found in this scope."},404);if(d.confirm!==A.slug)return g({ok:!1,error:`Type "${A.slug}" to confirm promotion.`},409);return g({ok:!0,release:xt.releases.promote(l.id,{targetEnvironmentId:A.id,targetResourceId:w.id,config:d.config&&typeof d.config==="object"?d.config:{},strategy:typeof d.strategy==="string"?d.strategy:void 0,actorId:S.id,approvalRequired:d.approvalRequired===!0})})}return g({ok:!1,error:"Unsupported release action."},422)}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"Release action failed."},409)}}if(v.pathname==="/api/compose"&&m.method==="GET"){let d=Br.applications.list({projectId:a.project.id}).filter((l)=>Ye(O,l.resourceId,"applications:read")).map((l)=>({...l,services:Br.applications.services(l.id)}));return g({applications:d,templates:Do(),environments:[...a.environments.values()]})}if(v.pathname==="/api/compose/preview"&&m.method==="POST"){let d=await D(m),l=String(d.environmentId??"");if(!Ri(O,l,"applications:manage"))return g({ok:!1,error:"Environment was not found in this scope."},404);try{return g({ok:!0,result:Br.applications.preview(String(d.source??""),{name:String(d.name??""),slug:typeof d.slug==="string"?d.slug:void 0,projectId:a.project.id,environmentId:l})})}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Compose could not be parsed."},422)}}if((v.pathname==="/api/compose/import"||v.pathname==="/api/compose/template")&&m.method==="POST"){let d=await D(m),l=String(d.environmentId??"");if(!Ri(O,l,"applications:manage"))return g({ok:!1,error:"Environment was not found in this scope."},404);let h=He(a.store,O);try{let S=v.pathname.endsWith("/template")?Br.applications.fromTemplate(String(d.templateId??""),d.inputs&&typeof d.inputs==="object"?d.inputs:{},{name:String(d.name??""),projectId:a.project.id,environmentId:l,version:typeof d.templateVersion==="string"?d.templateVersion:void 0,createdByActorId:h.id}):Br.applications.import(String(d.source??""),{name:String(d.name??""),slug:typeof d.slug==="string"?d.slug:void 0,projectId:a.project.id,environmentId:l,createdByActorId:h.id});return g({ok:!0,application:S.application,diagnostics:S.parsed.diagnostics})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Compose application could not be saved."},422)}}if(v.pathname==="/api/compose/action"&&m.method==="POST"){let d=await D(m),l=Br.applications.get(String(d.id??"")),h=String(d.action??""),S=h==="delete"||h==="stop"?"deployments:cancel":"deployments:create";if(!l||!Ye(O,l.resourceId,S))return g({ok:!1,error:"Compose application was not found in this scope."},404);try{let w=He(a.store,O);return g({ok:!0,operation:Br.enqueue(l,h,{actorId:w.id,service:typeof d.service==="string"?d.service:void 0,replicas:Number.isFinite(Number(d.replicas))?Number(d.replicas):void 0,removeVolumes:d.removeVolumes===!0,confirmation:typeof d.confirm==="string"?d.confirm:void 0})})}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"Compose operation could not be queued."},409)}}if((v.pathname==="/api/compose/logs"||v.pathname==="/api/compose/shell")&&m.method==="POST"){let d=await D(m),l=Br.applications.get(String(d.id??"")),h=v.pathname.endsWith("/shell"),S=h?"runtime:terminal":"runtime:logs";if(!l||!Ye(O,l.resourceId,S))return g({ok:!1,error:"Compose service was not found in this scope."},404);let w=String(d.service??"");if(!l.manifest.spec.services[w])return g({ok:!1,error:"Compose service was not found."},404);if(h&&d.confirm!==w)return g({ok:!1,error:`Type "${w}" to run a service command.`},409);let A=a.store.listEnvironments(l.projectId).find((k)=>k.id===l.environmentId)?.slug;if(!A)return g({ok:!1,error:"Compose environment was not found."},404);let I=h?Vy(l.manifest,w,Array.isArray(d.command)?d.command.map(String):["sh"]):zy(l.manifest,w,Number(d.lines)||200);return g(await oo(o,A,I))}if(v.pathname==="/api/previews/definitions"&&m.method==="POST"){let d=await D(m),l=String(d.resourceId??"");if(!Ye(O,l,"config:write"))return g({ok:!1,error:"Application was not found in this scope."},404);let h=He(a.store,O);try{return g({ok:!0,definition:je.previews.createDefinition({...d,projectId:a.project.id,resourceId:l,baseEnvironmentId:String(d.baseEnvironmentId??""),domainPattern:String(d.domainPattern??""),createdByActorId:h.id})})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Preview policy could not be created."},409)}}if(v.pathname==="/api/previews/deploy"&&m.method==="POST"){let d=await D(m),l=je.previews.getDefinition(String(d.definitionId??""));if(!l||!Ye(O,l.resourceId,"deployments:create"))return g({ok:!1,error:"Preview policy was not found in this scope."},404);let h=He(a.store,O);try{let S=je.previews.upsert({definitionId:l.id,sourceProvider:"dashboard",repository:"dashboard",branch:String(d.branch??""),pullRequestNumber:Number(d.pullRequestNumber)||void 0,commitSha:String(d.commitSha??""),createdByActorId:h.id});return g({ok:!0,preview:S.preview,operation:je.enqueueDeploy(S.preview,{created:S.created,actorId:h.id})})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Preview could not be queued."},409)}}if(v.pathname==="/api/previews/destroy"&&m.method==="POST"){let d=await D(m),l=je.previews.getInstance(String(d.id??""));if(!l||!Ye(O,l.resourceId,"deployments:cancel"))return g({ok:!1,error:"Preview was not found in this scope."},404);if(d.confirm!==l.name)return g({ok:!1,error:`Type "${l.name}" to confirm tagged teardown.`},409);let h=He(a.store,O);return g({ok:!0,operation:je.enqueueDestroy(l,"dashboard",h.id)})}if(v.pathname==="/api/previews/extend"&&m.method==="POST"){let d=await D(m),l=je.previews.getInstance(String(d.id??""));if(!l||!Ye(O,l.resourceId,"deployments:create"))return g({ok:!1,error:"Preview was not found in this scope."},404);return g({ok:!0,preview:je.previews.extend(l.id,Number(d.hours))})}if(v.pathname==="/api/previews/rebuild"&&m.method==="POST"){let d=await D(m),l=je.previews.getInstance(String(d.id??""));if(!l||!Ye(O,l.resourceId,"deployments:create"))return g({ok:!1,error:"Preview was not found in this scope."},404);let h=He(a.store,O);return g({ok:!0,operation:je.enqueueDeploy(l,{actorId:h.id,reason:"manual_rebuild"})})}if(v.pathname==="/api/previews/cleanup"&&m.method==="POST"){let d=await D(m);if(!d.dryRun&&d.confirm!=="cleanup previews")return g({ok:!1,error:'Type "cleanup previews" to confirm teardown.'},409);let l=He(a.store,O);return g({ok:!0,...je.cleanup({dryRun:d.dryRun===!0,maxAgeHours:Number(d.maxAgeHours)||void 0,keepCount:Number(d.keepCount)||void 0,actorId:l.id})})}if(v.pathname==="/api/control-plane/events")return g({events:a.store.listEvents({organizationId:a.organization.id,projectId:a.project.id,operationId:v.searchParams.get("operationId")??void 0,correlationId:v.searchParams.get("correlationId")??void 0,afterSequence:Number(v.searchParams.get("afterSequence"))||void 0,limit:Number(v.searchParams.get("limit"))||200})});if(v.pathname==="/api/search"){let d=String(v.searchParams.get("q")??"").trim().slice(0,128),l=Ot.role==="member"?new Set(Object.keys(Ot.sites)):void 0,h=d?By(a.store,{projectId:a.project.id,query:d,allowedResourceSlugs:l,limit:Number(v.searchParams.get("limit"))||20}):[];return g({query:d,results:h,stale:!1})}if(v.pathname==="/api/search/preferences"&&m.method==="GET"){let d=`dashboard:${O.username.toLowerCase()}`;return g({savedFilters:a.store.listSavedFilters(d),navigation:a.store.listNavigation(d)})}if(v.pathname==="/api/search/preferences"&&m.method==="POST"){let d=`dashboard:${O.username.toLowerCase()}`,l=await D(m),h=String(l.action??"");if(h==="save-filter")return g({savedFilter:a.store.saveFilter(d,String(l.name??""),String(l.routeId??""),l.query??{})});if(h==="favorite")return g({navigation:a.store.setFavorite(d,String(l.entityType??""),String(l.entityId??""),l.favorite!==!1)});if(h==="visit")return g({navigation:a.store.recordNavigation(d,String(l.entityType??""),String(l.entityId??""))});return g({ok:!1,error:"Unknown search preference action."},422)}if(v.pathname==="/api/search/preferences"&&m.method==="DELETE"){let d=`dashboard:${O.username.toLowerCase()}`,l=await D(m);return g({ok:a.store.deleteSavedFilter(d,String(l.id??""))})}if(v.pathname==="/api/organization"&&m.method==="GET"){let d=a.store.listMemberships(a.organization.id,{includeRevoked:!0}).map((l)=>{let h=a.store.getActor(l.actorId);return{...l,actor:h?{id:h.id,displayName:h.displayName,externalId:h.externalId,disabledAt:h.disabledAt}:void 0,grants:a.store.listGrants(l.id)}});return g({organization:a.organization,project:a.project,environments:a.store.listEnvironments(a.project.id),resources:a.store.listResources(a.project.id).map((l)=>({id:l.id,environmentId:l.environmentId,kind:l.kind,slug:l.slug,name:l.name})),memberships:d,invitations:a.store.listInvitations(a.organization.id)})}if(v.pathname==="/api/organization/invitations"&&m.method==="GET")return g({invitations:a.store.listInvitations(a.organization.id)});if(v.pathname==="/api/organization/invitations"&&m.method==="POST"){let d=await D(m),l=ya(d.roleTemplate),h=go(d);if(!l||!h)return g({ok:!1,error:"Choose a valid role template and resource scope."},422);let S=Q(O);if(!S.actor||!S.membership)return g({ok:!1,error:"Your organization membership is unavailable."},403);if(l==="owner"&&(!Qt(String(d.password??""),O.passwordHash)||S.membership.roleTemplate!=="owner"))return g({ok:!1,error:"Owner invitations require an owner to re-enter their password."},401);try{let w=a.store.createInvitation({organizationId:a.organization.id,email:String(d.email??""),roleTemplate:l,scope:h,invitedByActorId:S.actor.id,expiresInMs:Number(d.expiresInMs)||void 0}),A=`${v.origin}/accept-invitation?token=${encodeURIComponent(w.token)}`,I=await Li(o,{to:w.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${A}
|
|
494
|
-
|
|
495
|
-
This link expires ${w.invitation.expiresAt} and can be used once.`});return g({invitation:w.invitation,token:w.token,acceptUrl:A,delivered:I},201)}catch(w){return g({ok:!1,error:w instanceof Error?w.message:"Invitation could not be created."},422)}}if(v.pathname==="/api/organization/invitations"&&m.method==="DELETE"){let d=await D(m),l=Q(O);try{return g({invitation:a.store.revokeInvitation(String(d.id??""),l.actor?.id)})}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Invitation could not be revoked."},409)}}if(v.pathname==="/api/organization/invitations/resend"&&m.method==="POST"){let d=await D(m),l=Q(O);try{let h=a.store.reissueInvitation(String(d.id??""),l.actor?.id),S=`${v.origin}/accept-invitation?token=${encodeURIComponent(h.token)}`,w=await Li(o,{to:h.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${S}
|
|
496
|
-
|
|
497
|
-
This replacement link expires ${h.invitation.expiresAt} and can be used once.`});return g({invitation:h.invitation,token:h.token,acceptUrl:S,delivered:w})}catch(h){return g({ok:!1,error:h instanceof Error?h.message:"Invitation could not be resent."},409)}}if(v.pathname==="/api/organization/memberships"&&m.method==="PATCH"){let d=await D(m),l=a.store.getMembership(String(d.id??"")),h=ya(d.roleTemplate),S=go(d);if(!l||l.organizationId!==a.organization.id)return g({ok:!1,error:"Membership was not found."},404);if(!h||!S)return g({ok:!1,error:"Choose a valid role template and resource scope."},422);let w=Q(O);if((l.roleTemplate==="owner"||h==="owner")&&(!Qt(String(d.password??""),O.passwordHash)||w.membership?.roleTemplate!=="owner"))return g({ok:!1,error:"Ownership changes require an owner to re-enter their password."},401);let I=a.store.resolveAuthorizationTarget(a.organization.id,S)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),k=a.store.listGrants(l.id),M=mo({membership:l,grants:k,target:I}),_={...l,roleTemplate:h,scope:S},re=mo({membership:_,grants:k,target:I}),j={gained:re.filter((Y)=>!M.includes(Y)),lost:M.filter((Y)=>!re.includes(Y))};if(d.preview===!0)return g({membership:l,proposed:{roleTemplate:h,scope:S},accessDiff:j});if(String(d.confirm??"")!==l.id)return g({ok:!1,error:`Confirm this change with membership ID ${l.id}.`,accessDiff:j},409);try{return g({membership:a.store.updateMembership({id:l.id,roleTemplate:h,scope:S,actorId:w.actor?.id}),accessDiff:j})}catch(Y){return g({ok:!1,error:Y instanceof Error?Y.message:"Membership could not be updated."},409)}}if(v.pathname==="/api/organization/memberships"&&m.method==="DELETE"){let d=await D(m),l=a.store.getMembership(String(d.id??""));if(!l||l.organizationId!==a.organization.id)return g({ok:!1,error:"Membership was not found."},404);if(String(d.confirm??"")!==l.id)return g({ok:!1,error:`Confirm removal with membership ID ${l.id}.`},409);let h=Q(O);if(l.roleTemplate==="owner"&&(h.membership?.roleTemplate!=="owner"||!Qt(String(d.password??""),O.passwordHash)))return g({ok:!1,error:"Removing an owner requires an owner to re-enter their current password."},401);try{return g({membership:a.store.revokeMembership(l.id,h.actor?.id)})}catch(S){return g({ok:!1,error:S instanceof Error?S.message:"Membership could not be removed."},409)}}if(v.pathname==="/api/organization/grants"&&m.method==="POST"){let d=await D(m),l=String(d.capability??""),h=d.effect==="deny"?"deny":d.effect==="allow"?"allow":void 0,S=go(d),w=Q(O);if(!h||!S||!Fo.includes(l))return g({ok:!1,error:"Choose a valid capability, effect, and resource scope."},422);try{return g({grant:a.store.upsertGrant({organizationId:a.organization.id,membershipId:String(d.membershipId??""),effect:h,capability:l,scope:S,actorId:w.actor?.id})},201)}catch(A){return g({ok:!1,error:A instanceof Error?A.message:"Grant could not be created."},422)}}if(v.pathname==="/api/organization/grants"&&m.method==="DELETE"){let d=await D(m),l=Q(O),h=a.store.getGrant(String(d.id??""));if(!h||h.organizationId!==a.organization.id)return g({ok:!1,error:"Grant was not found."},404);return g({ok:a.store.removeGrant(h.id,l.actor?.id)})}if(v.pathname==="/api/tags"&&m.method==="GET")return g({tags:a.store.listTags(a.project.id),assignments:a.store.listResourceTags(a.project.id)});if(v.pathname==="/api/tags"&&m.method==="POST"){let d=await D(m),l=a.store.upsertTag(a.project.id,String(d.name??""),String(d.color??"#5a8be0"));if(d.resourceId)a.store.assignTag(String(d.resourceId),l.id);return g({tag:l},201)}if(v.pathname==="/api/tags"&&m.method==="DELETE"){let d=await D(m);return a.store.removeTag(String(d.resourceId??""),String(d.tagId??"")),g({ok:!0})}if(v.pathname==="/"&&!Ry(v.pathname,Ot))return new Response(null,{status:302,headers:{location:`/server/sites?env=${encodeURIComponent(B)}`}});if(v.pathname==="/"&&Pe?.mode==="serverless")return new Response(null,{status:302,headers:{location:`/serverless?env=${encodeURIComponent(B)}`}});let Co=Ch(v.pathname);if(Co)return new Response(null,{status:308,headers:{location:`${Co}?env=${encodeURIComponent(B)}`}});if(v.pathname==="/api/env"&&m.method==="POST"){let d=await D(m),l=String(d.env??"");if(!p.includes(l))return g({ok:!1,error:`Unknown environment '${l}'.`,environments:p},404);return g({ok:!0,environment:l,environments:p,href:`?env=${encodeURIComponent(l)}`})}if(v.pathname==="/api/config"){let d={...tA(o),environment:B,environments:p};return g(Th(d,Ot))}if(v.pathname==="/api/ssh-keys"&&m.method==="GET")return g({configPath:y,keys:fo(Ai(o))});if(v.pathname==="/api/ssh-keys"&&m.method==="POST"){if(!y)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await D(m),l=await ur(y,"utf8"),h=Ai(o),S=ib({configText:l,name:String(d.name??""),publicKey:String(d.publicKey??""),existingKeys:h});return await $n(y,S),Ey(o,[...h,{name:String(d.name??"").trim(),publicKey:String(d.publicKey??"").trim().replace(/\s+/g," ")}]),g({ok:!0,configPath:y,keys:fo(Ai(o))})}if(v.pathname==="/api/ssh-keys"&&m.method==="DELETE"){if(!y)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await D(m),l=String(d.name??v.searchParams.get("name")??""),h=await ur(y,"utf8"),S=Ai(o),w=ob({configText:h,name:l,existingKeys:S});return await $n(y,w),Ey(o,S.filter((A)=>A.name!==l.trim())),g({ok:!0,configPath:y,keys:fo(Ai(o))})}if(v.pathname==="/api/firewall"&&m.method==="GET")return g({configPath:y,alwaysOpen:[22,80,443],ports:Uu(o)});if(v.pathname==="/api/firewall"&&m.method==="POST"){if(!y)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await D(m),l=Number(d.port);if(!ao(l))return g({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let h=Uu(o),S=await ur(y,"utf8");try{await $n(y,Oh(S,l,h))}catch(I){return g({ok:!1,error:I?.message??String(I)},422)}let w=Nn([...h,l]);Ty(o,w);let A=d.apply===!1?null:await oo(o,B,`ufw allow ${l}/tcp`).catch((I)=>({ok:!1,error:String(I?.message??I)}));return g({ok:!0,configPath:y,ports:w,apply:A})}if(v.pathname==="/api/firewall"&&m.method==="DELETE"){if(!y)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await D(m),l=Number(d.port??v.searchParams.get("port"));if(!ao(l))return g({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let h=Uu(o),S=await ur(y,"utf8");await $n(y,_h(S,l,h));let w=Nn(h.filter((I)=>I!==l));Ty(o,w);let A=d.apply===!1?null:await oo(o,B,`ufw delete allow ${l}/tcp`).catch((I)=>({ok:!1,error:String(I?.message??I)}));return g({ok:!0,configPath:y,ports:w,apply:A})}if(v.pathname==="/api/sites"&&m.method==="POST"){if(!y)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await D(m),l=String(d.name??"").trim(),h=String(d.root??"").trim();if(!l||!h)return g({ok:!1,error:"Site name and root are required."},422);let S={deploy:d.deploy==="bucket"?"bucket":"server",root:h,path:String(d.path??"").trim()||void 0,domain:String(d.domain??"").trim()||void 0,build:String(d.build??"").trim()||void 0,start:String(d.start??"").trim()||void 0,port:d.port?Number(d.port):void 0,type:String(d.type??"").trim()||void 0};if(S.port!==void 0&&(!Number.isInteger(S.port)||S.port<1||S.port>65535))return g({ok:!1,error:"Port must be a number between 1 and 65535."},422);let w=await ur(y,"utf8"),A=ty({configText:w,name:l,root:S.root,domain:S.domain,path:S.path,deploy:S.deploy,build:S.build,start:S.start,port:S.port,type:S.type});return await $n(y,A),HT(o,l,Object.fromEntries(Object.entries(S).filter(([,I])=>I!==void 0))),Pe=await Mn(o,B),C.set(B,Pe),g({ok:!0,configPath:y,site:l,data:Pe})}if(v.pathname==="/api/sites"&&m.method==="DELETE"){if(!y)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await D(m),l=String(d.name??v.searchParams.get("name")??"").trim();if(!l||!o.sites?.[l])return g({ok:!1,error:`Site '${l}' was not found.`},404);let h=await ur(y,"utf8");return await $n(y,ry({configText:h,name:l})),delete o.sites[l],Pe=await Mn(o,B),C.set(B,Pe),g({ok:!0,configPath:y,site:l,data:Pe})}if(v.pathname==="/api/sites"&&m.method==="PATCH"){if(!y)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await D(m),l=String(d.name??"").trim(),h=o.sites?.[l];if(!l||!h)return g({ok:!1,error:`Site '${l}' was not found.`},404);if(Ot.role==="member"){let A=Rh(d);if(!A.ok)return g({ok:!1,error:A.error},403);let I=Ph({siteName:l,body:d,sites:o.sites??{},ownSites:Object.keys(Ot.sites)});if(!I.ok)return g({ok:!1,error:I.error},409)}if(d.port!==void 0&&d.port!==null&&d.port!==""&&(!Number.isInteger(Number(d.port))||Number(d.port)<1||Number(d.port)>65535))return g({ok:!1,error:"Port must be a number between 1 and 65535."},422);if(typeof d.domain==="string"&&d.domain.trim()&&!Lu(d.domain.trim()))return g({ok:!1,error:`Domain '${d.domain.trim()}' is not a valid hostname.`},422);let S=await ur(y,"utf8"),w=(A,I)=>{S=ny({configText:S,siteName:l,key:A,valueText:I})};if(d.ssl!==void 0)w("ssl",iy(d.ssl)),h.ssl=d.ssl;if(d.env!==void 0&&d.env&&typeof d.env==="object")w("env",sy(d.env)),h.env=d.env;if(d.aliases!==void 0&&Array.isArray(d.aliases)){let A=d.aliases.map((I)=>String(I));w("aliases",ay(A)),h.aliases=A.map((I)=>I.trim().toLowerCase()).filter(Boolean)}if(d.redirects!==void 0&&d.redirects&&typeof d.redirects==="object")w("redirects",cy(d.redirects)),h.redirects=d.redirects;for(let A of["domain","path","build","start","type","root","php"])if(typeof d[A]==="string"&&d[A].trim())w(A,oy(String(d[A]).trim())),h[A]=String(d[A]).trim();if(d.port!==void 0&&d.port!==null&&d.port!=="")w("port",String(Number(d.port))),h.port=Number(d.port);return await $n(y,S),Pe=await Mn(o,B),C.set(B,Pe),g({ok:!0,configPath:y,site:l,data:Pe})}if(v.pathname==="/api/sites/deploy"&&m.method==="POST"){let d=await D(m),l=String(d.name??"").trim();if(!l||!o.sites?.[l])return g({ok:!1,error:`Site '${l}' was not found.`},404);if(d.confirm!==l)return g({ok:!1,error:`Type "${l}" to deploy this site.`},409);let h=Kt(a,String(B));await new xn(ce).run(new to,{...h,artifactRoot:t}),Gs(ce,h,Pe??{});let S=Ks(ce,{scope:h,desiredConfigHash:a.project.desiredConfigHash});if(S.decision.outcome==="block")return g({ok:!1,error:`Deployment blocked by security policy: ${S.decision.explanation}`,securityReview:S},409);let w={id:`deploy:${l}`,label:`Deploy ${l}`,description:`Deploy the ${l} site for ${B}.`,command:["deploy","--env",B,"--site",l,"--yes"],mutates:!0},A=await Dr({controlPlane:a,environment:B,actor:O,kind:"dashboard.site.deploy",resourceSlug:l,input:{site:l},execute:()=>zu(w,{cwd:t,cliEntry:i})});return g({...A.result,controlPlaneOperation:A.operation,securityReview:S})}if(v.pathname==="/api/actions")return g(db(B));if(v.pathname==="/api/server/operations")return g(da(o,Pe));if(v.pathname==="/api/runtime/workloads"&&m.method==="GET"){let d=await Ht(o,B);return g(d)}if(v.pathname==="/api/runtime/logs"&&m.method==="GET"){let d=String(v.searchParams.get("workload")??"");if(!d)return g({ok:!1,error:"A workload query parameter is required."},422);let l=Math.min(1000,Math.max(1,Number(v.searchParams.get("limit"))||200));try{return g(await new cr(o,B).logs(d,{limit:l}))}catch(h){return g({ok:!1,error:String(h?.message??h)},404)}}if(v.pathname==="/api/runtime/log-sessions"&&m.method==="POST"){let d=await D(m),l=String(d.workloadId??"");if(!l)return g({ok:!1,error:"A workloadId is required."},422);let h=await Ht(o,B),S=h.workloads.find((I)=>I.id===l);if(!S)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);if(!S.capabilities.logs.supported)return g({ok:!1,error:S.capabilities.logs.reason??"Logs are unsupported for this workload."},409);let w=new cr(o,B,{inventory:async()=>h}),A=ze.create("logs",l);return(async()=>{let I=new Date(Date.now()-Math.min(3600000,Math.max(1000,Number(d.sinceMs)||60000)));try{for(let k=0;k<200&&!ze.signal(A.id)?.aborted;k++){let M=await w.logs(l,{limit:Math.min(500,Math.max(1,Number(d.limit)||200)),since:I});for(let _ of M.lines)if(ze.append(A.id,`${_.timestamp?`${_.timestamp} `:""}${_.message}
|
|
498
|
-
`),_.timestamp)I=new Date(Math.max(I.getTime(),new Date(_.timestamp).getTime()+1));await Bun.sleep(3000)}if(!ze.signal(A.id)?.aborted)ze.close(A.id,"complete")}catch(k){ze.append(A.id,k instanceof Error?k.message:String(k),"stderr"),ze.close(A.id,"failed",k instanceof Error?k.message:String(k))}})(),g({ok:!0,session:A,streamUrl:`/api/runtime/log-stream?id=${encodeURIComponent(A.id)}&workload=${encodeURIComponent(l)}`},201)}if((v.pathname==="/api/runtime/log-stream"||v.pathname==="/api/runtime/exec-stream")&&m.method==="GET"){let d=String(v.searchParams.get("id")??""),l=String(v.searchParams.get("workload")??""),h=Number(m.headers.get("last-event-id")??v.searchParams.get("after")??0)||0,S=ze.read(d,l,h),w=v.pathname.includes("exec")?"exec":"logs";if(!S||S.kind!==w)return g({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return BT(ze,S,h,m.signal)}if((v.pathname==="/api/runtime/log-sessions"||v.pathname==="/api/runtime/exec-sessions")&&m.method==="DELETE"){let d=await D(m),l=ze.cancel(String(d.id??""),String(d.workloadId??""));if(!l)return g({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return g({ok:!0,session:l})}if(v.pathname==="/api/runtime/exec-sessions"&&m.method==="POST"){let d=await D(m),l=String(d.workloadId??""),h=await Ht(o,B),S=h.workloads.find((k)=>k.id===l);if(!S)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);let w=Oe.resolveSession(m),A=new cr(o,B,{inventory:async()=>h}),I=ze.create("exec",l);return Dr({controlPlane:a,environment:B,actor:O,kind:"runtime.exec",resourceSlug:S.links.service,input:{workloadId:l,provider:S.provider,preset:d.preset?String(d.preset):null,freeForm:!!String(d.command??"").trim()},execute:()=>A.exec({workloadId:l,preset:["process","sockets","filesystem"].includes(String(d.preset))?String(d.preset):void 0,command:typeof d.command==="string"?d.command:void 0,confirm:String(d.confirm??""),recentAuth:!H||!!w&&U.isRecentlyAuthenticated(w)})}).then(({result:k,operation:M})=>{if(ze.append(I.id,`operation ${M.id}
|
|
499
|
-
`,"system"),k.stdout)ze.append(I.id,k.stdout,"stdout");if(k.stderr)ze.append(I.id,k.stderr,"stderr");ze.close(I.id,k.ok?"complete":"failed",k.error)}).catch((k)=>{let M=k instanceof Error?k.message:String(k);ze.append(I.id,M,"stderr"),ze.close(I.id,"failed",M)}),g({ok:!0,session:I,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(I.id)}&workload=${encodeURIComponent(l)}`},202)}if(v.pathname==="/api/runtime/files/read"&&m.method==="POST"){let d=await D(m),l=await Ht(o,B),h=Oe.resolveSession(m),S=await new cr(o,B,{inventory:async()=>l}).readFile({workloadId:String(d.workloadId??""),path:String(d.path??""),confirm:String(d.confirm??""),recentAuth:!H||!!h&&U.isRecentlyAuthenticated(h)});return g(S,S.ok?200:409)}if(v.pathname==="/api/runtime/files/write"&&m.method==="POST"){let d=await D(m),l=await Ht(o,B),h=String(d.workloadId??""),S=l.workloads.find((k)=>k.id===h);if(!S)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);let w=Oe.resolveSession(m),A=new cr(o,B,{inventory:async()=>l}),I=await Dr({controlPlane:a,environment:B,actor:O,kind:"runtime.file.write",resourceSlug:S.links.service,input:{workloadId:h,provider:S.provider,path:String(d.path??""),bytes:Buffer.from(String(d.contentBase64??""),"base64").byteLength},execute:()=>A.writeFile({workloadId:h,path:String(d.path??""),contentBase64:String(d.contentBase64??""),confirm:String(d.confirm??""),recentAuth:!H||!!w&&U.isRecentlyAuthenticated(w)})});return g({...I.result,controlPlaneOperation:I.operation},I.result.ok?200:409)}if(v.pathname==="/api/runtime/operations"&&m.method==="POST"){let d=await D(m),l=String(d.workloadId??""),h=String(d.action??"");if(!l||!["start","stop","restart","redeploy","scale","inspect"].includes(h))return g({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let S=await Ht(o,B),w=S.workloads.find((M)=>M.id===l);if(!w)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);let A=Oe.resolveSession(m),I=new cr(o,B,{inventory:async()=>S}),k=await Dr({controlPlane:a,environment:B,actor:O,kind:`runtime.${h}`,resourceSlug:w.links.service,input:{workloadId:l,provider:w.provider,action:h,replicas:d.replicas==null?null:Number(d.replicas)},execute:()=>I.run({workloadId:l,action:h,replicas:d.replicas==null?void 0:Number(d.replicas),confirm:String(d.confirm??""),recentAuth:!H||!!A&&U.isRecentlyAuthenticated(A)})});return g({...k.result,controlPlaneOperation:k.operation},k.result.ok?200:409)}if(v.pathname.startsWith("/api/protection")){let d=O.role==="admin"||Io(O,"security:read"),l=O.role==="admin"||Io(O,"security:manage");if(!d)return g({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:h,describePosture:S}=await import("./chunk-g3kp5ddx.js"),w=new h(a.store),A=()=>{if(!l)throw Error("Changing protection controls requires security:manage.")};if(v.pathname==="/api/protection"&&m.method==="GET"){let I=w.current();return g({ok:!0,posture:S(I),controls:I,raw:w.raw()})}if(v.pathname==="/api/protection/attack-mode"&&m.method==="POST"){A();let I=await D(m);if(I.enabled===!1)return g({ok:!0,disabled:w.disableAttackMode()});return g({ok:!0,control:w.enableAttackMode({hours:I.hours==null?void 0:Number(I.hours),reason:String(I.reason??"Enabled from the dashboard."),actorId:Q(O).actor?.id})})}if(v.pathname==="/api/protection/pause"&&m.method==="POST"){A();let I=await D(m);if(I.enabled===!1)return g({ok:!0,resumed:w.resumeMitigations()});return g({ok:!0,control:w.pauseMitigations({hours:I.hours==null?void 0:Number(I.hours),reason:String(I.reason??""),actorId:Q(O).actor?.id})})}if(v.pathname==="/api/protection/ip-rules"&&m.method==="GET")return g({ok:!0,ipRules:w.current().ipRules});if(v.pathname==="/api/protection/ip-rules"&&(m.method==="POST"||m.method==="DELETE")){A();let I=await D(m),k=I.list==="allow"?"allow":"block",M=m.method==="POST"?w.addIpRule(k,String(I.cidr??"")):w.removeIpRule(k,String(I.cidr??""));return g({ok:!0,ipRules:M})}return g({ok:!1,error:"Protection endpoint was not found."},404)}if(v.pathname.startsWith("/api/spend/")||v.pathname==="/api/usage"){let d=await mb(),l=d.store,h=d.service,S=d.gate,w=O.role==="admin"||Io(O,"billing:read"),A=O.role==="admin"||Io(O,"billing:manage");if(!w)return g({ok:!1,error:"Spend data requires the billing:read capability."},403);let I=a.environments.get(B),k={organizationId:a.organization.id,projectId:a.project.id,environmentId:I?.id},M=()=>{if(!A)throw Error("Changing a budget requires the billing:manage capability.")};if(v.pathname==="/api/usage"&&m.method==="GET")return g({ok:!0,...h.usageReport({organizationId:k.organizationId,projectId:k.projectId,period:v.searchParams.get("period")??"monthly",timezone:v.searchParams.get("timezone")??void 0})});if(v.pathname==="/api/spend/budgets"&&m.method==="GET")return g({ok:!0,budgets:l.listBudgets({organizationId:k.organizationId,projectId:k.projectId}).map((_)=>({..._,status:h.status(_)}))});if(v.pathname==="/api/spend/budgets"&&m.method==="POST"){M();let _=await D(m),re=String(_.scope??"project"),j=l.createBudget({organizationId:k.organizationId,projectId:re==="organization"?void 0:k.projectId,environmentId:re==="environment"?k.environmentId:void 0,name:String(_.name??"").trim(),period:_.period??"monthly",timezone:_.timezone?String(_.timezone):void 0,softLimitCents:_.softLimitCents==null?void 0:Math.round(Number(_.softLimitCents)),hardLimitCents:_.hardLimitCents==null?void 0:Math.round(Number(_.hardLimitCents)),graceSeconds:_.graceSeconds==null?void 0:Number(_.graceSeconds),dryRun:_.dryRun!==!1});return g({ok:!0,budget:j})}if(v.pathname==="/api/spend/budgets"&&m.method==="PATCH"){M();let _=await D(m),re=String(_.id??""),j=l.getBudget(re);if(!j||j.organizationId!==k.organizationId)return g({ok:!1,error:"Budget was not found."},404);return g({ok:!0,budget:l.updateBudget(re,{softLimitCents:_.softLimitCents==null?j.softLimitCents:Math.round(Number(_.softLimitCents)),hardLimitCents:_.hardLimitCents==null?j.hardLimitCents:Math.round(Number(_.hardLimitCents)),enabled:_.enabled==null?j.enabled:_.enabled===!0,dryRun:_.dryRun==null?j.dryRun:_.dryRun===!0},_.expectedVersion==null?void 0:Number(_.expectedVersion))})}if(v.pathname==="/api/spend/budgets"&&m.method==="DELETE"){M();let _=await D(m),re=String(_.id??""),j=l.getBudget(re);if(!j||j.organizationId!==k.organizationId)return g({ok:!1,error:"Budget was not found."},404);let Y=S.closeBudget(re);return l.deleteBudget(re),g({ok:!0,deleted:!0,lifted:Y})}if(v.pathname==="/api/spend/check"&&m.method==="POST"){M();let _=await D(m),{SpendRunner:re}=await import("./chunk-grepda40.js"),j=new re({controlPlane:a.store,store:l,alerts:ne});if(_.apply!==!0){let F=l.budgetsForScope(k.organizationId,k.projectId,k.environmentId);return g({ok:!0,applied:!1,preview:F.map((J)=>h.status(J))})}let Y=await j.run({...k,environmentKind:I?.kind});return g({ok:!0,applied:!0,result:Y})}if(v.pathname==="/api/spend/enforcement"&&m.method==="GET")return g({ok:!0,enforcement:S.listUnder({organizationId:k.organizationId})});if(v.pathname==="/api/spend/release"&&m.method==="POST"){M();let _=await D(m),re=S.close(String(_.budgetId??""),_.action);return g({ok:re,released:re,note:re?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(v.pathname==="/api/spend/anomalies"&&m.method==="GET")return g({ok:!0,anomalies:l.listAnomalies({organizationId:k.organizationId,projectId:k.projectId,unacknowledgedOnly:v.searchParams.get("unacknowledged")==="true"})});if(v.pathname==="/api/spend/anomalies/acknowledge"&&m.method==="POST"){M();let _=await D(m);return g({ok:!0,acknowledged:l.acknowledgeAnomaly(String(_.id??""))})}return g({ok:!1,error:"Spend endpoint was not found."},404)}if(v.pathname.startsWith("/api/health/")||v.pathname.startsWith("/api/alerts")||v.pathname.startsWith("/api/notifications/")){let d=a.environments.get(B),l=a.store.listResources(a.project.id,d?.id),h=O.role==="admin"||!!d&&Ri(O,d.id,"runtime:read")?l:l.filter((I)=>Ye(O,I.id,"runtime:read")),S=(I)=>!I||h.some((k)=>k.id===I),w=(I)=>{if(!I)return;let k=l.find((M)=>M.id===I||M.slug===I);if(!k)throw Error("Alert resource was not found.");if(!S(k.id))throw Error("Alert resource is outside your authorized scope.");return k.id},A=Q(O).actor;if(v.pathname==="/api/health/checks"&&m.method==="GET")return g({ok:!0,checks:ne.listHealthChecks(a.project.id,d?.id).filter((I)=>S(I.resourceId)).map((I)=>({...I,results:ne.listHealthResults(I.id,20)}))});if(v.pathname==="/api/health/checks"&&m.method==="POST"){let I=await D(m),k=String(I.kind??"http");if(k==="command"&&O.role!=="admin")return g({ok:!1,error:"Command health checks require an administrator."},403);let M={method:String(I.config?.method??"GET").toUpperCase().slice(0,10),path:I.config?.path?String(I.config.path).slice(0,500):void 0,port:I.config?.port==null?void 0:Number(I.config.port),command:Array.isArray(I.config?.command)?I.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(I.config?.expectedStatuses)?I.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:I.config?.expectedBody?String(I.config.expectedBody).slice(0,500):void 0};return g({ok:!0,check:ne.createHealthCheck({projectId:a.project.id,environmentId:d?.id,resourceId:w(I.resourceId??I.resource),name:String(I.name??""),kind:k,target:String(I.target??""),config:M,intervalSeconds:Number(I.intervalSeconds)||60,timeoutSeconds:Number(I.timeoutSeconds)||10,failureThreshold:Number(I.failureThreshold)||3,recoveryThreshold:Number(I.recoveryThreshold)||2,regions:Array.isArray(I.regions)?I.regions.map(String):["local"],enabled:I.enabled!==!1})},201)}if(v.pathname==="/api/health/checks"&&m.method==="PATCH"){let I=await D(m),k=ne.getHealthCheck(String(I.id??""));if(!k||!S(k.resourceId))return g({ok:!1,error:"Health check was not found."},404);return g({ok:!0,check:ne.setHealthCheckEnabled(k.id,I.enabled!==!1)})}if(v.pathname==="/api/health/checks/test"&&m.method==="POST"){let I=await D(m),k=ne.getHealthCheck(String(I.id??""));if(!k||!S(k.resourceId))return g({ok:!1,error:"Health check was not found."},404);return g({ok:!0,productionIncidentCreated:!1,result:await new Ei(ne).probe(k)})}if(v.pathname==="/api/health/checks/run"&&m.method==="POST"){let I=await D(m),k=ne.getHealthCheck(String(I.id??""));if(!k||!S(k.resourceId))return g({ok:!1,error:"Health check was not found."},404);let M=await new Ei(ne).runAndEvaluate(k),_=[];for(let re of M.evaluations.filter((j)=>j.notify&&j.alert)){let j=Dt.enqueue(a.organization.id,re.alert,re.transition);_.push(...await Dt.deliverAll(j))}return g({ok:!0,...M,deliveries:_})}if(v.pathname==="/api/alerts/rules"&&m.method==="GET")return g({ok:!0,rules:ne.listRules(a.project.id,d?.id).filter((I)=>S(I.resourceId))});if(v.pathname==="/api/alerts/rules"&&m.method==="POST"){let I=await D(m),k=I.healthCheckId?ne.getHealthCheck(String(I.healthCheckId)):void 0;if(I.healthCheckId&&(!k||!S(k.resourceId)))return g({ok:!1,error:"Health check was not found."},404);return g({ok:!0,rule:ne.createRule({projectId:a.project.id,environmentId:d?.id,resourceId:w(I.resourceId??I.resource)??k?.resourceId,healthCheckId:k?.id,name:String(I.name??""),signal:String(I.signal??(k?"health":"")),operator:String(I.operator??(k?"unhealthy":"gt")),threshold:I.threshold==null?void 0:Number(I.threshold),recoveryThreshold:I.recoveryThreshold==null?void 0:Number(I.recoveryThreshold),windowMs:Number(I.windowMs)||300000,consecutive:Number(I.consecutive)||k?.failureThreshold||3,recoveryConsecutive:Number(I.recoveryConsecutive)||k?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(I.noDataPolicy))?I.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(I.severity))?I.severity:"warning",groupBy:Array.isArray(I.groupBy)?I.groupBy.map(String):[],labels:I.labels&&typeof I.labels==="object"?I.labels:{},enabled:I.enabled!==!1})},201)}if(v.pathname==="/api/alerts/rules"&&m.method==="PATCH"){let I=await D(m),k=ne.getRule(String(I.id??""));if(!k||!S(k.resourceId))return g({ok:!1,error:"Alert rule was not found."},404);return g({ok:!0,rule:ne.setRuleEnabled(k.id,I.enabled!==!1)})}if(v.pathname==="/api/alerts/evaluate"&&m.method==="POST")return g({ok:!0,...await Yu(d?.id)});if(v.pathname==="/api/alerts"&&m.method==="GET")return g({ok:!0,alerts:ne.listAlerts(a.project.id,{environmentId:d?.id,states:v.searchParams.getAll("state").length?v.searchParams.getAll("state"):void 0,limit:Number(v.searchParams.get("limit"))||200}).filter((I)=>S(I.resourceId)).map((I)=>({...I,deliveries:ne.listDeliveries({alertId:I.id,limit:50})}))});if(v.pathname==="/api/alerts/action"&&m.method==="POST"){let I=await D(m),k=ne.getAlert(String(I.id??""));if(!k||!S(k.resourceId))return g({ok:!1,error:"Alert was not found."},404);let M=String(I.action??"");if(M==="acknowledge")return g({ok:!0,alert:ne.acknowledge(k.id,A?.id??"")});if(M==="assign")return g({ok:!0,alert:ne.assign(k.id,I.ownerActorId==="me"?A?.id:I.ownerActorId?String(I.ownerActorId):void 0,A?.id)});if(M==="silence"){if(O.role!=="admin")return g({ok:!1,error:"Silencing production alerts requires an administrator."},403);let _=Oe.resolveSession(m);if(H&&(!_||!U.isRecentlyAuthenticated(_)))return g({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return g({ok:!0,alert:ne.silenceAlert(k.id,String(I.until??""),A?.id)})}return g({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(v.pathname==="/api/alerts/silences"&&m.method==="POST"){let I=await D(m);return g({ok:!0,id:ne.createSilence({projectId:a.project.id,environmentId:d?.id,resourceId:w(I.resourceId??I.resource),matcher:I.matcher,reason:String(I.reason??""),startsAt:String(I.startsAt??new Date().toISOString()),endsAt:String(I.endsAt??""),timezone:String(I.timezone??"UTC"),actorId:A?.id})},201)}if(v.pathname==="/api/notifications/channels"&&m.method==="GET")return g({ok:!0,channels:ne.listChannels(a.organization.id)});if(v.pathname==="/api/notifications/channels"&&m.method==="POST"){let I=await D(m),k=String(I.kind??""),M=k==="email"?{to:I.config?.to,from:I.config?.from}:k==="telegram"?{chatId:String(I.config?.chatId??"")}:{};return g({ok:!0,channel:ne.createChannel({organizationId:a.organization.id,name:String(I.name??""),kind:k,config:M,credential:I.credential?String(I.credential):void 0,actorId:A?.id})},201)}if(v.pathname==="/api/notifications/channels"&&m.method==="PATCH"){let I=await D(m),k=String(I.id??"");if(I.credential)return g({ok:!0,channel:ne.rotateChannel(k,String(I.credential))});let M=String(I.status??"paused");if(!["active","paused","disabled"].includes(M))return g({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return g({ok:!0,channel:ne.setChannelStatus(k,M)})}if(v.pathname==="/api/notifications/channels/test"&&m.method==="POST"){let I=await D(m);return g({ok:!0,productionIncidentCreated:!1,result:await Dt.testChannel(String(I.id??""))})}if(v.pathname==="/api/notifications/routes"&&m.method==="GET")return g({ok:!0,routes:ne.listRoutes(a.organization.id)});if(v.pathname==="/api/notifications/routes"&&m.method==="POST"){let I=await D(m),k=Array.isArray(I.channelIds)?I.channelIds.map(String):[];if(k.some((M)=>ne.getChannel(M)?.organizationId!==a.organization.id))return g({ok:!1,error:"Route contains an unavailable channel."},422);return g({ok:!0,route:ne.createRoute({organizationId:a.organization.id,name:String(I.name??""),priority:Number(I.priority)||0,matcher:I.matcher&&typeof I.matcher==="object"?I.matcher:{},channelIds:k,quietHours:I.quietHours,groupWaitSeconds:Number(I.groupWaitSeconds)||30,reminderSeconds:I.reminderSeconds==null?void 0:Number(I.reminderSeconds),escalation:Array.isArray(I.escalation)?I.escalation:[],template:I.template?String(I.template):void 0,rateLimitPerMinute:Number(I.rateLimitPerMinute)||60,enabled:I.enabled!==!1})},201)}if(v.pathname==="/api/notifications/routes"&&m.method==="PATCH"){let I=await D(m),k=ne.getRoute(String(I.id??""));if(!k||k.organizationId!==a.organization.id)return g({ok:!1,error:"Notification route was not found."},404);return g({ok:!0,route:ne.setRouteEnabled(k.id,I.enabled!==!1)})}if(v.pathname==="/api/notifications/routes/preview"&&m.method==="POST"){let I=await D(m),M=(I.alertId?ne.getAlert(String(I.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:a.project.id,environmentId:d?.id,resourceId:w(I.resourceId??I.resource),dedupKey:"preview",groupKey:String(I.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(I.severity))?I.severity:"warning",title:String(I.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 g({ok:!0,productionIncidentCreated:!1,matches:Dt.preview(a.organization.id,M,String(I.eventType??"firing")).map((_)=>({route:_.route,channels:_.channels,quiet:_.quiet}))})}if(v.pathname==="/api/notifications/deliveries"&&m.method==="GET")return g({ok:!0,deliveries:ne.listDeliveries({alertId:v.searchParams.get("alertId")??void 0,states:v.searchParams.getAll("state"),limit:Number(v.searchParams.get("limit"))||200})});if(v.pathname==="/api/notifications/deliveries/retry"&&m.method==="POST"){let I=await D(m),k=ne.getDelivery(String(I.id??""));if(!k)return g({ok:!1,error:"Delivery was not found."},404);return ne.updateDelivery(k.id,{state:"retrying",attempt:Math.max(0,k.attempt-1),nextAttemptAt:new Date().toISOString()}),g({ok:!0,delivery:await Dt.deliver(k.id)})}}if(v.pathname.startsWith("/api/jobs")||v.pathname.startsWith("/api/workers")){let d=a.environments.get(B),l=a.store.listResources(a.project.id,d?.id),S=O.role==="admin"||!!d&&Ri(O,d.id,"automation:read")?l:l.filter((F)=>Ye(O,F.id,"automation:read")),w=(F)=>!F||S.some((J)=>J.id===F),A=Q(O).actor,I=C.get(B)??b,k=da(o,I),M=k.filter((F)=>!F.danger&&["scheduler","backup","worker"].includes(F.group)),_=Pr(o),re=()=>{let F=Oe.resolveSession(m);return!H||!!F&&U.isRecentlyAuthenticated(F)},j=(F)=>{if(!F||typeof F!=="object"||Array.isArray(F))return{};let J=Object.entries(F).slice(0,50);if(J.some(([,se])=>typeof se!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(se)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(J)},Y=(F,J,se)=>a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,resourceId:se,actorId:A?.id,type:`job.${F}`,payload:J});if(v.pathname==="/api/jobs/preview"&&m.method==="POST"){let F=await D(m);try{return g({ok:!0,productionExecutionCreated:!1,preview:yn(String(F.expression??""),String(F.timezone??"UTC"),new Date(F.from?String(F.from):Date.now()),Number(F.count)||5)})}catch(J){return g({ok:!1,error:J instanceof Error?J.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(v.pathname==="/api/jobs"&&m.method==="GET")return g({ok:!0,jobs:Qe.list(a.project.id,{environmentId:d?.id}).filter((F)=>w(F.resourceId)).map((F)=>({...F,preview:yn(F.normalizedExpression,F.timezone,new Date,5),capability:lc(F),lastExecution:Qe.listExecutions(F.id,1)[0]}))});if(v.pathname==="/api/jobs"&&m.method==="POST"){let F=await D(m),J=String(F.provider??(_==="serverless"?"eventbridge":"server")),se=_==="serverless"?"eventbridge":"server";if(J!==se)return g({ok:!1,error:`${_} environments accept ${se} schedules through this adapter.`},422);let le=F.operationId?String(F.operationId):void 0;if(J==="server"&&(!le||!M.some((Ve)=>Ve.id===le)))return g({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let ve=lc({provider:J,expression:String(F.expression??""),flexibleMinutes:Number(F.flexibleMinutes)||0,missedRunPolicy:F.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(F.overlapPolicy))?F.overlapPolicy:"forbid"});if(!ve.supported)return g({ok:!1,error:ve.notes.join(" ")},422);let Tt=F.resourceId?l.find((Ve)=>Ve.id===F.resourceId||Ve.slug===F.resourceId):void 0;if(F.resourceId&&(!Tt||!w(Tt.id)))return g({ok:!1,error:"Job resource was not found."},404);try{let Ve=J==="server"?{kind:"dashboard_operation",operationId:le}:{kind:"serverless_scheduler",action:"run"},Fr=Qe.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,resourceId:Tt?.id,name:String(F.name??""),provider:J,expression:String(F.expression??""),timezone:String(F.timezone??"UTC"),startsAt:F.startsAt?String(F.startsAt):void 0,endsAt:F.endsAt?String(F.endsAt):void 0,flexibleMinutes:Number(F.flexibleMinutes)||0,target:Ve,payloadRefs:j(F.payloadRefs),missedRunPolicy:F.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(F.overlapPolicy))?F.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(F.maxAttempts)||3,backoffSeconds:Number(F.backoffSeconds)||30,deadLetterRef:F.deadLetterRef?String(F.deadLetterRef):void 0},timeoutSeconds:Number(F.timeoutSeconds)||900,enabled:F.enabled!==!1,origin:"managed",ownerActorId:A?.id,observedState:{},reconciliationStatus:"pending"});return Y("created",{jobId:Fr.id,provider:Fr.provider,expression:Fr.normalizedExpression},Fr.resourceId),g({ok:!0,job:Fr,capability:ve},201)}catch(Ve){return g({ok:!1,error:Ve instanceof Error?Ve.message:"Scheduled job could not be created."},422)}}if(v.pathname==="/api/jobs"&&m.method==="PATCH"){let F=await D(m),J=Qe.get(String(F.id??""));if(!J||!w(J.resourceId))return g({ok:!1,error:"Scheduled job was not found."},404);if(J.origin==="config")return g({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let se=F.missedRunPolicy==null?void 0:String(F.missedRunPolicy),le=F.overlapPolicy==null?void 0:String(F.overlapPolicy);if(se&&!["skip","catch_up"].includes(se))return g({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(le&&!["allow","forbid","replace"].includes(le))return g({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let ve=Qe.updateSchedule(J.id,{expression:F.expression?String(F.expression):void 0,timezone:F.timezone?String(F.timezone):void 0,missedRunPolicy:se,overlapPolicy:le,timeoutSeconds:F.timeoutSeconds==null?void 0:Number(F.timeoutSeconds)});return Y("updated",{jobId:ve.id,expression:ve.normalizedExpression,version:ve.version},ve.resourceId),g({ok:!0,job:ve})}catch(ve){return g({ok:!1,error:ve instanceof Error?ve.message:"Scheduled job could not be updated."},422)}}if(v.pathname==="/api/jobs/action"&&m.method==="POST"){let F=await D(m),J=Qe.get(String(F.id??""));if(!J||!w(J.resourceId))return g({ok:!1,error:"Scheduled job was not found."},404);let se=String(F.action??"");if(se==="run"){let le=Qu.enqueue(J,{trigger:"manual",actorId:A?.id});return Y("run_queued",{jobId:J.id,executionId:le.id},J.resourceId),g({ok:!0,execution:le},202)}if(["disable","delete"].includes(se)&&d?.kind==="production"){if(String(F.confirm??"")!==se)return g({ok:!1,error:`Type "${se}" to confirm this production change.`},409);if(!re())return g({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(se==="enable"||se==="disable"){let le=Qe.setEnabled(J.id,se==="enable");return Y(se==="enable"?"enabled":"disabled",{jobId:J.id},J.resourceId),g({ok:!0,job:le})}if(se==="delete")try{return Qe.remove(J.id),Y("deleted",{jobId:J.id,name:J.name},J.resourceId),g({ok:!0,deleted:J.id})}catch(le){return g({ok:!1,error:le instanceof Error?le.message:"Scheduled job could not be deleted."},409)}return g({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(v.pathname==="/api/jobs/history"&&m.method==="GET"){let F=Qe.get(String(v.searchParams.get("jobId")??""));if(!F||!w(F.resourceId))return g({ok:!1,error:"Scheduled job was not found."},404);return g({ok:!0,executions:Qe.listExecutions(F.id,Number(v.searchParams.get("limit"))||100).map((J)=>({...J,logs:J.operationId?Ee.logs(J.operationId,{limit:500}):[]}))})}if(v.pathname==="/api/jobs/reconcile"&&m.method==="POST"){if(!d)return g({ok:!1,error:"Environment was not found."},404);let F=pc(Qe,o,{organization:a.organization,project:a.project,environment:d,resources:l});return Y("reconciled",F),g({ok:!0,reconciliation:F})}if(v.pathname==="/api/workers"&&m.method==="GET"){let F=Array.isArray(I.workersDetail??I.workers)?I.workersDetail??I.workers:[];return g({ok:!0,workers:Qe.listWorkers(a.project.id,d?.id).filter((J)=>w(J.resourceId)).map((J)=>{let se=F.find((le)=>le.name===J.name||le.site===J.target.site);return se?{...J,observedState:{...J.observedState,status:se.status??"configured",currentJob:se.currentJob??null,failures:Number(se.failed??se.failures)||0,processed:Number(se.processed)||0}}:J})})}if(v.pathname==="/api/workers/action"&&m.method==="POST"){let F=await D(m),J=Qe.getWorker(String(F.id??""));if(!J||!w(J.resourceId))return g({ok:!1,error:"Worker was not found."},404);let se=String(F.action??"");if(se==="restart"){if(String(F.confirm??"")!==J.name)return g({ok:!1,error:`Type "${J.name}" to restart this worker.`},409);let le=k.find((Ve)=>Ve.id===J.target.operationId);if(!le)return g({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let ve=await ua(o,B,le),Tt=Qe.reconcileWorker(J.id,ve.ok?"in_sync":"unavailable",{...J.observedState,lastRestartAt:new Date().toISOString(),command:ve.command??null,error:ve.error??ve.stderr??null});return Y("worker_restarted",{workerId:J.id,ok:ve.ok},J.resourceId),g({...ve,worker:Tt},ve.ok?200:409)}if(se==="scale")return g({ok:!1,error:J.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 g({ok:!1,error:"Action must be restart or scale."},422)}}if(v.pathname.startsWith("/api/telemetry/")){let d=a.environments.get(B),l=new ma(a.store),h=a.store.listResources(a.project.id,d?.id),S=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(v.pathname)?"runtime:logs":"runtime:read",w=O.role==="admin"||!!d&&Ri(O,d.id,S),A=w?h:h.filter((j)=>Ye(O,j.id,S)),I=(j)=>ly(A,w,j),k=(j)=>{let Y=new Date,F={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},J=String(j.to??Y.toISOString()),se=String(j.from??new Date(new Date(J).getTime()-(F[String(j.range??"1h")]??F["1h"])).toISOString()),le=(Tt)=>{let Ve=(Array.isArray(Tt)?Tt:String(Tt??"").split(",")).map(String).filter(Boolean);return Ve.length?Ve:void 0},ve=le(j.kinds)?.filter((Tt)=>["metric","log","trace","request","event"].includes(Tt));return{projectId:a.project.id,environmentId:d?.id,resourceIds:I(j.resources),kinds:ve,names:le(j.names),sources:le(j.sources),levels:le(j.levels),from:se,to:J,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}},M=Object.fromEntries(v.searchParams.entries()),_=(j=!1)=>Fu({controlPlane:a.store,projectId:a.project.id,environmentId:d?.id,config:o,environment:B,force:j,lightweight:!j}),re=()=>{let j=a.store.getSetting(`telemetry.collection:${a.project.id}:${d?.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??po(a.store,a.project.id)}};if(v.pathname==="/api/telemetry/status"&&m.method==="GET"){_(!1);let j=re(),Y=w?j.statuses:l.status(a.project.id,d?.id,j.policy.rawDays,j.policy.samplingRate,A.map((J)=>J.id)),F=Y.reduce((J,se)=>J+se.estimatedDailyBytes*30,0);return g({ok:!0,generatedAt:j.generatedAt,cached:j.cached,sources:Y,errors:w?j.errors:[],policy:j.policy,retention:{rawDays:j.policy.rawDays,downsampleAfterDays:j.policy.downsampleAfterDays,downsampleBucketMs:j.policy.downsampleBucketMs,maxRecords:j.policy.maxRecords},estimatedMonthlyBytes:F,estimatedMonthlyCostUsd:eb(F,j.policy),costEstimateConfigured:j.policy.estimatedStorageUsdPerGbMonth>0})}if(v.pathname==="/api/telemetry/settings"&&m.method==="GET")return g({ok:!0,policy:po(a.store,a.project.id)});if(v.pathname==="/api/telemetry/settings"&&m.method==="PATCH"){let j=Zy(a.store,a.project.id,await D(m));return Sy(a.project.id),g({ok:!0,policy:j})}if(v.pathname==="/api/telemetry/query"&&m.method==="GET"){_(!1);let j=re();return g({ok:!0,collection:{generatedAt:j.generatedAt,cached:j.cached},...l.query(k(M))})}if(v.pathname==="/api/telemetry/tail"&&m.method==="GET"){_(!1);let j=new TextEncoder,Y=new Date,F=k({...M,kinds:M.kinds||"log,request,event,trace",from:M.from||new Date(Y.getTime()-120000).toISOString(),to:Y.toISOString(),limit:Math.min(1000,Number(M.limit)||200),cursor:void 0}),J=m.headers.get("last-event-id")||String(M.cursor??"")||void 0,se,le=!1,ve=!1,Tt=new ReadableStream({start(Ve){let Fr=()=>{if(le)return;if(le=!0,se)clearInterval(se);m.signal.removeEventListener("abort",Fr);try{Ve.close()}catch{}},dl=async()=>{if(le||ve)return;ve=!0;try{let cn=l.tail({...F,to:new Date(Date.now()+1000).toISOString()},J);for(let ul of cn.records)J=tb(ul)??J,Ve.enqueue(j.encode(`id: ${J??""}
|
|
500
|
-
event: record
|
|
501
|
-
data: ${JSON.stringify(ul)}
|
|
502
|
-
|
|
503
|
-
`));if(cn.cursor)J=cn.cursor}catch(cn){Ve.enqueue(j.encode(`event: error
|
|
504
|
-
data: ${JSON.stringify({message:cn instanceof Error?cn.message:String(cn)})}
|
|
505
|
-
|
|
506
|
-
`))}finally{ve=!1}};dl(),se=setInterval(()=>{if(dl(),!le)Ve.enqueue(j.encode(`event: heartbeat
|
|
507
|
-
data: ${JSON.stringify({cursor:J,at:new Date().toISOString()})}
|
|
508
|
-
|
|
509
|
-
`))},5000),se.unref?.(),m.signal.addEventListener("abort",Fr,{once:!0})},cancel(){if(le=!0,se)clearInterval(se)}});return new Response(Tt,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}if(v.pathname==="/api/telemetry/series"&&m.method==="GET"){_(!1);let j=re(),Y=["sum","avg","min","max","count","p50","p90","p95","p99"].includes(String(M.aggregation))?M.aggregation:"avg",F=k({...M,kinds:"metric",limit:5000}),J=l.series({...F,bucketMs:Number(M.bucketMs)||60000,aggregation:Y,timezone:String(M.timezone??"UTC"),compareFrom:M.compareFrom,compareTo:M.compareTo});return g({ok:!0,collection:{generatedAt:j.generatedAt,cached:j.cached},query:{aggregation:Y,bucketMs:Number(M.bucketMs)||60000,timezone:String(M.timezone??"UTC")},series:J})}if(v.pathname==="/api/telemetry/refresh"&&m.method==="POST")return g({ok:!0,...await _(!0)});if(v.pathname==="/api/telemetry/export"&&m.method==="POST"){let j=await D(m);await _(!1);let Y=l.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),...Y},null,2),{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.json"',"content-type":"application/json; charset=utf-8"}});let J=["timestamp","kind","source","name","level","value","unit","message","traceId","requestId","deploymentId","releaseId","workloadId"],se=[J.join(","),...Y.records.map((le)=>J.map((ve)=>`"${String(le[ve]??"").replaceAll('"','""')}"`).join(","))].join(`
|
|
510
|
-
`);return new Response(se,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(v.pathname==="/api/telemetry/saved-queries"&&m.method==="GET"){let j=Q(O);return g({ok:!0,queries:l.listSavedQueries(a.project.id,j.actor?.id)})}if(v.pathname==="/api/telemetry/saved-queries"&&m.method==="POST"){let j=await D(m),Y=Q(O);return g({ok:!0,query:l.saveQuery(a.project.id,Y.actor?.id,String(j.name??""),k(j.query??j))},201)}if(v.pathname==="/api/telemetry/saved-queries"&&m.method==="DELETE"){let j=await D(m),Y=Q(O),F=l.deleteSavedQuery(a.project.id,Y.actor?.id,String(j.id??""));return g({ok:F},F?200:404)}}if(v.pathname.startsWith("/api/configuration")){let d=a.environments.get(B),l=O.role==="admin"||!!Ot.capabilities?.includes("secrets:read"),h=O.role==="admin"||!!Ot.capabilities?.includes("secrets:write"),S={projectId:a.project.id,environmentId:d?.id},w={"cache-control":"no-store"};if(v.pathname==="/api/configuration"&&m.method==="GET"){let A=Object.fromEntries(v.searchParams),I=A.scopeType||A.scopeId?Ci(A,S):void 0,k=["variable","secret"].includes(String(A.kind))?A.kind:void 0,M=I?.type==="preview"?je.previews.getInstance(I.id):void 0,_=M?je.previews.getDefinition(M.definitionId):void 0,re=I?await wt.resolve({projectId:a.project.id,environmentId:I.environmentId,resourceId:I.resourceId,functionId:I.type==="function"?I.id:void 0,previewId:I.previewId,trustedPreview:!!M&&!M.fork,allowedPreviewSecrets:_?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:l}):void 0,j=a.store.listResources(a.project.id);return g({ok:!0,entries:wt.list({projectId:a.project.id,scope:I,kind:k,search:A.search,canReadSecretMetadata:l}),effectiveEntries:re?Object.values(re.entries).filter((Y)=>!k||Y.kind===k).filter((Y)=>!A.search||Y.key.toLowerCase().includes(String(A.search).toLowerCase())):[],configurationHash:re?.configurationHash,warnings:re?.warnings??[],scopes:{project:a.project,environments:a.store.listEnvironments(a.project.id),resources:j.filter((Y)=>Y.kind!=="function"),functions:j.filter((Y)=>Y.kind==="function"),previews:je.previews.listInstances({projectId:a.project.id}).filter((Y)=>Y.status!=="destroyed").map((Y)=>({id:Y.id,name:Y.name,environmentId:Y.baseEnvironmentId,resourceId:Y.resourceId,fork:Y.fork,status:Y.status}))}},200,w)}if(v.pathname==="/api/configuration/export"&&m.method==="GET"){let A=Ci(Object.fromEntries(v.searchParams),S);return new Response(wt.exportVariables({projectId:a.project.id,scope:A}),{headers:{...w,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(v.pathname==="/api/configuration/plan"&&m.method==="POST"){let A=await D(m),I=Ci(A,S),k=A.values&&typeof A.values==="object"&&!Array.isArray(A.values)?Object.fromEntries(Object.entries(A.values).map(([M,_])=>[M,String(_)])):{};return g({ok:!0,plan:wt.plan({projectId:a.project.id,scope:I,values:k,removeMissing:A.removeMissing===!0})},200,w)}if(v.pathname==="/api/configuration"&&m.method==="POST"){let A=await D(m),I=Ci(A,S),k=A.kind==="secret"?"secret":"variable",M=String(A.key??"");if(k==="secret"&&!h)return g({ok:!1,error:"Secret write permission is required."},403,w);try{let _=await wt.set({organizationId:a.organization.id,projectId:a.project.id,scope:I,key:M,kind:k,value:A.value==null?void 0:String(A.value),reference:A.reference==null?void 0:String(A.reference),backend:A.backend,required:A.required===!0,expectedVersion:A.expectedVersion==null?void 0:Number(A.expectedVersion),confirmed:String(A.confirm??"")===M,idempotencyKey:m.headers.get("idempotency-key")??A.idempotencyKey,actorId:Q(O).actor?.id});return g({ok:!0,entry:wt.list({projectId:a.project.id,scope:I,canReadSecretMetadata:l}).find((re)=>re.id===_.entry.id),mutation:_.mutation,warnings:_.warnings},_.mutation.added.length?201:200,w)}catch(_){return g({ok:!1,error:_ instanceof Error?_.message:String(_)},409,w)}}if(v.pathname==="/api/configuration/import"&&m.method==="POST"){let A=await D(m),I=Ci(A,S),k=Array.isArray(A.secretKeys)?A.secretKeys.map(String):[];if(k.length&&!h)return g({ok:!1,error:"Secret write permission is required."},403,w);try{let M=await wt.importDotenv({organizationId:a.organization.id,projectId:a.project.id,scope:I,source:String(A.source??""),secretKeys:k,backend:A.backend,confirmed:A.confirm==="import",idempotencyKey:m.headers.get("idempotency-key")??A.idempotencyKey,actorId:Q(O).actor?.id});return g({ok:M.document.valid,diagnostics:M.document.diagnostics,mutation:M.mutation,warnings:M.warnings},M.document.valid?200:422,w)}catch(M){return g({ok:!1,error:M instanceof Error?M.message:String(M)},409,w)}}if(v.pathname==="/api/configuration/dependencies"&&m.method==="POST"){let A=await D(m),I=$r.get(String(A.entryId??"")),k=a.store.getResource(String(A.resourceId??""));if(!I||I.projectId!==a.project.id||!k||k.projectId!==a.project.id)return g({ok:!1,error:"Configuration entry or dependent resource was not found."},404,w);return g({ok:!0,dependency:$r.setDependency({entryId:I.id,resourceId:k.id,injectionTarget:["native_reference","file"].includes(String(A.injectionTarget))?A.injectionTarget:"environment",required:A.required!==!1,requiresRedeploy:A.requiresRedeploy!==!1,lastDeployedVersion:A.lastDeployedVersion==null?void 0:Number(A.lastDeployedVersion)})},200,w)}if(v.pathname==="/api/configuration/transfer"&&m.method==="POST"){let A=await D(m),I=$r.get(String(A.id??"")),k=Ci({...A,scopeType:A.targetScopeType,scopeId:A.targetScopeId},S);if(!I||I.projectId!==a.project.id)return g({ok:!1,error:"Configuration entry was not found."},404,w);if(I.kind==="secret"&&!h)return g({ok:!1,error:"Secret write permission is required."},403,w);try{let M=await wt.transfer({entryId:I.id,targetScope:k,mode:A.mode==="move"?"move":"copy",confirmed:A.confirm===I.key,actorId:Q(O).actor?.id,idempotencyKey:m.headers.get("idempotency-key")??A.idempotencyKey});return g({ok:!0,entry:wt.list({projectId:a.project.id,scope:k,canReadSecretMetadata:l}).find((_)=>_.id===M.entry.id),mutation:M.mutation},200,w)}catch(M){return g({ok:!1,error:M instanceof Error?M.message:String(M)},409,w)}}if(v.pathname==="/api/configuration/bulk"&&m.method==="POST"){let A=await D(m),I=Array.isArray(A.ids)?A.ids.map(String).slice(0,500):[],k=I.map((_)=>$r.get(_)).filter((_)=>!!_&&_.projectId===a.project.id);if(k.length!==I.length)return g({ok:!1,error:"One or more configuration entries were not found."},404,w);if(k.some((_)=>_.kind==="secret")&&!h)return g({ok:!1,error:"Secret write permission is required."},403,w);if(A.action!=="delete"||A.confirm!=="bulk")return g({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,w);let M=[];try{for(let _ of k)M.push(await wt.remove({entryId:_.id,expectedVersion:_.version,confirmed:!0,actorId:Q(O).actor?.id}));return g({ok:!0,removed:M.flatMap((_)=>_.removed),affectedResourceIds:[...new Set(M.flatMap((_)=>_.affectedResourceIds))].sort()},200,w)}catch(_){return g({ok:!1,error:_ instanceof Error?_.message:String(_),partial:M.flatMap((re)=>re.removed)},409,w)}}if(v.pathname==="/api/configuration/reveal"&&m.method==="POST"){let A=await D(m),I=Oe.resolveSession(m);try{return g({ok:!0,value:await wt.reveal({entryId:String(A.id??""),canRevealSecrets:l,recentlyAuthenticated:!H||!!I&&U.isRecentlyAuthenticated(I),actorId:Q(O).actor?.id})},200,w)}catch(k){return g({ok:!1,error:k instanceof Error?k.message:String(k)},403,w)}}if(v.pathname==="/api/configuration"&&m.method==="DELETE"){let A=await D(m),I=$r.get(String(A.id??""));if(I?.kind==="secret"&&!h)return g({ok:!1,error:"Secret write permission is required."},403,w);if(!I||I.projectId!==a.project.id)return g({ok:!1,error:"Configuration entry was not found."},404,w);try{return g({ok:!0,mutation:await wt.remove({entryId:I.id,expectedVersion:Number(A.expectedVersion),confirmed:String(A.confirm??"")===I.key,actorId:Q(O).actor?.id})},200,w)}catch(k){return g({ok:!1,error:k instanceof Error?k.message:String(k)},409,w)}}}if(v.pathname.startsWith("/api/fleet")){let d=Q(O).actor?.id,l=(h,S=409)=>g({ok:!1,error:h instanceof Error?h.message:String(h)},S,{"cache-control":"no-store"});if(v.pathname==="/api/fleet"&&m.method==="GET")return g({ok:!0,servers:ki.list(a.project.id),resources:a.store.listResources(a.project.id),operations:Ee.list({projectId:a.project.id,limit:200}).filter((h)=>h.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(v.pathname==="/api/fleet"&&m.method==="POST"){let h=await D(m);try{return g({ok:!0,server:rr.enroll({organizationId:a.organization.id,projectId:a.project.id,name:String(h.name??""),provider:["aws","hetzner"].includes(String(h.provider))?h.provider:"ssh",providerId:h.providerId?String(h.providerId):void 0,region:h.region?String(h.region):void 0,zone:h.zone?String(h.zone):void 0,endpoint:String(h.endpoint??""),sshUser:String(h.sshUser??"deploy"),sshPort:h.sshPort?Number(h.sshPort):22,credentialRef:String(h.credentialRef??""),roles:Array.isArray(h.roles)?h.roles:[],labels:h.labels&&typeof h.labels==="object"?h.labels:{}})},201)}catch(S){return l(S,422)}}if(v.pathname==="/api/fleet/action"&&m.method==="POST"){let h=await D(m),S=String(h.id??""),w=String(h.action??"");try{if(w==="test")return g({ok:!0,server:await rr.test(S)});if(w==="validate")return g({ok:!0,server:await rr.validate(S)});if(w==="review_host_key")return g({ok:!0,server:rr.reviewHostKey(S,String(h.fingerprint??""))});if(w==="bootstrap")return g({ok:!0,...rr.bootstrap(S,h.confirmed===!0)},h.confirmed===!0?202:200);if(w==="heartbeat")return g({ok:!0,server:rr.heartbeat(S,{usage:h.usage&&typeof h.usage==="object"?h.usage:{}})});if(w==="drain")return g({ok:!0,server:rr.drain(S,h.completed===!0)});if(w==="uncordon")return g({ok:!0,server:rr.uncordon(S)});if(w==="archive")return g({ok:!0,server:rr.archive(S,String(h.confirmation??""))});return l("Unsupported fleet action.",422)}catch(A){return l(A)}}}if(v.pathname.startsWith("/api/capacity")){let d=(l,h=409)=>g({ok:!1,error:l instanceof Error?l.message:String(l)},h,{"cache-control":"no-store"});if(v.pathname==="/api/capacity"&&m.method==="GET")return g({ok:!0,pools:Lr.listPools(a.project.id),placements:Lr.listPlacements(a.project.id),servers:ki.list(a.project.id)},200,{"cache-control":"no-store"});if(v.pathname==="/api/capacity"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,pool:Lr.createPool({organizationId:a.organization.id,projectId:a.project.id,name:String(l.name??""),purpose:String(l.purpose??"application"),backend:String(l.backend??"server"),region:l.region?String(l.region):void 0,architecture:l.architecture?String(l.architecture):void 0,labels:l.labels&&typeof l.labels==="object"?l.labels:{},requiredServerLabels:l.requiredServerLabels&&typeof l.requiredServerLabels==="object"?l.requiredServerLabels:{},toleratedTaints:Array.isArray(l.toleratedTaints)?l.toleratedTaints.map(String):[],capacity:l.capacity&&typeof l.capacity==="object"?l.capacity:{},maxWorkloads:Number(l.maxWorkloads??10),costWeight:Number(l.costWeight??1),spreadKey:l.spreadKey?String(l.spreadKey):void 0,concurrency:Number(l.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(h){return d(h,422)}}if(v.pathname==="/api/capacity/member"&&m.method==="POST"){let l=await D(m);try{return Lr.addMember(String(l.poolId??""),String(l.serverId??"")),g({ok:!0,pool:Lr.getPool(String(l.poolId??""))})}catch(h){return d(h,422)}}if(v.pathname==="/api/capacity/explain"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,decisions:Hu.explain(a.project.id,{purpose:String(l.purpose??"application"),resources:l.resources&&typeof l.resources==="object"?l.resources:{},region:l.region?String(l.region):void 0,architecture:l.architecture?String(l.architecture):void 0,labels:l.labels&&typeof l.labels==="object"?l.labels:{}})})}catch(h){return d(h,422)}}if(v.pathname==="/api/capacity/action"&&m.method==="POST"){let l=await D(m);try{if(l.action==="drain")return g({ok:!0,...Hu.drainPool(String(l.poolId??""))});if(l.action==="enable")return g({ok:!0,pool:Lr.updatePool(String(l.poolId??""),{status:"active"})});if(l.action==="disable")return g({ok:!0,pool:Lr.updatePool(String(l.poolId??""),{status:"disabled"})});return d("Unsupported capacity action.",422)}catch(h){return d(h,422)}}}if(v.pathname.startsWith("/api/regions")){let d=(l,h=409)=>g({ok:!1,error:l instanceof Error?l.message:String(l)},h,{"cache-control":"no-store"});if(v.pathname==="/api/regions"&&m.method==="GET")return g({ok:!0,topologies:sn.list(a.project.id).map((l)=>({topology:l,targets:sn.targets(l.id),channels:sn.channels(l.id),route:sn.route(l.id),executions:sn.executions(l.id)}))},200,{"cache-control":"no-store"});if(v.pathname==="/api/regions"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,topology:Gu.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:a.environments.get(B)?.id,name:String(l.name??""),hostname:String(l.hostname??""),regions:Array.isArray(l.regions)?l.regions:[],trafficPolicy:l.trafficPolicy==="weighted"||l.trafficPolicy==="latency"?l.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(l.replicate)?l.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(l.maxLagSeconds??30),retainOnDestroy:l.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:l.cdnEnabled===!0,wafEnabled:l.wafEnabled===!0})},201)}catch(h){return d(h,422)}}if(v.pathname==="/api/regions/action"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,...Gu.enqueue({topologyId:String(l.topologyId??""),kind:String(l.action??""),targetRegion:l.targetRegion?String(l.targetRegion):void 0,revision:l.revision?String(l.revision):void 0,manifest:l.manifest&&typeof l.manifest==="object"?l.manifest:{},confirmation:l.confirmation?String(l.confirmation):void 0,deleteData:l.deleteData===!0})},202)}catch(h){return d(h,422)}}}if(v.pathname.startsWith("/api/maintenance")){let d=(l,h=409)=>g({ok:!1,error:l instanceof Error?l.message:String(l)},h,{"cache-control":"no-store"});if(v.pathname==="/api/maintenance"&&m.method==="GET")return g({ok:!0,manifests:gr.manifests(a.organization.id),windows:gr.windows(a.project.id),campaigns:gr.campaigns(a.project.id).map((l)=>({campaign:l,targets:gr.targets(l.id)})),cleanups:gr.cleanups(a.project.id),drills:gr.drills(a.project.id)},200,{"cache-control":"no-store"});if(v.pathname==="/api/maintenance/cleanup-preview"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,plan:await Ea.previewCleanup({projectId:a.project.id,kind:String(l.kind??"operations"),criteria:{olderThanDays:Number(l.olderThanDays??30)}},Ku)},201)}catch(h){return d(h,422)}}if(v.pathname==="/api/maintenance/cleanup-apply"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,...Ea.enqueueCleanup(String(l.planId??""),String(l.confirmation??""))},202)}catch(h){return d(h,422)}}if(v.pathname==="/api/maintenance/drill"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,drill:gr.createDrill({projectId:a.project.id,scenario:String(l.scenario??"control_plane"),isolatedTarget:String(l.isolatedTarget??""),expectedRpoMinutes:Number(l.expectedRpoMinutes??60),expectedRtoMinutes:Number(l.expectedRtoMinutes??30),recoveryPointId:l.recoveryPointId?String(l.recoveryPointId):void 0,topologyId:l.topologyId?String(l.topologyId):void 0})},201)}catch(h){return d(h,422)}}if(v.pathname==="/api/maintenance/drill-run"&&m.method==="POST"){let l=await D(m);try{return g({ok:!0,...Ea.enqueueDrill(String(l.drillId??""))},202)}catch(h){return d(h,422)}}}if(v.pathname.startsWith("/api/volumes")){let d=a.environments.get(B),l=Q(O).actor?.id,h=(S,w=409)=>g({ok:!1,error:S instanceof Error?S.message:String(S)},w,{"cache-control":"no-store"});if(v.pathname==="/api/volumes"&&m.method==="GET"){let S=Ia.inventory(a.project.id,d?.id),w=a.store.listResources(a.project.id,d?.id).map((A)=>({id:A.id,name:A.name,slug:A.slug,kind:A.kind,provider:A.provider,providerId:A.providerId}));return g({ok:!0,volumes:S,resources:w,operations:Ee.list({projectId:a.project.id,limit:100}).filter((A)=>A.operation.kind.startsWith("volume.")),recoveryPoints:Ue.listRecoveryPoints(a.project.id).filter((A)=>A.kind==="volume"),providers:Ca.map((A)=>({provider:A.provider,type:A.type,capabilities:A.capabilities()}))},200,{"cache-control":"no-store"})}if(v.pathname==="/api/volumes"&&m.method==="POST"){let S=await D(m);try{return g({ok:!0,...pr.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,resourceId:S.resourceId?String(S.resourceId):void 0,name:String(S.name??""),provider:String(S.provider??"docker"),type:S.type==="docker"?"docker":S.type,capacityBytes:S.capacityBytes==null?void 0:Number(S.capacityBytes),filesystem:S.filesystem?String(S.filesystem):void 0,encrypted:S.encrypted===!0,desiredState:S.desiredState&&typeof S.desiredState==="object"?S.desiredState:{},actorId:l})},202,{"cache-control":"no-store"})}catch(w){return h(w,422)}}if(v.pathname==="/api/volumes/attach"&&m.method==="POST"){let S=await D(m);try{return g({ok:!0,...pr.attach(String(S.volumeId??""),{resourceId:String(S.resourceId??""),targetPath:String(S.targetPath??""),readOnly:S.readOnly===!0,uid:S.uid==null?void 0:Number(S.uid),gid:S.gid==null?void 0:Number(S.gid),mode:S.mode?String(S.mode):void 0,propagation:S.propagation,driverOptions:S.driverOptions&&typeof S.driverOptions==="object"?S.driverOptions:{},actorId:l})},202)}catch(w){return h(w,422)}}if(v.pathname==="/api/volumes/detach"&&m.method==="POST"){let S=await D(m);try{return g({ok:!0,...pr.detach(String(S.volumeId??""),String(S.attachmentId??""),{force:S.force===!0,drained:S.drained===!0,unmounted:S.unmounted===!0,confirmation:S.confirmation?String(S.confirmation):void 0,actorId:l})},202)}catch(w){return h(w)}}if(v.pathname==="/api/volumes/resize"&&m.method==="POST"){let S=await D(m);try{return g({ok:!0,...pr.resize(String(S.volumeId??""),Number(S.capacityBytes),{drained:S.drained===!0,actorId:l})},202)}catch(w){return h(w,422)}}if(v.pathname==="/api/volumes/snapshot"&&m.method==="POST"){let S=await D(m);try{return g({ok:!0,...pr.snapshot(String(S.volumeId??""),{name:S.name?String(S.name):void 0,actorId:l})},202)}catch(w){return h(w,422)}}if(v.pathname==="/api/volumes/restore"&&m.method==="POST"){let S=await D(m);try{return g({ok:!0,...pr.restore(String(S.snapshotId??""),{name:String(S.name??""),actorId:l})},202)}catch(w){return h(w,422)}}if(v.pathname==="/api/volumes/discover"&&m.method==="POST")try{return g({ok:!0,volumes:await pr.discover({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,actorId:l})})}catch(S){return h(S,502)}if(v.pathname==="/api/volumes/adopt"&&m.method==="POST"){let S=await D(m);try{return g({ok:!0,volume:pr.adopt(String(S.volumeId??""),{name:String(S.name??""),actorId:l})})}catch(w){return h(w,422)}}if(v.pathname==="/api/volumes"&&m.method==="DELETE"){let S=await D(m),w=Oe.resolveSession(m);try{return g({ok:!0,...pr.delete(String(S.volumeId??""),{recentAuthAt:!H||w&&U.isRecentlyAuthenticated(w)?new Date().toISOString():void 0,confirmation:S.confirmation?String(S.confirmation):void 0,backupOverride:S.backupOverride===!0,backupOverrideConfirmation:S.backupOverrideConfirmation?String(S.backupOverrideConfirmation):void 0,actorId:l})},202)}catch(A){return h(A)}}}if(v.pathname==="/api/backups"&&m.method==="GET"){let d=a.environments.get(B),l=Ue.listPolicies(a.project.id,d?.id),h=new Set(l.map((k)=>k.id)),S=Ue.listRecoveryPoints(a.project.id).filter((k)=>!k.policyId||h.has(k.policyId)),w=Ue.listJobs(a.project.id).filter((k)=>!k.policyId||h.has(k.policyId)),A=(k)=>({...k,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!k.credentialRef,clientEncryptionConfigured:!!k.encryptionKeyRef}),I=await Promise.all(Ue.listDestinations(a.project.id).map(async(k)=>({...A(k),credentialStatus:await Mp(k,lr)})));return g({ok:!0,destinations:I,policies:l,recoveryPoints:S,jobs:w,coverage:Ue.coverage(a.project.id).filter((k)=>h.has(k.policy.id)),resources:d?a.store.listResources(a.project.id,d.id).map((k)=>({id:k.id,name:k.name,slug:k.slug,kind:k.kind})):[]})}if(v.pathname==="/api/backups/destinations"&&m.method==="POST"){let d=await D(m),l=String(d.name??"").trim(),h=String(d.provider??""),S=String(d.encryption??"provider"),w=`secret://data-services/backups/${a.project.id}/${l}`,A=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(h))return g({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(S))return g({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let I,k;if(d.credentials&&typeof d.credentials==="object"&&!Array.isArray(d.credentials))I=`${w}/credentials`,await lr.put(I,JSON.stringify(d.credentials)),A.push(I);if(S!=="provider"){let _=String(d.encryptionKey??"");if(_.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");k=`${w}/encryption-key`,await lr.put(k,_),A.push(k)}let M=Ue.createDestination({organizationId:a.organization.id,projectId:a.project.id,name:l,provider:h,endpoint:d.endpoint?String(d.endpoint):void 0,endpointPolicy:d.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:d.bucket?String(d.bucket):void 0,prefix:String(d.prefix??""),region:d.region?String(d.region):Mr,forcePathStyle:d.forcePathStyle===!0,credentialRef:I,encryption:S,encryptionKeyRef:k,immutability:d.immutability&&typeof d.immutability==="object"&&!Array.isArray(d.immutability)?d.immutability:{},status:"untested"});return g({ok:!0,destination:{...M,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!I,clientEncryptionConfigured:!!k}},201)}catch(I){for(let k of A)await lr.remove(k).catch(()=>{});return g({ok:!1,error:I instanceof Error?I.message:String(I)},422)}}if(v.pathname==="/api/backups/destinations/test"&&m.method==="POST"){let d=await D(m),l=Ue.getDestination(String(d.id??""));if(!l||l.projectId!==a.project.id)return g({ok:!1,error:"Backup destination was not found."},404);if(l.provider==="aws_backup")return g({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await Wu.test(l),g({ok:!0,destination:Ue.recordDestinationTest(l.id,{ok:!0})})}catch(h){let S=h instanceof Error?h.message:String(h);return Ue.recordDestinationTest(l.id,{ok:!1,error:S}),g({ok:!1,error:S},502)}}if(v.pathname==="/api/backups/policies"&&m.method==="POST"){let d=await D(m),l=a.environments.get(B),h=Ue.getDestination(String(d.destinationId??"")),S=String(d.resourceKind??""),w=d.dataServiceId?String(d.dataServiceId):void 0,A=w?Re.get(w):void 0,I=d.resourceId?String(d.resourceId):void 0,k=I?a.store.getResource(I):void 0;if(!l)return g({ok:!1,error:"Environment was not found."},404);if(!h||h.projectId!==a.project.id)return g({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(S))return g({ok:!1,error:"A supported backup resource kind is required."},422);if(w&&(!A||A.projectId!==a.project.id||A.environmentId!==l.id))return g({ok:!1,error:"Data service was not found in this environment."},404);if(I&&(!k||k.projectId!==a.project.id||k.environmentId!==l.id))return g({ok:!1,error:"Resource was not found in this environment."},404);if(S==="managed_database"&&!A)return g({ok:!1,error:"Managed database policies require a data service."},422);if(S==="logical_database"&&(!A||!["container","server"].includes(A.provider)))return g({ok:!1,error:"Logical database policies require an on-box data service."},422);if(S==="volume"&&(!k||!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(String(d.volumeName??""))))return g({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let M=Array.isArray(d.includePatterns)?d.includePatterns.map(String).filter(Boolean):[];if(S==="files"&&(!k||!M.length))return g({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(S==="control_plane"&&h.encryption==="provider")return g({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(S==="infrastructure"&&(h.provider!=="aws_backup"||!M.some((_)=>_.startsWith("resource:arn:"))||!M.some((_)=>_.startsWith("role:arn:"))))return g({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let _=Ue.createPolicy({organizationId:a.organization.id,projectId:a.project.id,environmentId:l.id,resourceId:I,dataServiceId:w,destinationId:h.id,name:String(d.name??"").trim(),resourceKind:S,schedule:String(d.schedule??"daily"),timezone:String(d.timezone??"UTC"),retention:d.retention&&typeof d.retention==="object"&&!Array.isArray(d.retention)?d.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(d.compression))?d.compression:"gzip",encryption:["destination","client_side","both"].includes(String(d.encryption))?d.encryption:"destination",includePatterns:S==="volume"?[String(d.volumeName),...M]:M,excludePatterns:Array.isArray(d.excludePatterns)?d.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(d.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(d.expectedRtoMinutes)||120),healthCheckId:d.healthCheckId?String(d.healthCheckId):void 0,enabled:d.enabled!==!1});return g({ok:!0,policy:_},201)}catch(_){return g({ok:!1,error:_ instanceof Error?_.message:String(_)},422)}}if(v.pathname==="/api/backups/run"&&m.method==="POST"){let d=await D(m),l=Ue.getPolicy(String(d.policyId??"")),h=a.environments.get(B);if(!l||l.projectId!==a.project.id||l.environmentId!==h?.id)return g({ok:!1,error:"Backup policy was not found in this environment."},404);try{let S=on.enqueueBackup(l,new Date().toISOString(),Q(O).actor?.id);return g({ok:!0,job:S},202)}catch(S){return g({ok:!1,error:S instanceof Error?S.message:String(S)},409)}}if(v.pathname==="/api/backups/verify"&&m.method==="POST"){let d=await D(m),l=Ue.getRecoveryPoint(String(d.recoveryPointId??""));if(!l||l.projectId!==a.project.id)return g({ok:!1,error:"Recovery point was not found."},404);return g({ok:!0,job:on.enqueueVerification(l)},202)}if(v.pathname==="/api/backups/restore"&&m.method==="POST"){let d=await D(m),l=Ue.getRecoveryPoint(String(d.recoveryPointId??"")),h=d.mode==="in_place"?"in_place":"isolated",S=d.target&&typeof d.target==="object"&&!Array.isArray(d.target)?{...d.target,inPlace:h==="in_place"}:{inPlace:h==="in_place"},w=Oe.resolveSession(m),A={mode:h,target:S,targetName:String(d.targetName??""),confirm:d.confirm?String(d.confirm):void 0,recentAuth:!H||!!w&&U.isRecentlyAuthenticated(w),downtimeAcknowledged:d.downtimeAcknowledged===!0,safetyBackupId:d.safetyBackupId?String(d.safetyBackupId):void 0};if(!l||l.projectId!==a.project.id)return g({ok:!1,error:"Recovery point was not found."},404);if(d.drill===!0&&h!=="isolated")return g({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let I=on.planRestore(l,A);if(d.execute!==!0)return g({ok:!0,plan:I,executionCreated:!1});let k=on.enqueueRestore(l,{...A,drill:d.drill===!0,actorId:Q(O).actor?.id});return g({ok:!0,plan:I,job:k},202)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:String(I)},409)}}if(v.pathname==="/api/backups/recovery-points"&&m.method==="POST"){let d=await D(m),l=Ue.getRecoveryPoint(String(d.id??""));if(!l||l.projectId!==a.project.id)return g({ok:!1,error:"Recovery point was not found."},404);if(d.held==null&&d.pinned==null)return g({ok:!1,error:"held or pinned must be provided."},422);return g({ok:!0,recoveryPoint:Ue.updateRecoveryPoint(l.id,{held:d.held==null?l.held:d.held===!0,pinned:d.pinned==null?l.pinned:d.pinned===!0})})}if(v.pathname==="/api/backups/retention"&&m.method==="POST")return g({ok:!0,jobs:on.enqueueRetention()},202);if(v.pathname==="/api/data-services/capabilities"&&m.method==="GET"){let d=String(v.searchParams.get("engine")??""),l=String(v.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(d)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(l))return g({ok:!1,error:"A supported engine and provider are required."},422);return g({ok:!0,engine:d,provider:l,capabilities:Fi(d,l)})}if(v.pathname==="/api/data-services"&&m.method==="GET"){let d=a.environments.get(B),l=Re.list(a.project.id,d?.id).map((h)=>{let S=Re.credential(h.id);return{...h,credentialRef:void 0,credential:S?{configured:!0,username:S.username,version:S.version,rotatedAt:S.rotatedAt}:void 0,dependencies:Re.dependencies(h.id).map((w)=>({resourceId:w.resourceId,requiresRedeploy:w.requiresRedeploy}))}});return g({ok:!0,services:l})}if(v.pathname==="/api/data-services/preview"&&m.method==="POST"){let d=await D(m);if(d.id){let S=Re.get(String(d.id)),w=a.environments.get(B),A=String(d.action??"");if(!S||S.projectId!==a.project.id||S.environmentId!==w?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!ba.includes(A))return g({ok:!1,error:`Action must be one of: ${ba.join(", ")}.`},422);try{return g({ok:!0,plan:yo.plan(S,A,d.changes??{})})}catch(I){return g({ok:!1,error:I instanceof Error?I.message:String(I)},422)}}let l=String(d.engine??""),h=String(d.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(h))return g({ok:!1,error:"A supported engine and provider are required."},422);return g({ok:!0,capabilities:Fi(l,h),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(v.pathname==="/api/data-services"&&m.method==="POST"){let d=await D(m),l=String(d.engine??""),h=String(d.provider??""),S=a.environments.get(B),w=Q(O);if(!S)return g({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(h))return g({ok:!1,error:"A supported engine and provider are required."},422);let A={organizationId:a.organization.id,projectId:a.project.id,environmentId:S.id,resourceId:d.resourceId?String(d.resourceId):void 0,name:String(d.name??"").trim(),engine:l,provider:h,placement:String(d.placement??d.name??"").trim(),engineVersion:d.engineVersion?String(d.engineVersion):void 0,plan:String(d.plan??(h==="aws_elasticache"?"cache.t4g.micro":h==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:d.storageGb==null?void 0:Number(d.storageGb),highAvailability:d.highAvailability===!0,publicExposure:d.publicExposure===!0,allowedCidrs:Array.isArray(d.allowedCidrs)?d.allowedCidrs.map(String):[],desiredState:d.desiredState&&typeof d.desiredState==="object"&&!Array.isArray(d.desiredState)?d.desiredState:{},observedState:{},origin:d.adopt===!0?"adopted":"managed",managementEnabled:d.adopt!==!0,ownerActorId:w.actor?.id,username:d.username?String(d.username):void 0};try{if(d.adopt===!0){let k=Re.create({...A,status:"adopted",credentialRef:void 0});return g({ok:!0,service:k,readOnly:!0},201)}if(!Ju({provider:h,engine:l}))return g({ok:!1,error:`No ${h}/${l} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let I=await yo.create(A);return g({ok:!0,service:I.service,operationId:I.operationId,oneTimeCredential:I.credential},201)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:String(I)},422)}}if(v.pathname==="/api/data-services/connections"&&m.method==="GET"){let d=Re.get(String(v.searchParams.get("id")??"")),l=a.environments.get(B);if(!d||d.projectId!==a.project.id||d.environmentId!==l?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);let h=typeof d.observedState.endpoint==="string"?d.observedState.endpoint:void 0,S=typeof d.observedState.readerEndpoint==="string"?d.observedState.readerEndpoint:void 0,w=Number(d.observedState.port)||(d.engine==="postgres"?5432:d.engine==="redis"?6379:d.engine==="mongodb"?27017:d.engine==="libsql"?8080:3306),A=typeof d.observedState.database==="string"?d.observedState.database:void 0,I=typeof d.observedState.tls==="boolean"?d.observedState.tls:d.provider.startsWith("aws_"),k=[...h?[{type:d.publicExposure?"external":"internal",host:h,port:w,database:A,tls:I}]:[],...S?[{type:"internal",host:S,port:w,database:A,tls:I}]:[],{type:"tunnel",host:h??d.placement,port:w,database:A,tls:I}];return g({ok:!0,serviceId:d.id,guidance:Fp(d,k)})}if(v.pathname==="/api/data-services/action"&&m.method==="POST"){let d=await D(m),l=Re.get(String(d.id??"")),h=a.environments.get(B),S=String(d.action??"");if(!l||l.projectId!==a.project.id||l.environmentId!==h?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!ba.includes(S))return g({ok:!1,error:`Action must be one of: ${ba.join(", ")}.`},422);let w=d.changes&&typeof d.changes==="object"&&!Array.isArray(d.changes)?d.changes:{};try{let A=yo.plan(l,S,w);if(d.execute!==!0)return g({ok:!0,plan:A,productionExecutionCreated:!1});let I=yo.enqueue(l,S,w,Q(O).actor?.id);return g({ok:!0,plan:A,operationId:I},202)}catch(A){return g({ok:!1,error:A instanceof Error?A.message:String(A)},409)}}if(v.pathname==="/api/data-services/dependencies"&&m.method==="POST"){let d=await D(m),l=Re.get(String(d.id??"")),h=a.environments.get(B),S=a.store.getResource(String(d.resourceId??""));if(!l||l.projectId!==a.project.id||l.environmentId!==h?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!S||S.projectId!==a.project.id||S.environmentId!==h?.id)return g({ok:!1,error:"Dependent resource was not found in this environment."},404);if(d.remove===!0)return g({ok:Re.removeDependency(l.id,S.id)});return Re.addDependency({serviceId:l.id,resourceId:S.id,secretRef:l.credentialRef??`secret://data-services/${l.projectId}/${l.name}`,requiresRedeploy:d.requiresRedeploy!==!1}),g({ok:!0,dependencies:Re.dependencies(l.id).map((w)=>({resourceId:w.resourceId,requiresRedeploy:w.requiresRedeploy}))})}if(v.pathname==="/api/data-services/management"&&m.method==="POST"){let d=await D(m),l=Re.get(String(d.id??"")),h=a.environments.get(B);if(!l||l.projectId!==a.project.id||l.environmentId!==h?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(l.origin!=="adopted"||d.reviewed!==!0||d.confirm!==l.name)return g({ok:!1,error:`Enabling management requires reviewed=true and typing ${l.name}.`},409);return g({ok:!0,service:Re.update(l.id,l.version,{managementEnabled:!0})})}if(v.pathname==="/api/data-services/reveal"&&m.method==="POST"){let d=await D(m),l=Re.get(String(d.id??"")),h=a.environments.get(B),S=l?Re.credential(l.id):void 0;if(!l||l.projectId!==a.project.id||l.environmentId!==h?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!S)return g({ok:!1,error:"No managed credential is configured."},404);return g({ok:!0,credential:{username:S.username,password:await lr.resolve(S.secretRef),version:S.version}},200,{"cache-control":"no-store"})}if(v.pathname==="/api/databases"&&m.method==="GET")return g(await Bf(o,B));if(v.pathname==="/api/databases"&&m.method==="POST"){let d=await D(m),l=String(d.name??"").trim();if(!Or(l))return g({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return g({...await jf(o,B,l),name:l})}if(v.pathname==="/api/databases/vitess"&&m.method==="GET"){let d=await Vf(o,B);return g({...d,unhealthy:qf(d.tablets),missingPrimary:Jf(d)})}if(v.pathname==="/api/databases/vitess/provision"&&m.method==="POST"){let d=await D(m);try{return g(await rh(o,B,{keyspace:String(d.keyspace??""),username:String(d.username??""),password:String(d.password??""),sharded:d.sharded===!0,confirm:String(d.confirm??"")}))}catch(l){return g({ok:!1,error:l instanceof Error?l.message:String(l)},422)}}if(v.pathname==="/api/databases/vitess/migrations"&&m.method==="GET"){let d=v.searchParams.get("keyspace")??void 0;return g(await Xf(o,B,d))}if(v.pathname==="/api/databases/vitess/migrations/action"&&m.method==="POST"){let d=await D(m),l=String(d.uuid??"").trim(),h=String(d.action??"");if(!["retry","cancel","cleanup","complete"].includes(h))return g({ok:!1,error:"Unknown migration action."},422);return g(await Zf(o,B,l,h))}if(v.pathname==="/api/databases/vitess/keyspaces"&&m.method==="POST"){let d=await D(m),l=String(d.name??"").trim(),h=d.sharded===!0;return g(await Kf(o,B,l,{sharded:h}))}if(v.pathname==="/api/databases/vitess/vschema"&&m.method==="POST"){let d=await D(m),l=String(d.keyspace??"").trim(),h=typeof d.vschema==="string"?d.vschema:JSON.stringify(d.vschema??null);return g(await Qf(o,B,l,h))}if(v.pathname==="/api/databases/vitess/schema"&&m.method==="POST"){let d=await D(m),l=String(d.sql??"");return g(await Yf(o,B,l))}if(v.pathname==="/api/databases/vitess/install-client"&&m.method==="POST")return g(await Gf(o,B));if(v.pathname==="/api/databases/backups"&&m.method==="GET")return g(await zf(o,B));if(v.pathname==="/api/databases/backup"&&m.method==="POST"){let d=await D(m),l=String(d.database??"").trim();if(!Or(l))return g({ok:!1,error:"Database name must be a valid identifier."},422);if(d.confirm!==l)return g({ok:!1,error:`Type "${l}" to back up this database.`},409);return g(await Uf(o,B,l))}if(v.pathname==="/api/databases/users"&&m.method==="POST"){let d=await D(m),l=String(d.username??"").trim(),h=String(d.password??""),S=String(d.database??"").trim()||void 0,w=d.access==="readonly"?"readonly":"all";if(!Or(l))return g({ok:!1,error:"Username must be a valid identifier."},422);if(!h)return g({ok:!1,error:"Password is required."},422);if(S&&!Or(S))return g({ok:!1,error:"Database must be a valid identifier."},422);return g({...await Ff(o,B,{username:l,password:h,database:S,access:w}),username:l})}if(v.pathname==="/api/dashboard-data")return Pe=C.get(B)??await ae(B),ae(B),g(Eu(Pe,{user:Ot,slug:o.project.slug}));if(v.pathname==="/api/users"&&m.method==="GET")return g({ok:!0,users:vt(t).map(vi)});if(v.pathname==="/api/users"&&m.method==="POST"){let d=await D(m),l=String(d.username??"").trim();if(!oa(l))return g({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let h=d.sites&&typeof d.sites==="object"?d.sites:{},S=new Set(Object.keys(o.sites??{})),w={};for(let[k,M]of Object.entries(h)){if(!S.has(k))return g({ok:!1,error:`Site '${k}' was not found.`},404);if(M!=="owner"&&M!=="collaborator")return g({ok:!1,error:`Unknown site role '${M}'. Use 'owner' or 'collaborator'.`},422);w[k]=M}let A=typeof d.password==="string"&&d.password.trim()?d.password.trim():void 0;if(A&&A.length<12)return g({ok:!1,error:"Password must be at least 12 characters."},422);let I=io(t,{username:l,password:A,name:typeof d.name==="string"?d.name:void 0,sites:w});return Qs(a,vt(t)),jt(),g({ok:!0,user:vi(I.user),password:I.password})}if(v.pathname==="/api/users"&&m.method==="DELETE"){let d=await D(m),l=String(d.username??"").trim();if(l.toLowerCase()===O.username.toLowerCase())return g({ok:!1,error:"You cannot remove your own account."},409);let h=Bt(vt(t),l),S=h?a.store.getActorByExternalId("user",`dashboard:${h.username.toLowerCase()}`):void 0,w=S?a.store.getMembershipForActor(a.organization.id,S.id):void 0;if(w&&w.source!=="legacy")return g({ok:!1,error:"Organization members must be removed from Organization access."},409);let A=vu(t,l);if(!A.ok)return g(A,409);return Qs(a,vt(t)),W.clear(),g({ok:!0,username:l})}if(v.pathname==="/api/actions/run"&&m.method==="POST"){let d=await m.json().catch(()=>({})),l=d.action?rA(d.action,B):void 0;if(!l)return g({ok:!1,error:"Unknown dashboard action."},404);if(l.mutates&&d.confirm!==l.confirm)return g({ok:!1,error:`Type "${l.confirm}" to run this action.`},409);let h=await Dr({controlPlane:a,environment:B,actor:O,kind:`dashboard.action.${l.id}`,input:{action:l.id},execute:()=>zu(l,{cwd:t,cliEntry:i})});return g({...h.result,controlPlaneOperation:h.operation})}if(v.pathname==="/api/server/operations/run"&&m.method==="POST"){let d=await m.json().catch(()=>({})),l=d.operation?Cu(d.operation,o,Pe):void 0;if(!l)return g({ok:!1,error:"Unknown or unavailable server operation."},404);if(l.mutates&&d.confirm!==l.confirm)return g({ok:!1,error:`Type "${l.confirm}" to run this operation.`},409);let h=Kt(a,String(B));await new xn(ce).run(new to,{...h,artifactRoot:t});let S=Ks(ce,{scope:h,desiredConfigHash:a.project.desiredConfigHash});if(S.decision.outcome==="block")return g({ok:!1,error:`Operation blocked by security policy: ${S.decision.explanation}`,securityReview:S},409);let w=await Dr({controlPlane:a,environment:B,actor:O,kind:`dashboard.server.${l.id}`,resourceSlug:l.target,input:{operation:l.id,target:l.target,to:d.to??null},execute:()=>ua(o,B,l,{to:d.to})});return g({...w.result,controlPlaneOperation:w.operation,securityReview:S})}if(v.pathname==="/api/server/command"&&m.method==="POST"){let d=await m.json().catch(()=>({}));if(d.confirm!=="run")return g({ok:!1,error:'Type "run" to execute this command on the server.'},409);let l=await Dr({controlPlane:a,environment:B,actor:O,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>oo(o,B,String(d.command??""))});return g({...l.result,controlPlaneOperation:l.operation})}if(v.pathname==="/api/serverless/operations")return g(_u(o,B,Pe));if(v.pathname==="/api/serverless/operations/run"&&m.method==="POST"){let d=await m.json().catch(()=>({})),l=d.operation?zh(d.operation,o,B,Pe):void 0;if(!l)return g({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(l.mutates&&d.confirm!==l.confirm)return g({ok:!1,error:`Type "${l.confirm}" to run this operation.`},409);let h=await Dr({controlPlane:a,environment:B,actor:O,kind:`dashboard.serverless.${l.id}`,input:{operation:l.id,min:d.min??null,max:d.max??null},execute:()=>Vh(o,B,l,{min:d.min,max:d.max})});return Pe=await Mn(o,B),C.set(B,Pe),g({...h.result,controlPlaneOperation:h.operation})}if(v.pathname==="/api/serverless/command"&&m.method==="POST"){let d=await m.json().catch(()=>({}));if(d.confirm!=="run")return g({ok:!1,error:'Type "run" to execute this command.'},409);return g(await qh(o,B,String(d.command??"")))}if(v.pathname==="/api/serverless/dlq"&&m.method==="GET"){let d=Number(v.searchParams.get("max"))||10;return g(await Jh(o,B,d))}if(v.pathname==="/api/serverless/dlq/redrive"&&m.method==="POST"){let d=await m.json().catch(()=>({}));if(d.confirm!=="redrive")return g({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return g(await Wh(o,B,{max:d.max,targetQueue:d.targetQueue}))}if(v.pathname==="/api/serverless/dlq/purge"&&m.method==="POST"){if((await m.json().catch(()=>({}))).confirm!=="purge")return g({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return g(await Hh(o,B))}if(v.pathname==="/api/serverless/secrets"&&m.method==="GET")return g({secrets:Gh(o,B)});if(v.pathname==="/api/serverless/secrets"&&m.method==="POST"){let d=await m.json().catch(()=>({})),l=String(d.secretId??"").trim();if(!l)return g({ok:!1,error:"A secret id is required."},422);if(typeof d.value!=="string"||d.value==="")return g({ok:!1,error:"A non-empty value is required."},422);return g(await Kh(o,B,l,d.value))}if(v.pathname==="/api/serverless/secrets"&&m.method==="DELETE"){let d=await m.json().catch(()=>({})),l=String(d.secretId??"").trim();if(!l)return g({ok:!1,error:"A secret id is required."},422);if(d.confirm!==l)return g({ok:!1,error:`Type "${l}" to delete this secret.`},409);return g(await Qh(o,B,l))}if(v.pathname==="/api/serverless/functions/config"&&m.method==="POST"){let d=await m.json().catch(()=>({})),l=String(d.mode??"").trim();if(d.confirm!==l)return g({ok:!1,error:`Type "${l}" to update this function.`},409);return g(await Yh(o,B,l,{memory:d.memory,timeout:d.timeout}))}if(v.pathname==="/api/serverless/alarms"&&m.method==="GET")return g(await Xh(o,B));if(v.pathname==="/api/serverless/alarms"&&m.method==="POST"){let d=await m.json().catch(()=>({})),l=String(d.preset??"").trim(),h=Number(d.threshold);if(!l)return g({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(h))return g({ok:!1,error:"A numeric threshold is required."},422);return g(await Zh(o,B,l,h))}if(v.pathname==="/api/serverless/alarms"&&m.method==="DELETE"){let d=await m.json().catch(()=>({})),l=String(d.name??"").trim();if(!l)return g({ok:!1,error:"An alarm name is required."},422);if(d.confirm!==l)return g({ok:!1,error:`Type "${l}" to delete this alarm.`},409);return g(await ey(o,B,l))}if(v.pathname==="/api/serverless/traces"&&m.method==="GET"){let d=Number(v.searchParams.get("minutes"))||30;return g(await pa(o,B,d))}if(v.pathname==="/api/serverless/scheduler"&&m.method==="POST"){let d=await m.json().catch(()=>({})),l=String(d.action??"").trim();if(l!=="enable"&&l!=="disable"&&l!=="run")return g({ok:!1,error:"Unknown scheduler action."},422);if(d.confirm!==l)return g({ok:!1,error:`Type "${l}" to ${l} the scheduler.`},409);return g(await Mu(o,B,l))}if(!Ry(v.pathname,Ot))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(B)}`}});let zn=await Zt(O,B);if(!zn)return va("ts-cloud dashboard UI is unavailable.",503);return Py(zn,v.pathname)}catch(an){if(e.verbose)console.error(an);return g({ok:!1,error:an?.message??String(an)},500)}})();if(!Fe)return Fe;if(ye&&(v.pathname.startsWith("/api/")||v.pathname.startsWith("/auth/"))){let oe;if((z.headers.get("content-type")||"").includes("application/json"))oe=await z.json().catch(()=>{return});let Xe=Oe.resolveUser(m),Ge=Xe?Q(Xe).actor:void 0;a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,actorId:Ge?.id,correlationId:te,type:Fe.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Fe.status<400?"info":"warning",payload:FT(m.method,v.pathname,oe,Fe.status,Date.now()-K)})}return Fe.headers.set("x-request-id",te),Fe}});bo?.start();let vb=e.spendLoop??!0,cl;if(vb)(async()=>{let{SpendRunner:m,SpendLoopLease:q,startSpendLoop:K}=await import("./chunk-grepda40.js"),{store:z}=await Dy(a.store),te=new m({controlPlane:a.store,store:z,alerts:ne});cl=K(te,{lease:new q(a.store,{owner:`dashboard:${process.pid}`}),onError:(ye)=>console.error(`[ts-cloud] spend cycle failed: ${ye instanceof Error?ye.message:String(ye)}`)})})();let wb=Fn.stop.bind(Fn);return Fn.stop=(m)=>{clearInterval(il),clearInterval(ol),clearInterval(sl),clearInterval(nl),clearInterval(rl),clearInterval(Xu),clearInterval(Zu),clearInterval(el),clearInterval(tl),jt(),ze.clear(),bo?.stop(),cl?.();let q=wb(m);if(bo)bo.settled().finally(()=>a.store.close());else a.store.close();return q},{server:Fn,url:`http://${r}:${Fn.port}/`}}
|
|
511
|
-
export{Lo as w,Wr as x,sc as y,Lf as z,Rm as A,Pm as B,ty as C,uE as D,Om as E,Qi as F,Od as G,_d as H,Fd as I,Ud as J,Jd as K,Wd as L,Md as M,Ld as N,jd as O,ji as P,Fi as Q,Cc as R,Fp as S,Yo as T,Ec as U,Tc as V,Ac as W,kc as X,Rc as Y,xc as Z,Dc as _,Oc as $,Zn as aa,_c as ba,qa as ca,Hn as da,Ro as ea,Po as fa,$i as ga,Zl as ha,qn as ia,Pa as ja,Ft as ka,Oa as la,Na as ma,Ma as na,Eo as oa,da as pa,Cu as qa,ua as ra,oo as sa,Di as ta,ln as ua,Xi as va,eo as wa,Hs as xa,Kt as ya,xf as za,I$ as Aa,C$ as Ba,Ks as Ca,k$ as Da,Pn as Ea,ll as Fa,Uo as Ga,hn as Ha,yn as Ia,lc as Ja,fc as Ka,pc as La,gc as Ma,Sc as Na,wc as Oa,Go as Pa,e_ as Qa,Gd as Ra,Kd as Sa,cf as Ta,cr as Ua,Fu as Va,kB as Wa};
|