@stacksjs/ts-cloud 0.11.7 → 0.12.1
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-0rtn6q5x.js +3 -0
- package/dist/bin/chunk-258ehp9s.js +1 -0
- package/dist/bin/chunk-2yctv06c.js +1 -0
- package/dist/bin/chunk-3276rveh.js +37 -0
- package/dist/bin/chunk-3m665jwp.js +70 -0
- package/dist/bin/chunk-3s2p9vxj.js +1 -0
- package/dist/bin/chunk-4esma5m9.js +1 -0
- package/dist/bin/chunk-4n0j3n3b.js +2 -0
- package/dist/bin/chunk-54bqchag.js +92 -0
- package/dist/bin/{chunk-4q6tad44.js → chunk-5bhx3bsa.js} +121 -121
- package/dist/bin/chunk-5zagqd20.js +1 -0
- package/dist/bin/chunk-7hw2js5h.js +512 -0
- package/dist/bin/chunk-8h1qr6x4.js +50 -0
- package/dist/bin/{chunk-w32xv8n4.js → chunk-9vdc7adf.js} +6 -6
- package/dist/bin/chunk-a1dd6sby.js +1 -0
- package/dist/bin/chunk-a4dw35gs.js +1 -0
- package/dist/bin/chunk-a9d55ker.js +1 -0
- package/dist/bin/chunk-awa1qade.js +9 -0
- package/dist/bin/chunk-b6by94pk.js +2 -0
- package/dist/bin/chunk-c8sypnbe.js +2 -0
- package/dist/bin/chunk-cx4e3d4w.js +1 -0
- package/dist/bin/chunk-d5a3vheh.js +2 -0
- package/dist/bin/chunk-e1fym2bd.js +1 -0
- package/dist/bin/chunk-ej4h0q2y.js +1 -0
- package/dist/bin/chunk-ett305ym.js +4 -0
- package/dist/bin/chunk-f11xf3n6.js +2 -0
- package/dist/bin/chunk-fq7ktvgy.js +3 -0
- package/dist/bin/chunk-fyq4th2m.js +1 -0
- package/dist/bin/chunk-g67qr8yf.js +1 -0
- package/dist/bin/chunk-gc82cx4h.js +1 -0
- package/dist/bin/chunk-hchtvpr9.js +1 -0
- package/dist/bin/chunk-hpe4jjce.js +1 -0
- package/dist/bin/chunk-k5vprsef.js +6 -0
- package/dist/bin/chunk-m22krd4z.js +3 -0
- package/dist/bin/chunk-mkppcwz8.js +1 -0
- package/dist/bin/chunk-mpjg0kc7.js +2 -0
- package/dist/bin/chunk-mrm4m4dk.js +2 -0
- package/dist/bin/chunk-nff46rxd.js +1 -0
- package/dist/bin/chunk-np1z3bgt.js +1 -0
- package/dist/bin/chunk-nskxkk6r.js +1 -0
- package/dist/bin/chunk-pez932b1.js +111 -0
- package/dist/bin/chunk-qsdf5kzk.js +2 -0
- package/dist/bin/chunk-r61qmhv1.js +2 -0
- package/dist/bin/chunk-r6gdcz5c.js +1 -0
- package/dist/bin/chunk-satwnr42.js +2 -0
- package/dist/bin/{chunk-dz1ec589.js → chunk-scqmd4qv.js} +30 -30
- package/dist/bin/chunk-smbycpt5.js +44 -0
- package/dist/bin/chunk-sn7e0sn7.js +2 -0
- package/dist/bin/chunk-ss574pka.js +1 -0
- package/dist/bin/chunk-tj0xb2d8.js +585 -0
- package/dist/bin/chunk-v3rzf9d0.js +141 -0
- package/dist/bin/chunk-wnpma6t3.js +34 -0
- package/dist/bin/chunk-xan0e052.js +5 -0
- package/dist/bin/chunk-xbk2y43r.js +60 -0
- package/dist/bin/chunk-xjp3v95e.js +6 -0
- package/dist/bin/chunk-xyt490vp.js +6 -0
- package/dist/bin/chunk-yn9r02gy.js +1 -0
- package/dist/bin/chunk-zhkhn9cc.js +1 -0
- package/dist/bin/cli.js +445 -430
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-0zf72ngj.js +1 -0
- package/dist/chunk-2hpjte1d.js +704 -0
- package/dist/chunk-4m6gwhwr.js +5 -0
- package/dist/chunk-5m29dhke.js +34 -0
- package/dist/chunk-6fzeemcs.js +114 -0
- package/dist/{chunk-zz52xje8.js → chunk-6xcbfs2r.js} +111 -111
- package/dist/chunk-bpnhqb70.js +6 -0
- package/dist/chunk-ead1nkbr.js +60 -0
- package/dist/chunk-fea461tj.js +141 -0
- package/dist/chunk-fvjczc73.js +1 -0
- package/dist/chunk-gearw6rk.js +4 -0
- package/dist/chunk-j60hesb3.js +2 -0
- package/dist/chunk-pmgtmt3d.js +1 -0
- package/dist/chunk-prf2pkvq.js +5 -0
- package/dist/chunk-q0wffgw5.js +37 -0
- package/dist/chunk-qcemnt35.js +50 -0
- package/dist/chunk-qvbwsaay.js +1 -0
- package/dist/chunk-r2pbqcnz.js +2 -0
- package/dist/chunk-r6110zv2.js +1 -0
- package/dist/chunk-rr1yaj55.js +2 -0
- package/dist/chunk-wcrj06cg.js +44 -0
- package/dist/chunk-wte9mh18.js +92 -0
- package/dist/{chunk-aw0cgv5w.js → chunk-y1dh3znq.js} +52 -52
- package/dist/chunk-y6e86wjs.js +445 -0
- package/dist/chunk-y8b7ht4v.js +1 -0
- package/dist/chunk-yf487g6e.js +2 -0
- package/dist/chunk-zmmc9j5f.js +2 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +91 -91
- package/dist/operations/drained-sites.d.ts +56 -0
- package/dist/operations/drained-sites.test.d.ts +1 -0
- package/dist/pages/cloudflare-pages.d.ts +240 -0
- package/dist/pages/cloudflare-pages.test.d.ts +1 -0
- package/dist/pages/index.d.ts +2 -0
- 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 +2 -2
- package/dist/ui/data/backups.html +80 -80
- package/dist/ui/data/services.html +78 -78
- package/dist/ui/data/volumes.html +50 -50
- package/dist/ui/index.html +50 -50
- package/dist/ui/infrastructure/topology.html +118 -118
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +48 -48
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +75 -75
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +82 -82
- 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 +54 -54
- package/dist/ui/operations/workloads.html +104 -104
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +105 -105
- package/dist/ui/server/deployments.html +50 -50
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +76 -76
- package/dist/ui/server/fleet.html +34 -34
- package/dist/ui/server/logs.html +24 -24
- package/dist/ui/server/metrics.html +112 -112
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +26 -26
- package/dist/ui/server/sites.html +120 -120
- package/dist/ui/server/ssh-keys.html +52 -52
- package/dist/ui/server/team.html +144 -144
- package/dist/ui/server/terminal.html +15 -15
- package/dist/ui/serverless/alarms.html +52 -52
- package/dist/ui/serverless/assets.html +27 -27
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +35 -35
- package/dist/ui/serverless/deployments.html +27 -27
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +40 -40
- package/dist/ui/serverless/logs.html +24 -24
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +48 -48
- package/dist/ui/serverless/secrets.html +52 -52
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +53 -53
- package/dist/ui-src/src/charts.ts +8721 -13558
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +4 -3
- package/dist/bin/chunk-0zwknfwp.js +0 -1
- package/dist/bin/chunk-3aph4c1w.js +0 -2
- package/dist/bin/chunk-4xhj37nj.js +0 -37
- package/dist/bin/chunk-5nkqza92.js +0 -1
- package/dist/bin/chunk-5nsqz5n3.js +0 -585
- package/dist/bin/chunk-64vczwwt.js +0 -1
- package/dist/bin/chunk-6tfwm33r.js +0 -6
- package/dist/bin/chunk-7g2ahkse.js +0 -1
- package/dist/bin/chunk-7zhgmp1s.js +0 -3
- package/dist/bin/chunk-82mj52xr.js +0 -141
- package/dist/bin/chunk-8khgprf6.js +0 -44
- package/dist/bin/chunk-9a88fp00.js +0 -2
- package/dist/bin/chunk-a7w13qfm.js +0 -2
- package/dist/bin/chunk-b4wt9jcg.js +0 -60
- package/dist/bin/chunk-btsyjhk7.js +0 -92
- package/dist/bin/chunk-c0bdafbx.js +0 -2
- package/dist/bin/chunk-cbsys5v8.js +0 -111
- package/dist/bin/chunk-cd0ps58j.js +0 -1
- package/dist/bin/chunk-d7ke90zt.js +0 -2
- package/dist/bin/chunk-djg4zyqk.js +0 -1
- package/dist/bin/chunk-dkaz333b.js +0 -1
- package/dist/bin/chunk-dkf4qsp2.js +0 -1
- package/dist/bin/chunk-e2bybahr.js +0 -3
- package/dist/bin/chunk-e5ab5twy.js +0 -50
- package/dist/bin/chunk-edvvx3hg.js +0 -1
- package/dist/bin/chunk-ehc63fvs.js +0 -2
- package/dist/bin/chunk-f06c5np9.js +0 -1
- package/dist/bin/chunk-g0fm1xcs.js +0 -1
- package/dist/bin/chunk-gq8794k6.js +0 -1
- package/dist/bin/chunk-hq9x489e.js +0 -70
- package/dist/bin/chunk-j447p8t4.js +0 -512
- package/dist/bin/chunk-ja1vjdn1.js +0 -6
- package/dist/bin/chunk-k3120rx6.js +0 -1
- package/dist/bin/chunk-kg61p5hw.js +0 -3
- package/dist/bin/chunk-mcr0r4at.js +0 -2
- package/dist/bin/chunk-mfrf9q4b.js +0 -2
- package/dist/bin/chunk-my3ewh3a.js +0 -34
- package/dist/bin/chunk-nw3d4k52.js +0 -1
- package/dist/bin/chunk-p70bc9yr.js +0 -1
- package/dist/bin/chunk-r6b3pq31.js +0 -4
- package/dist/bin/chunk-s4yzes15.js +0 -2
- package/dist/bin/chunk-sj5csg49.js +0 -2
- package/dist/bin/chunk-tvz9c388.js +0 -1
- package/dist/bin/chunk-wkx799z2.js +0 -1
- package/dist/bin/chunk-x6f61g36.js +0 -9
- package/dist/bin/chunk-xhwqpgwq.js +0 -2
- package/dist/bin/chunk-xk08030d.js +0 -6
- package/dist/bin/chunk-y1h63vpm.js +0 -1
- package/dist/bin/chunk-yw6f160x.js +0 -1
- package/dist/bin/chunk-zdt2rjk6.js +0 -1
- package/dist/bin/chunk-zh2d4704.js +0 -1
- package/dist/bin/chunk-znnawt0k.js +0 -1
- package/dist/bin/chunk-zpe64t4r.js +0 -1
- package/dist/bin/chunk-zsf6pccz.js +0 -1
- package/dist/chunk-1qdne0bf.js +0 -1
- package/dist/chunk-5vt93kxx.js +0 -1
- package/dist/chunk-73ztr55z.js +0 -2
- package/dist/chunk-95e6aeqz.js +0 -1
- package/dist/chunk-aj025v2s.js +0 -4
- package/dist/chunk-aw0spg20.js +0 -445
- package/dist/chunk-by2bwzk6.js +0 -141
- package/dist/chunk-dr4pj8hp.js +0 -5
- package/dist/chunk-hn40z11p.js +0 -37
- package/dist/chunk-kasdm9tx.js +0 -34
- package/dist/chunk-mz0dk78z.js +0 -6
- package/dist/chunk-nk7sav4r.js +0 -92
- package/dist/chunk-p10xt3jb.js +0 -1
- package/dist/chunk-q0rc1ax9.js +0 -114
- package/dist/chunk-q9q6cmt0.js +0 -1
- package/dist/chunk-rd38qdnf.js +0 -1
- package/dist/chunk-tz9myq9a.js +0 -2
- package/dist/chunk-wavjkdb8.js +0 -2
- package/dist/chunk-x3hay61c.js +0 -44
- package/dist/chunk-xcj8zfmg.js +0 -2
- package/dist/chunk-y4xkj2f1.js +0 -50
- package/dist/chunk-ywjkyg8p.js +0 -704
- package/dist/chunk-z2qqwy7e.js +0 -2
- package/dist/chunk-zam6ecam.js +0 -60
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Al as $t}from"./chunk-x3hay61c.js";import{Vl as yr,Wl as Lr}from"./chunk-zz52xje8.js";var Es=["edge.requests","edge.egress_gb","function.invocations","function.gb_seconds","build.minutes","compute.instance_hours","storage.gb_hours","object.egress_gb","object.requests","database.gb_hours","database.io_requests","telemetry.ingest_gb","image.transformations"],ut={"edge.requests":{key:"edge.requests",unit:"requests",label:"Edge requests",precision:0},"edge.egress_gb":{key:"edge.egress_gb",unit:"gb",label:"Edge egress",precision:3},"function.invocations":{key:"function.invocations",unit:"invocations",label:"Function invocations",precision:0},"function.gb_seconds":{key:"function.gb_seconds",unit:"gb_seconds",label:"Function compute",precision:2},"build.minutes":{key:"build.minutes",unit:"minutes",label:"Build minutes",precision:2},"compute.instance_hours":{key:"compute.instance_hours",unit:"hours",label:"Instance hours",precision:2},"storage.gb_hours":{key:"storage.gb_hours",unit:"gb_hours",label:"Block storage",precision:2},"object.egress_gb":{key:"object.egress_gb",unit:"gb",label:"Object storage egress",precision:3},"object.requests":{key:"object.requests",unit:"requests",label:"Object storage requests",precision:0},"database.gb_hours":{key:"database.gb_hours",unit:"gb_hours",label:"Database storage",precision:2},"database.io_requests":{key:"database.io_requests",unit:"requests",label:"Database I/O",precision:0},"telemetry.ingest_gb":{key:"telemetry.ingest_gb",unit:"gb",label:"Telemetry ingest",precision:3},"image.transformations":{key:"image.transformations",unit:"count",label:"Image transformations",precision:0}},ms=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],k={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var gs=1e6;function Un(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function lr(e,t){if(!(e>0))return 0;let r=[...t].sort((s,a)=>{if(s.upToQuantity===null)return 1;if(a.upToQuantity===null)return-1;return s.upToQuantity-a.upToQuantity}),n=e,i=0,o=0;for(let s of r){if(n<=0)break;let d=(s.upToQuantity===null?1/0:s.upToQuantity)-i;if(d<=0)continue;let c=Math.min(n,d);o+=c*s.microCentsPerUnit,n-=c,i+=c}if(n>0){let s=r.reduce((a,d)=>Math.max(a,d.microCentsPerUnit),0);o+=n*s}return o}function Dn(e,t,r,n){let i=e.entries.filter((a)=>a.meter===t);if(i.length===0)return;let o=i.filter((a)=>a.provider===r),s=o.length>0?o:i.filter((a)=>a.provider==="*");return s.find((a)=>a.region===n)??s.find((a)=>a.region==null)}function pt(e,t,r=0){let n=Dn(e,t.meter,t.provider,t.region),i=Math.max(0,t.quantity);if(!n)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:i,includedQuantity:0,billableQuantity:i,costCents:0,unpriced:!0};let o=Math.max(0,n.includedQuantity??0),s=Math.max(0,r-o),a=Math.max(0,o-Math.max(0,r)),d=Math.min(i,a),c=i-d,p=Un(n),l=lr(s+c,p)-lr(s,p);return{meter:t.meter,provider:n.provider,region:n.region??t.region,quantity:i,includedQuantity:d,billableQuantity:c,costCents:l/1e6,unpriced:!1}}function _s(e,t){let r=new Map,n=[];for(let i of t){let o=`${i.meter}\x00${i.provider??""}\x00${i.region??""}`,s=r.get(o)??0,a=pt(e,i,s);r.set(o,s+a.quantity),n.push(a)}return{currency:e.currency,totalCents:n.reduce((i,o)=>i+o.costCents,0),lines:n,unpricedMeters:[...new Set(n.filter((i)=>i.unpriced).map((i)=>String(i.meter)))]}}function hs(e){return Math.round(e*100)/100}function Ns(e,...t){let r=new Map,n=(o)=>`${o.meter}\x00${o.provider}\x00${o.region??""}`;for(let o of e.entries)r.set(n(o),o);let i=e.currency;for(let o of t){i=o.currency||i;for(let s of o.entries)r.set(n(s),s)}return{currency:i,entries:[...r.values()]}}var K=(e)=>Math.round(e*1e6),j=(e)=>Math.round(e*1e6),ur={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:j(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:K(8.5)},{upToQuantity:51200,microCentsPerUnit:K(8)},{upToQuantity:null,microCentsPerUnit:K(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:j(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:j(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:j(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:K(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:j(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:j(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:j(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:K(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:K(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:j(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:j(0.006027397260273972)},{meter:"edge.requests",provider:"hetzner",microCentsPerUnit:0},{meter:"edge.requests",provider:"local",microCentsPerUnit:0},{meter:"edge.egress_gb",provider:"local",microCentsPerUnit:0},{meter:"function.invocations",provider:"local",microCentsPerUnit:0},{meter:"function.gb_seconds",provider:"local",microCentsPerUnit:0},{meter:"build.minutes",provider:"*",includedQuantity:6000,microCentsPerUnit:j(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:K(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:j(0.05)}]};var pr=new Map;function mr(e){let t=pr.get(e);if(!t)t=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short",hourCycle:"h23"}),pr.set(e,t);return t}var wn={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function Ue(e){try{return mr(e),!0}catch{return!1}}function Et(e,t){let r=mr(t).formatToParts(e),n=(i)=>r.find((o)=>o.type===i)?.value??"0";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),second:Number(n("second")),weekday:wn[n("weekday")]??0}}function Er(e,t){let r=Et(e,t);return Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)-Math.floor(e.getTime()/1000)*1000}function te(e,t,r,n,i=0){let o=Date.UTC(t,r-1,n,i),s=new Date(o-Er(new Date(o),e));return new Date(o-Er(s,e))}function kn(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function Q(e,t,r=new Date){let n=Ue(t)?t:"UTC",i=Et(r,n),o,s,a;if(e==="daily")o=te(n,i.year,i.month,i.day),s=te(n,i.year,i.month,i.day+1),a=`${i.year}-${String(i.month).padStart(2,"0")}-${String(i.day).padStart(2,"0")}`;else if(e==="weekly"){let p=(i.weekday+6)%7;o=te(n,i.year,i.month,i.day-p),s=te(n,i.year,i.month,i.day-p+7);let l=Et(o,n);a=`week of ${l.year}-${String(l.month).padStart(2,"0")}-${String(l.day).padStart(2,"0")}`}else o=te(n,i.year,i.month,1),s=te(n,i.year,i.month+1,1),a=kn(i.year,i.month);let d=s.getTime()-o.getTime(),c=Math.max(0,Math.min(d,r.getTime()-o.getTime()));return{start:o.toISOString(),end:s.toISOString(),elapsedMs:c,totalMs:d,label:a}}function ys(e,t,r=new Date){let n=Q(e,t,r),i=new Date(new Date(n.start).getTime()-1),o=Q(e,t,i);return{...o,elapsedMs:o.totalMs}}function ue(e){let r=(typeof e==="string"?new Date(e):e).getTime();if(!Number.isFinite(r))throw Error("hourBucket requires a valid date");return new Date(Math.floor(r/3600000)*3600000).toISOString()}function Ls(e,t,r=9600){let n=Math.floor(new Date(e).getTime()/3600000)*3600000,i=new Date(t).getTime();if(!Number.isFinite(n)||!Number.isFinite(i))throw Error("hourBucketsBetween requires valid dates");let o=[];for(let s=n;s<i&&o.length<r;s+=3600000)o.push(new Date(s).toISOString());return o}import{createHash as Xn}from"node:crypto";var De=1073741824,gr=[{match:"request.count",meter:"edge.requests"},{match:"traffic.requests",meter:"edge.requests"},{match:"http.request",meter:"edge.requests",field:"count"},{match:"traffic.bytes_out",meter:"edge.egress_gb",scale:1/De},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/De},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/De,cumulative:!0},{match:"storage.egress.day_downloads",meter:"object.requests"},{match:"function.invocation",meter:"function.invocations",field:"count"},{match:"function.duration_ms",meter:"function.gb_seconds",scale:0.001},{match:"build.duration_ms",meter:"build.minutes",scale:0.000016666666666666667},{match:"telemetry.ingest_bytes",meter:"telemetry.ingest_gb",scale:1/De},{match:"image.transform",meter:"image.transformations",field:"count"}];function Pn(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function xn(e,t=gr){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>Pn(r,e))}function jn(e,t){let r=t.field??"value",n=r==="count"?1:r==="bytesOut"?e.bytesOut:r==="bytesIn"?e.bytesIn:r==="durationMs"?e.durationMs:e.value;if(n==null||!Number.isFinite(n))return;return n*(t.scale??1)}function Fn(e,t){return Xn("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class mt{resetToleranceRatio;last=new Map;constructor(e=0.999){this.resetToleranceRatio=e}delta(e,t,r=new Date){if(!Number.isFinite(t)||t<0)return;let n=new Date(r).getTime(),i=this.last.get(e);if(!i)return this.last.set(e,{value:t,at:n}),t>0?t:void 0;if(n<i.at)return;if(t<i.value&&t>=i.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:n}),t>=i.value){let o=t-i.value;return o>0?o:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[n,i]of this.last)if(i.at<t)this.last.delete(n),r++;return r}get size(){return this.last.size}}function Tr(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function _r(e,t,r={}){let n=r.mappings??gr,i=r.counters,o=[];for(let s of t){let a=xn(s.name,n);if(!a)continue;let d=jn(s,a);if(d==null)continue;if(a.cumulative){if(!i)continue;let p=[s.projectId,s.environmentId??"",s.resourceId??"",s.name,s.source].join("\x00"),l=i.delta(p,d,s.timestamp);if(l==null)continue;d=l}if(!(d>0))continue;let c={organizationId:e,projectId:s.projectId,environmentId:s.environmentId,resourceId:s.resourceId,provider:Tr(s.attributes,"provider")??r.defaultProvider,region:s.region??Tr(s.attributes,"region"),meter:a.meter,quantity:d,timestamp:s.timestamp,attributes:{source:s.source,signal:s.name}};o.push({...c,key:Fn(c,s.id)})}return o}function hr(e){let t=new Map;for(let r of e){let n=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),i=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,n].join("\x00"),o=t.get(i);if(o)o.quantity+=r.quantity;else t.set(i,{...r,timestamp:n})}return[...t.values()]}import{createHash as ti}from"node:crypto";var q=40,Tt=[{version:1,name:"core_control_plane",sql:`
|
|
1
|
+
import{Al as zt}from"./chunk-wcrj06cg.js";import{Vl as Rr,Wl as Or}from"./chunk-6xcbfs2r.js";var cE=["edge.requests","edge.egress_gb","function.invocations","function.gb_seconds","build.minutes","compute.instance_hours","storage.gb_hours","object.egress_gb","object.requests","database.gb_hours","database.io_requests","telemetry.ingest_gb","image.transformations"],ot={"edge.requests":{key:"edge.requests",unit:"requests",label:"Edge requests",precision:0},"edge.egress_gb":{key:"edge.egress_gb",unit:"gb",label:"Edge egress",precision:3},"function.invocations":{key:"function.invocations",unit:"invocations",label:"Function invocations",precision:0},"function.gb_seconds":{key:"function.gb_seconds",unit:"gb_seconds",label:"Function compute",precision:2},"build.minutes":{key:"build.minutes",unit:"minutes",label:"Build minutes",precision:2},"compute.instance_hours":{key:"compute.instance_hours",unit:"hours",label:"Instance hours",precision:2},"storage.gb_hours":{key:"storage.gb_hours",unit:"gb_hours",label:"Block storage",precision:2},"object.egress_gb":{key:"object.egress_gb",unit:"gb",label:"Object storage egress",precision:3},"object.requests":{key:"object.requests",unit:"requests",label:"Object storage requests",precision:0},"database.gb_hours":{key:"database.gb_hours",unit:"gb_hours",label:"Database storage",precision:2},"database.io_requests":{key:"database.io_requests",unit:"requests",label:"Database I/O",precision:0},"telemetry.ingest_gb":{key:"telemetry.ingest_gb",unit:"gb",label:"Telemetry ingest",precision:3},"image.transformations":{key:"image.transformations",unit:"count",label:"Image transformations",precision:0}},NE=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],k={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var lE=1e6;function vs(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function Tr(e,t){if(!(e>0))return 0;let r=[...t].sort((E,a)=>{if(E.upToQuantity===null)return 1;if(a.upToQuantity===null)return-1;return E.upToQuantity-a.upToQuantity}),s=e,n=0,i=0;for(let E of r){if(s<=0)break;let d=(E.upToQuantity===null?1/0:E.upToQuantity)-n;if(d<=0)continue;let T=Math.min(s,d);i+=T*E.microCentsPerUnit,s-=T,n+=T}if(s>0){let E=r.reduce((a,d)=>Math.max(a,d.microCentsPerUnit),0);i+=s*E}return i}function ys(e,t,r,s){let n=e.entries.filter((a)=>a.meter===t);if(n.length===0)return;let i=n.filter((a)=>a.provider===r),E=i.length>0?i:n.filter((a)=>a.provider==="*");return E.find((a)=>a.region===s)??E.find((a)=>a.region==null)}function ct(e,t,r=0){let s=ys(e,t.meter,t.provider,t.region),n=Math.max(0,t.quantity);if(!s)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:n,includedQuantity:0,billableQuantity:n,costCents:0,unpriced:!0};let i=Math.max(0,s.includedQuantity??0),E=Math.max(0,r-i),a=Math.max(0,i-Math.max(0,r)),d=Math.min(n,a),T=n-d,N=vs(s),o=Tr(E+T,N)-Tr(E,N);return{meter:t.meter,provider:s.provider,region:s.region??t.region,quantity:n,includedQuantity:d,billableQuantity:T,costCents:o/1e6,unpriced:!1}}function LE(e,t){let r=new Map,s=[];for(let n of t){let i=`${n.meter}\x00${n.provider??""}\x00${n.region??""}`,E=r.get(i)??0,a=ct(e,n,E);r.set(i,E+a.quantity),s.push(a)}return{currency:e.currency,totalCents:s.reduce((n,i)=>n+i.costCents,0),lines:s,unpricedMeters:[...new Set(s.filter((n)=>n.unpriced).map((n)=>String(n.meter)))]}}function mE(e){return Math.round(e*100)/100}function uE(e,...t){let r=new Map,s=(i)=>`${i.meter}\x00${i.provider}\x00${i.region??""}`;for(let i of e.entries)r.set(s(i),i);let n=e.currency;for(let i of t){n=i.currency||n;for(let E of i.entries)r.set(s(E),E)}return{currency:n,entries:[...r.values()]}}var z=(e)=>Math.round(e*1e6),K=(e)=>Math.round(e*1e6),or={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:K(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:z(8.5)},{upToQuantity:51200,microCentsPerUnit:z(8)},{upToQuantity:null,microCentsPerUnit:z(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:K(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:K(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:K(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:z(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:K(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:K(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:K(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:z(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:z(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:K(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:K(0.006027397260273972)},{meter:"edge.requests",provider:"hetzner",microCentsPerUnit:0},{meter:"edge.requests",provider:"local",microCentsPerUnit:0},{meter:"edge.egress_gb",provider:"local",microCentsPerUnit:0},{meter:"function.invocations",provider:"local",microCentsPerUnit:0},{meter:"function.gb_seconds",provider:"local",microCentsPerUnit:0},{meter:"build.minutes",provider:"*",includedQuantity:6000,microCentsPerUnit:K(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:z(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:K(0.05)}]};var cr=new Map;function _r(e){let t=cr.get(e);if(!t)t=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short",hourCycle:"h23"}),cr.set(e,t);return t}var ps={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function ye(e){try{return _r(e),!0}catch{return!1}}function Nt(e,t){let r=_r(t).formatToParts(e),s=(n)=>r.find((i)=>i.type===n)?.value??"0";return{year:Number(s("year")),month:Number(s("month")),day:Number(s("day")),hour:Number(s("hour")),minute:Number(s("minute")),second:Number(s("second")),weekday:ps[s("weekday")]??0}}function Nr(e,t){let r=Nt(e,t);return Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)-Math.floor(e.getTime()/1000)*1000}function ee(e,t,r,s,n=0){let i=Date.UTC(t,r-1,s,n),E=new Date(i-Nr(new Date(i),e));return new Date(i-Nr(E,e))}function Ds(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function G(e,t,r=new Date){let s=ye(t)?t:"UTC",n=Nt(r,s),i,E,a;if(e==="daily")i=ee(s,n.year,n.month,n.day),E=ee(s,n.year,n.month,n.day+1),a=`${n.year}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`;else if(e==="weekly"){let N=(n.weekday+6)%7;i=ee(s,n.year,n.month,n.day-N),E=ee(s,n.year,n.month,n.day-N+7);let o=Nt(i,s);a=`week of ${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`}else i=ee(s,n.year,n.month,1),E=ee(s,n.year,n.month+1,1),a=Ds(n.year,n.month);let d=E.getTime()-i.getTime(),T=Math.max(0,Math.min(d,r.getTime()-i.getTime()));return{start:i.toISOString(),end:E.toISOString(),elapsedMs:T,totalMs:d,label:a}}function gE(e,t,r=new Date){let s=G(e,t,r),n=new Date(new Date(s.start).getTime()-1),i=G(e,t,n);return{...i,elapsedMs:i.totalMs}}function oe(e){let r=(typeof e==="string"?new Date(e):e).getTime();if(!Number.isFinite(r))throw Error("hourBucket requires a valid date");return new Date(Math.floor(r/3600000)*3600000).toISOString()}function RE(e,t,r=9600){let s=Math.floor(new Date(e).getTime()/3600000)*3600000,n=new Date(t).getTime();if(!Number.isFinite(s)||!Number.isFinite(n))throw Error("hourBucketsBetween requires valid dates");let i=[];for(let E=s;E<n&&i.length<r;E+=3600000)i.push(new Date(E).toISOString());return i}import{createHash as bs}from"node:crypto";var pe=1073741824,Lr=[{match:"request.count",meter:"edge.requests"},{match:"traffic.requests",meter:"edge.requests"},{match:"http.request",meter:"edge.requests",field:"count"},{match:"traffic.bytes_out",meter:"edge.egress_gb",scale:1/pe},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/pe},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/pe,cumulative:!0},{match:"storage.egress.day_downloads",meter:"object.requests"},{match:"function.invocation",meter:"function.invocations",field:"count"},{match:"function.duration_ms",meter:"function.gb_seconds",scale:0.001},{match:"build.duration_ms",meter:"build.minutes",scale:0.000016666666666666667},{match:"telemetry.ingest_bytes",meter:"telemetry.ingest_gb",scale:1/pe},{match:"image.transform",meter:"image.transformations",field:"count"}];function ks(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function Fs(e,t=Lr){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>ks(r,e))}function Ps(e,t){let r=t.field??"value",s=r==="count"?1:r==="bytesOut"?e.bytesOut:r==="bytesIn"?e.bytesIn:r==="durationMs"?e.durationMs:e.value;if(s==null||!Number.isFinite(s))return;return s*(t.scale??1)}function Hs(e,t){return bs("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class _t{resetToleranceRatio;last=new Map;constructor(e=0.999){this.resetToleranceRatio=e}delta(e,t,r=new Date){if(!Number.isFinite(t)||t<0)return;let s=new Date(r).getTime(),n=this.last.get(e);if(!n)return this.last.set(e,{value:t,at:s}),t>0?t:void 0;if(s<n.at)return;if(t<n.value&&t>=n.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:s}),t>=n.value){let i=t-n.value;return i>0?i:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[s,n]of this.last)if(n.at<t)this.last.delete(s),r++;return r}get size(){return this.last.size}}function lr(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function mr(e,t,r={}){let s=r.mappings??Lr,n=r.counters,i=[];for(let E of t){let a=Fs(E.name,s);if(!a)continue;let d=Ps(E,a);if(d==null)continue;if(a.cumulative){if(!n)continue;let N=[E.projectId,E.environmentId??"",E.resourceId??"",E.name,E.source].join("\x00"),o=n.delta(N,d,E.timestamp);if(o==null)continue;d=o}if(!(d>0))continue;let T={organizationId:e,projectId:E.projectId,environmentId:E.environmentId,resourceId:E.resourceId,provider:lr(E.attributes,"provider")??r.defaultProvider,region:E.region??lr(E.attributes,"region"),meter:a.meter,quantity:d,timestamp:E.timestamp,attributes:{source:E.source,signal:E.name}};i.push({...T,key:Hs(T,E.id)})}return i}function ur(e){let t=new Map;for(let r of e){let s=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),n=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,s].join("\x00"),i=t.get(n);if(i)i.quantity+=r.quantity;else t.set(n,{...r,timestamp:s})}return[...t.values()]}import{createHash as ws}from"node:crypto";var B=40,lt=[{version:1,name:"core_control_plane",sql:`
|
|
2
2
|
CREATE TABLE projects (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
slug TEXT NOT NULL UNIQUE,
|
|
@@ -1475,71 +1475,71 @@ import{Al as $t}from"./chunk-x3hay61c.js";import{Vl as yr,Wl as Lr}from"./chunk-
|
|
|
1475
1475
|
-- once a minute, forever.
|
|
1476
1476
|
CREATE INDEX telemetry_kind_scope_time_idx
|
|
1477
1477
|
ON telemetry_records(project_id, kind, timestamp);
|
|
1478
|
-
`}];import{createHash as
|
|
1479
|
-
[output truncated]`}function
|
|
1480
|
-
WHERE id = ? AND version = ?`,[r.name??
|
|
1481
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,
|
|
1482
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.environmentId??null,e.kind,e.slug,e.name,e.provider??null,e.providerId??null,
|
|
1483
|
-
version = version + 1, updated_at = ? WHERE id = ? AND version = ?`,[r.name??
|
|
1484
|
-
WHERE organization_memberships.actor_id = ? AND organization_memberships.status = 'active' ORDER BY organizations.name COLLATE NOCASE`).all(e):this.database.query("SELECT * FROM organizations ORDER BY name COLLATE NOCASE").all()).map(
|
|
1485
|
-
JOIN projects ON projects.id = resources.project_id WHERE resources.id = ? AND projects.organization_id = ?`).get(t.id,e);return r?{organizationId:e,projectId:String(r.project_id),environmentId:
|
|
1486
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",
|
|
1487
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1488
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1489
|
-
VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, '{}', ?, ?, ?)`,[t,e.projectId??null,e.environmentId??null,e.resourceId??null,e.actorId??null,e.kind,r,e.idempotencyKey??null,
|
|
1490
|
-
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[e,
|
|
1491
|
-
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[t,
|
|
1492
|
-
finished_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?`,[t.to,
|
|
1493
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,
|
|
1494
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,[e,
|
|
1495
|
-
WHERE tags.project_id = ? ORDER BY tags.normalized_name`).all(e).map((r)=>({resourceId:String(r.resource_id),tag:
|
|
1496
|
-
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET last_visited_at = excluded.last_visited_at, visit_count = visit_count + 1`,[e,t,r,
|
|
1497
|
-
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET favorite = excluded.favorite`,[e,t,r,
|
|
1498
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1499
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1500
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1501
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1502
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1503
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1504
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1478
|
+
`}];import{createHash as Fe,randomBytes as Ms}from"node:crypto";import{chmodSync as Ct,existsSync as Cr,mkdirSync as js,statSync as Bs}from"node:fs";import{dirname as gr}from"node:path";import{Database as $s}from"bun:sqlite";var te=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],Lt=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ks={owner:new Set(te),admin:new Set(te.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...Lt,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...Lt,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(Lt),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function De(e){return Ks[e]}function mt(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function be(e){let{membership:t,capability:r,target:s}=e;if(!t||t.status!=="active"||t.organizationId!==s.organizationId)return{allowed:!1,reason:"inactive-membership"};let n=e.grants.filter((a)=>a.organizationId===s.organizationId&&a.membershipId===t.id&&a.capability===r&&mt(a.scope,s)),i=n.find((a)=>a.effect==="deny");if(i)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:i.id,scope:i.scope}};let E=n.find((a)=>a.effect==="allow");if(E)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};if(!mt(t.scope,s))return{allowed:!1,reason:"scope-mismatch"};if(De(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function xs(e){return te.filter((t)=>be({...e,capability:t}).allowed)}class q extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class ut extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class ke extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}function qs(){return Rr("control-plane.sqlite")}var Ar=65536,Ot=16384,Ys=["succeeded","failed","cancelled","timed_out"],zs={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},Gs=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,Ur=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function P(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function O(e){return typeof e==="string"?e:void 0}function At(e,t){if(t&&Gs.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(Ur,"[REDACTED]");if(Array.isArray(e))return e.map((r)=>At(r));if(e&&typeof e==="object"){let r={};for(let[s,n]of Object.entries(e))r[s]=At(n,s);return r}return String(e??"")}function h(e,t=Ar){let r=At(e),s=JSON.stringify(r);if(Buffer.byteLength(s)<=t)return r;return{truncated:!0,originalBytes:Buffer.byteLength(s),preview:s.slice(0,Math.max(0,t-128))}}function U(e){return JSON.stringify(h(e))}function gt(e){if(!e)return;let t=e.replace(Ur,"[REDACTED]");return Buffer.byteLength(t)<=Ot?t:`${t.slice(0,Ot-24)}
|
|
1479
|
+
[output truncated]`}function Pe(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:O(e.description),organizationId:O(e.organization_id),desiredConfigHash:O(e.desired_config_hash),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function He(e){return{id:String(e.id),projectId:String(e.project_id),slug:String(e.slug),name:String(e.name),kind:String(e.kind),region:O(e.region),desiredState:P(e.desired_state),discoveredState:P(e.discovered_state),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ke(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:O(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:O(e.provider),providerId:O(e.provider_id),desiredState:P(e.desired_state),discoveredState:P(e.discovered_state),metadata:P(e.metadata),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function xe(e){return{id:String(e.id),kind:String(e.kind),externalId:O(e.external_id),displayName:String(e.display_name),metadata:P(e.metadata),disabledAt:O(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Q(e){return{id:String(e.id),projectId:O(e.project_id),environmentId:O(e.environment_id),resourceId:O(e.resource_id),actorId:O(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:O(e.idempotency_key),input:P(e.input),output:P(e.output),error:O(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:O(e.lease_owner),leaseExpiresAt:O(e.lease_expires_at),cancelRequestedAt:O(e.cancel_requested_at),startedAt:O(e.started_at),finishedAt:O(e.finished_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Rt(e){return{id:String(e.id),sequence:Number(e.sequence),organizationId:O(e.organization_id),projectId:O(e.project_id),operationId:O(e.operation_id),resourceId:O(e.resource_id),actorId:O(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:P(e.payload),createdAt:String(e.created_at)}}function ce(e){return{id:String(e.id),projectId:String(e.project_id),name:String(e.name),normalizedName:String(e.normalized_name),color:String(e.color),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Me(e){return{id:String(e.id),actorKey:String(e.actor_key),name:String(e.name),routeId:String(e.route_id),query:P(e.query),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function je(e){return{actorKey:String(e.actor_key),entityType:String(e.entity_type),entityId:String(e.entity_id),favorite:Number(e.favorite)===1,lastVisitedAt:String(e.last_visited_at),visitCount:Number(e.visit_count)}}function Be(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ut(e){let t=String(e.scope_type);return{type:t,...t==="organization"?{}:{id:String(e.scope_id)}}}function $e(e){return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),roleTemplate:String(e.role_template),scope:Ut(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:O(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ne(e,t){let r=O(e.accepted_at),s=O(e.revoked_at),n=String(e.expires_at),i=s?"revoked":r?"accepted":n<=t?"expired":"pending";return{id:String(e.id),organizationId:String(e.organization_id),email:String(e.email),roleTemplate:String(e.role_template),scope:Ut(e),invitedByActorId:O(e.invited_by_actor_id),acceptedByActorId:O(e.accepted_by_actor_id),expiresAt:n,acceptedAt:r,revokedAt:s,state:i,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function qe(e){return{id:String(e.id),organizationId:String(e.organization_id),membershipId:String(e.membership_id),effect:String(e.effect),capability:String(e.capability),scope:Ut(e),source:String(e.source??"manual"),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function _e(e){return{type:e.type,id:e.id??null}}function Qs(e){return Array.from({length:e},()=>"?").join(", ")}function m(e,t,r){return e.run(t,r)}class hr{path;database;nowFn;idFn;constructor(e={}){this.path=e.path??Or(e.cwd??process.cwd(),"control-plane.sqlite"),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID());let t=this.path===":memory:";if(!t){js(gr(this.path),{recursive:!0,mode:448});try{Ct(gr(this.path),448)}catch{}}if(this.database=new $s(this.path,{create:!0,strict:!0}),this.database.run("PRAGMA foreign_keys = ON"),this.database.run(`PRAGMA busy_timeout = ${Math.max(100,e.busyTimeoutMs??5000)}`),!t)this.database.run("PRAGMA journal_mode = WAL"),this.database.run("PRAGMA synchronous = NORMAL");if(this.migrate(),!t)this.secureDatabaseFiles()}now(){return this.nowFn().toISOString()}secureDatabaseFiles(){for(let e of[this.path,`${this.path}-wal`,`${this.path}-shm`]){if(!Cr(e))continue;try{Ct(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{Ct(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>B)throw new ke(t,B);if(t===B)return;let r;if(t>0&&this.path!==":memory:")r=`${this.path}.v${t}.${Date.now()}.bak`,this.backupTo(r);try{if(this.database.transaction(()=>{for(let n of lt){if(n.version<=t)continue;this.database.run(n.sql),m(this.database,"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",[n.version,n.name,this.now()]),this.database.run(`PRAGMA user_version = ${n.version}`)}}).exclusive(),r)this.setSetting("storage.last_backup",{path:r,createdAt:this.now(),reason:"pre-migration"})}catch(s){let n=r?` Restore from ${r}.`:"";throw Error(`Control-plane migration from schema ${t} failed.${n} ${s instanceof Error?s.message:String(s)}`)}}close(){if(this.path!==":memory:")this.secureDatabaseFiles();this.database.close()}transaction(e){return this.database.transaction(e).immediate()}createProject(e){let t=e.id??this.idFn(),r=this.now();return m(this.database,"INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t,e.slug,e.name,e.description??null,e.organizationId??null,e.desiredConfigHash??null,r,r]),this.getProject(t)}getProject(e){let t=this.database.query("SELECT * FROM projects WHERE id = ?").get(e);return t?Pe(t):void 0}getProjectBySlug(e){let t=this.database.query("SELECT * FROM projects WHERE slug = ?").get(e);return t?Pe(t):void 0}listProjects(){return this.database.query("SELECT * FROM projects ORDER BY name COLLATE NOCASE, id").all().map(Pe)}updateProject(e,t,r){let s=this.getProject(e);if(!s||s.version!==t)throw new q("Project",e,t);if(m(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
|
|
1480
|
+
WHERE id = ? AND version = ?`,[r.name??s.name,r.description===null?null:r.description??s.description??null,r.organizationId===null?null:r.organizationId??s.organizationId??null,r.desiredConfigHash===null?null:r.desiredConfigHash??s.desiredConfigHash??null,this.now(),e,t]).changes!==1)throw new q("Project",e,t);return this.getProject(e)}createEnvironment(e){let t=e.id??this.idFn(),r=this.now();return m(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, created_at, updated_at)
|
|
1481
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,U(e.desiredState??{}),U(e.discoveredState??{}),r,r]),He(this.database.query("SELECT * FROM environments WHERE id = ?").get(t))}listEnvironments(e){return this.database.query("SELECT * FROM environments WHERE project_id = ? ORDER BY name COLLATE NOCASE, id").all(e).map(He)}getEnvironmentBySlug(e,t){let r=this.database.query("SELECT * FROM environments WHERE project_id = ? AND slug = ?").get(e,t);return r?He(r):void 0}createResource(e){let t=e.id??this.idFn(),r=this.now();return m(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, created_at, updated_at)
|
|
1482
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.environmentId??null,e.kind,e.slug,e.name,e.provider??null,e.providerId??null,U(e.desiredState??{}),U(e.discoveredState??{}),U(e.metadata??{}),r,r]),Ke(this.database.query("SELECT * FROM resources WHERE id = ?").get(t))}listResources(e,t){return(t?this.database.query("SELECT * FROM resources WHERE project_id = ? AND environment_id = ? ORDER BY kind, name COLLATE NOCASE").all(e,t):this.database.query("SELECT * FROM resources WHERE project_id = ? ORDER BY kind, name COLLATE NOCASE").all(e)).map(Ke)}getResource(e){let t=this.database.query("SELECT * FROM resources WHERE id = ?").get(e);return t?Ke(t):void 0}updateResource(e,t,r){let s=this.getResource(e);if(!s||s.version!==t)throw new q("Resource",e,t);if(m(this.database,`UPDATE resources SET name = ?, provider = ?, provider_id = ?, desired_state = ?, discovered_state = ?, metadata = ?,
|
|
1483
|
+
version = version + 1, updated_at = ? WHERE id = ? AND version = ?`,[r.name??s.name,r.provider===null?null:r.provider??s.provider??null,r.providerId===null?null:r.providerId??s.providerId??null,U(r.desiredState??s.desiredState),U(r.discoveredState??s.discoveredState),U(r.metadata??s.metadata),this.now(),e,t]).changes!==1)throw new q("Resource",e,t);return this.getResource(e)}createActor(e){let t=e.id??this.idFn(),r=this.now();return m(this.database,"INSERT INTO actors (id, kind, external_id, display_name, metadata, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[t,e.kind,e.externalId??null,e.displayName,U(e.metadata??{}),r,r]),xe(this.database.query("SELECT * FROM actors WHERE id = ?").get(t))}getActorByExternalId(e,t){let r=this.database.query("SELECT * FROM actors WHERE kind = ? AND external_id = ?").get(e,t);return r?xe(r):void 0}getActor(e){let t=this.database.query("SELECT * FROM actors WHERE id = ?").get(e);return t?xe(t):void 0}createOrganization(e){let t=e.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/.test(t))throw Error("Organization slugs must contain 3-64 lowercase letters, numbers, or dashes");let r=e.name.trim();if(!r||r.length>100)throw Error("Organization names must contain 1-100 characters");let s=e.id??this.idFn(),n=this.now();return m(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[s,t,r,n,n]),this.getOrganization(s)}getOrganization(e){let t=this.database.query("SELECT * FROM organizations WHERE id = ?").get(e);return t?Be(t):void 0}getOrganizationBySlug(e){let t=this.database.query("SELECT * FROM organizations WHERE slug = ?").get(e.trim().toLowerCase());return t?Be(t):void 0}listOrganizations(e){return(e?this.database.query(`SELECT organizations.* FROM organizations JOIN organization_memberships ON organization_memberships.organization_id = organizations.id
|
|
1484
|
+
WHERE organization_memberships.actor_id = ? AND organization_memberships.status = 'active' ORDER BY organizations.name COLLATE NOCASE`).all(e):this.database.query("SELECT * FROM organizations ORDER BY name COLLATE NOCASE").all()).map(Be)}normalizeAuthorizationScope(e,t={type:"organization"}){if(t.type==="organization"){if(t.id&&t.id!==e)throw Error("Organization scope does not match the requested organization");return{type:"organization"}}if(!t.id)throw Error(`${t.type} scopes require an ID`);if(!this.resolveAuthorizationTarget(e,t))throw Error("Authorization scope was not found in this organization");return{type:t.type,id:t.id}}resolveAuthorizationTarget(e,t){if(!this.getOrganization(e))return;if(t.type==="organization")return{organizationId:e};if(!t.id)return;if(t.type==="project"){let s=this.database.query("SELECT id FROM projects WHERE id = ? AND organization_id = ?").get(t.id,e);return s?{organizationId:e,projectId:String(s.id)}:void 0}if(t.type==="environment"){let s=this.database.query("SELECT environments.id, environments.project_id FROM environments JOIN projects ON projects.id = environments.project_id WHERE environments.id = ? AND projects.organization_id = ?").get(t.id,e);return s?{organizationId:e,projectId:String(s.project_id),environmentId:String(s.id)}:void 0}let r=this.database.query(`SELECT resources.id, resources.project_id, resources.environment_id FROM resources
|
|
1485
|
+
JOIN projects ON projects.id = resources.project_id WHERE resources.id = ? AND projects.organization_id = ?`).get(t.id,e);return r?{organizationId:e,projectId:String(r.project_id),environmentId:O(r.environment_id),resourceId:String(r.id)}:void 0}createMembership(e){if(!this.getActor(e.actorId))throw Error("Membership actor was not found");let t=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&t.type!=="organization")throw Error("Owners must be scoped to the organization");let r=e.id??this.idFn(),s=this.now();m(this.database,`INSERT INTO organization_memberships (id, organization_id, actor_id, role_template, scope_type, scope_id, source, created_at, updated_at)
|
|
1486
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",s,s]);let n=this.getMembership(r);return this.appendEvent({organizationId:e.organizationId,actorId:e.performedByActorId,type:"organization.membership.created",payload:{membershipId:r,actorId:e.actorId,roleTemplate:e.roleTemplate,scope:_e(t)}}),n}getMembership(e){let t=this.database.query("SELECT * FROM organization_memberships WHERE id = ?").get(e);return t?$e(t):void 0}getMembershipForActor(e,t){let r=this.database.query("SELECT * FROM organization_memberships WHERE organization_id = ? AND actor_id = ?").get(e,t);return r?$e(r):void 0}listMemberships(e,t={}){let r=t.includeRevoked?"":"AND status = 'active'";return this.database.query(`SELECT * FROM organization_memberships WHERE organization_id = ? ${r} ORDER BY created_at, id`).all(e).map($e)}updateMembership(e){let t=this.getMembership(e.id);if(!t)throw Error("Membership was not found");let r=this.normalizeAuthorizationScope(t.organizationId,e.scope??t.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");if(t.roleTemplate==="owner"&&t.status==="active"&&(e.roleTemplate!=="owner"||r.type!=="organization"))this.assertAnotherOwner(t);return m(this.database,"UPDATE organization_memberships SET role_template = ?, scope_type = ?, scope_id = ?, session_version = session_version + 1, updated_at = ? WHERE id = ?",[e.roleTemplate,r.type,r.id??null,this.now(),t.id]),this.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"organization.membership.updated",payload:{membershipId:t.id,from:{roleTemplate:t.roleTemplate,scope:_e(t.scope)},to:{roleTemplate:e.roleTemplate,scope:_e(r)}}}),this.getMembership(t.id)}revokeMembership(e,t){let r=this.getMembership(e);if(!r)throw Error("Membership was not found");if(r.status==="revoked")return r;if(r.roleTemplate==="owner")this.assertAnotherOwner(r);return m(this.database,"UPDATE organization_memberships SET status = 'revoked', session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),e]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.membership.revoked",payload:{membershipId:e}}),this.getMembership(e)}touchMembership(e){let t=this.now();m(this.database,"UPDATE organization_memberships SET last_active_at = ?, updated_at = ? WHERE id = ? AND status = ?",[t,t,e,"active"]);let r=this.getMembership(e);if(!r)throw Error("Membership was not found");return r}assertAnotherOwner(e){if(Number(this.database.query("SELECT COUNT(*) AS count FROM organization_memberships WHERE organization_id = ? AND status = ? AND role_template = 'owner'").get(e.organizationId,"active")?.count??0)<=1)throw Error("Cannot remove or demote the last organization owner")}createInvitation(e){let t=e.email.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid invitation email is required");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");let s=Ms(32).toString("base64url"),n=Fe("sha256").update(s).digest("hex"),i=e.id??this.idFn(),E=this.now(),a=new Date(this.nowFn().getTime()+Math.min(2592000000,Math.max(60000,e.expiresInMs??604800000))).toISOString();return m(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, expires_at, created_at, updated_at)
|
|
1487
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e.organizationId,t,e.roleTemplate,r.type,r.id??null,n,e.invitedByActorId??null,a,E,E]),this.appendEvent({organizationId:e.organizationId,actorId:e.invitedByActorId,type:"organization.invitation.created",payload:{invitationId:i,email:t,roleTemplate:e.roleTemplate,scope:_e(r),expiresAt:a}}),{invitation:this.getInvitation(i),token:s}}getInvitation(e){let t=this.database.query("SELECT * FROM organization_invitations WHERE id = ?").get(e);return t?Ne(t,this.now()):void 0}listInvitations(e){return this.database.query("SELECT * FROM organization_invitations WHERE organization_id = ? ORDER BY created_at DESC").all(e).map((t)=>Ne(t,this.now()))}inspectInvitationToken(e){let t=Fe("sha256").update(e).digest("hex"),r=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(t);return r?Ne(r,this.now()):void 0}acceptInvitation(e,t){let r=Fe("sha256").update(e).digest("hex");return this.transaction(()=>{let s=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(r);if(!s)throw Error("Invitation is invalid");let n=Ne(s,this.now());if(n.state!=="pending")throw Error(`Invitation is ${n.state}`);if(!this.getActor(t))throw Error("Invitation actor was not found");if(m(this.database,"UPDATE organization_invitations SET accepted_by_actor_id = ?, accepted_at = ?, updated_at = ? WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?",[t,this.now(),this.now(),n.id,this.now()]).changes!==1)throw Error("Invitation is no longer available");let E=this.getMembershipForActor(n.organizationId,t),a=E??this.createMembership({organizationId:n.organizationId,actorId:t,roleTemplate:n.roleTemplate,scope:n.scope,source:"invitation"});if(E&&n.roleTemplate==="owner"&&E.roleTemplate!=="owner")a=this.updateMembership({id:E.id,roleTemplate:"owner",scope:{type:"organization"},actorId:t});else if(E)for(let d of De(n.roleTemplate))this.upsertGrant({organizationId:n.organizationId,membershipId:E.id,effect:"allow",capability:d,scope:n.scope,source:"invitation"});return this.appendEvent({organizationId:n.organizationId,actorId:t,type:"organization.invitation.accepted",payload:{invitationId:n.id,membershipId:a.id}}),{invitation:this.getInvitation(n.id),membership:this.getMembership(a.id)}})}revokeInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.acceptedAt)throw Error("Accepted invitations cannot be revoked");if(!r.revokedAt)m(this.database,"UPDATE organization_invitations SET revoked_at = ?, updated_at = ? WHERE id = ?",[this.now(),this.now(),e]);return this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.invitation.revoked",payload:{invitationId:e}}),this.getInvitation(e)}reissueInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.state==="accepted")throw Error("Accepted invitations cannot be reissued");return this.revokeInvitation(e,t),this.createInvitation({organizationId:r.organizationId,email:r.email,roleTemplate:r.roleTemplate,scope:r.scope,invitedByActorId:t})}upsertGrant(e){if(!te.includes(e.capability))throw Error("Unknown authorization capability");let t=this.getMembership(e.membershipId);if(!t||t.organizationId!==e.organizationId)throw Error("Grant membership was not found in this organization");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope),s=this.now(),n=this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? AND effect = ? AND capability = ? AND scope_type = ? AND scope_id IS ?").get(e.membershipId,e.effect,e.capability,r.type,r.id??null);if(n)return qe(n);let i=e.id??this.idFn();return m(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
|
|
1488
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e.organizationId,e.membershipId,e.effect,e.capability,r.type,r.id??null,e.source??"manual",s,s]),m(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[s,e.membershipId]),this.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"organization.grant.created",payload:{grantId:i,membershipId:e.membershipId,effect:e.effect,capability:e.capability,scope:_e(r)}}),this.getGrant(i)}getGrant(e){let t=this.database.query("SELECT * FROM authorization_grants WHERE id = ?").get(e);return t?qe(t):void 0}listGrants(e){return this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? ORDER BY effect DESC, capability, scope_type, scope_id").all(e).map(qe)}removeGrant(e,t){let r=this.getGrant(e);if(!r)return!1;let s=m(this.database,"DELETE FROM authorization_grants WHERE id = ?",[e]).changes===1;if(s)m(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),r.membershipId]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.grant.removed",payload:{grantId:e,membershipId:r.membershipId}});return s}createOperation(e){if(e.idempotencyKey){let n=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(n)return Q(n)}let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),s=this.now();try{return this.transaction(()=>{return m(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key, input, output, priority, created_at, updated_at)
|
|
1489
|
+
VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, '{}', ?, ?, ?)`,[t,e.projectId??null,e.environmentId??null,e.resourceId??null,e.actorId??null,e.kind,r,e.idempotencyKey??null,U(e.input??{}),e.priority??0,s,s]),this.appendEvent({projectId:e.projectId,operationId:t,resourceId:e.resourceId,actorId:e.actorId,correlationId:r,type:"operation.queued",payload:{kind:e.kind}}),this.getOperation(t)})}catch(n){if(e.idempotencyKey){let i=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(i)return Q(i)}throw n}}getOperation(e){let t=this.database.query("SELECT * FROM operations WHERE id = ?").get(e);return t?Q(t):void 0}listOperations(e={}){let t=[],r=[];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.state)t.push("state = ?"),r.push(e.state);if(e.kind)t.push("kind = ?"),r.push(e.kind);if(e.before)t.push("created_at < ?"),r.push(e.before);let s=Math.min(500,Math.max(1,e.limit??100));r.push(s);let n=t.length?`WHERE ${t.join(" AND ")}`:"";return this.database.query(`SELECT * FROM operations ${n} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...r).map(Q)}claimNextOperation(e,t=60000,r){let s=this.now(),n=new Date(this.nowFn().getTime()+t).toISOString();return this.transaction(()=>{let i=r?.length?`AND kind IN (${Qs(r.length)})`:"",E=r?[...r]:[],a=this.database.query(`SELECT * FROM operations WHERE state = 'queued' ${i} ORDER BY priority DESC, created_at ASC, id ASC LIMIT 1`).get(...E);if(!a)return;let d=Q(a);if(m(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
|
|
1490
|
+
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[e,n,s,s,d.id,d.version]).changes!==1)return;return this.appendEvent({projectId:d.projectId,operationId:d.id,resourceId:d.resourceId,actorId:d.actorId,correlationId:d.correlationId,type:"operation.running",payload:{attempt:d.attempt+1,workerId:e}}),this.getOperation(d.id)})}claimOperation(e,t,r=60000){let s=this.now(),n=new Date(this.nowFn().getTime()+r).toISOString();return this.transaction(()=>{let i=this.getOperation(e);if(!i||i.state!=="queued")return;if(m(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
|
|
1491
|
+
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[t,n,s,s,i.id,i.version]).changes!==1)return;return this.appendEvent({projectId:i.projectId,operationId:i.id,resourceId:i.resourceId,actorId:i.actorId,correlationId:i.correlationId,type:"operation.running",payload:{attempt:i.attempt+1,workerId:t}}),this.getOperation(i.id)})}transitionOperation(e,t){return this.transaction(()=>{let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);let s=t.expectedVersion??r.version;if(r.version!==s)throw new q("Operation",e,s);if(!zs[r.state].includes(t.to))throw new ut(r.state,t.to);let n=this.now(),i=Ys.includes(t.to),E=t.to==="queued";if(m(this.database,`UPDATE operations SET state = ?, output = ?, error = ?, lease_owner = ?, lease_expires_at = ?,
|
|
1492
|
+
finished_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?`,[t.to,U(t.output??r.output),gt(t.error)??null,E||i?null:t.leaseOwner??r.leaseOwner??null,E||i?null:t.leaseExpiresAt??r.leaseExpiresAt??null,i?n:null,n,e,s]).changes!==1)throw new q("Operation",e,s);return this.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:r.actorId,correlationId:r.correlationId,type:`operation.${t.to}`,level:t.to==="failed"?"error":"info",payload:{from:r.state,to:t.to,error:gt(t.error)??null}}),this.getOperation(e)})}requestCancellation(e){let t=this.now();m(this.database,"UPDATE operations SET cancel_requested_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND state IN ('queued', 'running')",[t,t,e]);let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);return r}reconcileOrphanedOperations(e={}){let t=(e.now??this.nowFn()).toISOString(),r=e.policy??"fail",s=this.database.query("SELECT * FROM operations WHERE state = 'running' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").all(t).map(Q),n=0,i=0;for(let E of s)if(r==="requeue")this.transitionOperation(E.id,{to:"queued",expectedVersion:E.version,error:"Worker lease expired; operation requeued after restart."}),n++;else this.transitionOperation(E.id,{to:"failed",expectedVersion:E.version,error:"Worker lease expired or dashboard restarted before completion."}),i++;return{requeued:n,failed:i}}appendEvent(e){let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),s=e.organizationId??(e.projectId?O(this.database.query("SELECT organization_id FROM projects WHERE id = ?").get(e.projectId)?.organization_id):void 0);return m(this.database,`INSERT INTO events (id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
|
|
1493
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,s??null,e.projectId??null,e.operationId??null,e.resourceId??null,e.actorId??null,r,e.type,e.level??"info",U(e.payload??{}),this.now()]),Rt(this.database.query("SELECT * FROM events WHERE id = ?").get(t))}listEvents(e={}){let t=[],r=[];if(e.organizationId)t.push("organization_id = ?"),r.push(e.organizationId);if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.operationId)t.push("operation_id = ?"),r.push(e.operationId);if(e.resourceId)t.push("resource_id = ?"),r.push(e.resourceId);if(e.correlationId)t.push("correlation_id = ?"),r.push(e.correlationId);if(e.afterSequence!==void 0)t.push("sequence > ?"),r.push(e.afterSequence);let s=Math.min(1000,Math.max(1,e.limit??200));r.push(s);let n=t.length?`WHERE ${t.join(" AND ")}`:"";return this.database.query(`SELECT * FROM events ${n} ORDER BY sequence ASC LIMIT ?`).all(...r).map(Rt)}setSetting(e,t){m(this.database,`INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)
|
|
1494
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,[e,U(t),this.now()])}getSetting(e){let t=this.database.query("SELECT value FROM settings WHERE key = ?").get(e);return t?P(t.value):void 0}upsertTag(e,t,r="#5a8be0"){let s=t.trim().toLowerCase().replace(/\s+/g,"-");if(!/^[a-z0-9][a-z0-9-]{0,31}$/.test(s))throw Error("Tag names must contain 1-32 letters, numbers, or dashes");if(!/^#[0-9a-f]{6}$/i.test(r))throw Error("Tag colors must be six-digit hex colors");let n=this.now(),i=this.database.query("SELECT * FROM tags WHERE project_id = ? AND normalized_name = ?").get(e,s);if(i)return m(this.database,"UPDATE tags SET name = ?, color = ?, updated_at = ? WHERE id = ?",[t.trim(),r.toLowerCase(),n,String(i.id)]),ce(this.database.query("SELECT * FROM tags WHERE id = ?").get(String(i.id)));let E=this.idFn();return m(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[E,e,t.trim(),s,r.toLowerCase(),n,n]),ce(this.database.query("SELECT * FROM tags WHERE id = ?").get(E))}listTags(e){return this.database.query("SELECT * FROM tags WHERE project_id = ? ORDER BY normalized_name").all(e).map(ce)}assignTag(e,t){if(!this.database.query("SELECT tags.id FROM tags JOIN resources ON resources.project_id = tags.project_id WHERE tags.id = ? AND resources.id = ?").get(t,e))throw Error("The tag and resource must belong to the same project");m(this.database,"INSERT OR IGNORE INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[e,t,this.now()])}removeTag(e,t){m(this.database,"DELETE FROM resource_tags WHERE resource_id = ? AND tag_id = ?",[e,t])}listResourceTags(e){return this.database.query(`SELECT resource_tags.resource_id, tags.* FROM resource_tags JOIN tags ON tags.id = resource_tags.tag_id
|
|
1495
|
+
WHERE tags.project_id = ? ORDER BY tags.normalized_name`).all(e).map((r)=>({resourceId:String(r.resource_id),tag:ce(r)}))}saveFilter(e,t,r,s){let n=t.trim();if(!n||n.length>64)throw Error("Saved filter names must contain 1-64 characters");if(!r||r.length>160||/^[a-z][a-z0-9+.-]*:|^\/\//i.test(r))throw Error("Saved filter routes must be local route IDs or paths");let i=U(s);if(i.length>8192)throw Error("Saved filter queries must be smaller than 8 KB");let E=this.database.query("SELECT * FROM saved_filters WHERE actor_key = ? AND name = ?").get(e,n),a=this.now();if(E)return m(this.database,"UPDATE saved_filters SET route_id = ?, query = ?, updated_at = ? WHERE id = ?",[r,i,a,String(E.id)]),Me(this.database.query("SELECT * FROM saved_filters WHERE id = ?").get(String(E.id)));let d=this.idFn();return m(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[d,e,n,r,i,a,a]),Me(this.database.query("SELECT * FROM saved_filters WHERE id = ?").get(d))}listSavedFilters(e){return this.database.query("SELECT * FROM saved_filters WHERE actor_key = ? ORDER BY updated_at DESC, name").all(e).map(Me)}deleteSavedFilter(e,t){return m(this.database,"DELETE FROM saved_filters WHERE actor_key = ? AND id = ?",[e,t]).changes===1}recordNavigation(e,t,r){let s=this.now();return m(this.database,`INSERT INTO navigation_items (actor_key, entity_type, entity_id, last_visited_at) VALUES (?, ?, ?, ?)
|
|
1496
|
+
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET last_visited_at = excluded.last_visited_at, visit_count = visit_count + 1`,[e,t,r,s]),je(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}setFavorite(e,t,r,s){let n=this.now();return m(this.database,`INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at) VALUES (?, ?, ?, ?, ?)
|
|
1497
|
+
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET favorite = excluded.favorite`,[e,t,r,s?1:0,n]),je(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}listNavigation(e,t={}){let r=t.favoritesOnly?"AND favorite = 1":"",s=Math.min(100,Math.max(1,t.limit??20));return this.database.query(`SELECT * FROM navigation_items WHERE actor_key = ? ${r} ORDER BY favorite DESC, last_visited_at DESC LIMIT ?`).all(e,s).map(je)}compact(e={}){let t=new Date(this.nowFn().getTime()-(e.eventRetentionDays??90)*86400000).toISOString(),r=new Date(this.nowFn().getTime()-(e.operationRetentionDays??365)*86400000).toISOString(),s=this.transaction(()=>{let n=m(this.database,"DELETE FROM events WHERE created_at < ?",[t]).changes,i=m(this.database,"DELETE FROM operations WHERE created_at < ? AND state IN ('succeeded', 'failed', 'cancelled', 'timed_out')",[r]).changes;return{events:n,operations:i}});if(e.vacuum!==!1)this.database.run("VACUUM");return{deletedEvents:s.events,deletedOperations:s.operations,vacuumed:e.vacuum!==!1}}createBackup(e="manual"){if(this.path===":memory:")throw Error("Cannot create a filesystem backup for an in-memory control plane");let t=`${this.path}.${Date.now()}.bak`;return this.backupTo(t),this.setSetting("storage.last_backup",{path:t,createdAt:this.now(),reason:e}),t}integrityCheck(){let e=this.database.query("PRAGMA integrity_check").all();return e.length===1&&Object.values(e[0])[0]==="ok"?"ok":"corrupt"}health(){let e=Object.fromEntries(["queued","running","succeeded","failed","cancelled","timed_out"].map((n)=>[n,0]));for(let n of this.database.query("SELECT state, COUNT(*) AS count FROM operations GROUP BY state").all())e[String(n.state)]=Number(n.count);let t=this.database.query("PRAGMA journal_mode").get(),r=this.getSetting("storage.last_backup"),s=r&&!Array.isArray(r)&&typeof r==="object"&&typeof r.createdAt==="string"?r.createdAt:void 0;return{path:this.path,schemaVersion:Number(this.database.query("PRAGMA user_version").get()?.user_version??0),supportedSchemaVersion:B,integrity:this.integrityCheck(),journalMode:String(t?.journal_mode??"unknown"),databaseBytes:this.path!==":memory:"&&Cr(this.path)?Bs(this.path).size:this.database.serialize().byteLength,lastBackupAt:s,operations:e,pendingRetryableOperations:e.queued+e.failed+e.timed_out}}exportSnapshot(){let e={};for(let t of this.database.query("SELECT key, value FROM settings ORDER BY key").all())e[String(t.key)]=P(t.value);return{format:"ts-cloud-control-plane",schemaVersion:B,exportedAt:this.now(),organizations:this.database.query("SELECT * FROM organizations ORDER BY id").all().map(Be),memberships:this.database.query("SELECT * FROM organization_memberships ORDER BY id").all().map($e),invitations:this.database.query("SELECT * FROM organization_invitations ORDER BY id").all().map((t)=>({...Ne(t,this.now()),tokenHash:String(t.token_hash)})),grants:this.database.query("SELECT * FROM authorization_grants ORDER BY id").all().map(qe),projects:this.database.query("SELECT * FROM projects ORDER BY id").all().map(Pe),environments:this.database.query("SELECT * FROM environments ORDER BY id").all().map(He),resources:this.database.query("SELECT * FROM resources ORDER BY id").all().map(Ke),actors:this.database.query("SELECT * FROM actors ORDER BY id").all().map(xe),operations:this.database.query("SELECT * FROM operations ORDER BY id").all().map(Q),events:this.database.query("SELECT * FROM events ORDER BY sequence").all().map(Rt),settings:e,tags:this.database.query("SELECT * FROM tags ORDER BY id").all().map(ce),resourceTags:this.database.query("SELECT * FROM resource_tags ORDER BY resource_id, tag_id").all().map((t)=>({resourceId:String(t.resource_id),tagId:String(t.tag_id),createdAt:String(t.created_at)})),savedFilters:this.database.query("SELECT * FROM saved_filters ORDER BY id").all().map(Me),navigationItems:this.database.query("SELECT * FROM navigation_items ORDER BY actor_key, entity_type, entity_id").all().map(je)}}importSnapshot(e,t={}){if(e.format!=="ts-cloud-control-plane")throw Error("Unsupported control-plane snapshot format");if(e.schemaVersion>B)throw new ke(e.schemaVersion,B);this.transaction(()=>{if((Number(this.database.query("SELECT COUNT(*) AS count FROM projects").get()?.count??0)>0||Number(this.database.query("SELECT COUNT(*) AS count FROM operations").get()?.count??0)>0)&&!t.replace)throw Error("Control plane is not empty; pass replace: true to import this snapshot");if(t.replace)this.database.run("DELETE FROM authorization_grants"),this.database.run("DELETE FROM organization_invitations"),this.database.run("DELETE FROM organization_memberships"),this.database.run("DELETE FROM resource_tags"),this.database.run("DELETE FROM tags"),this.database.run("DELETE FROM saved_filters"),this.database.run("DELETE FROM navigation_items"),this.database.run("DELETE FROM events"),this.database.run("DELETE FROM operations"),this.database.run("DELETE FROM resources"),this.database.run("DELETE FROM environments"),this.database.run("DELETE FROM projects"),this.database.run("DELETE FROM actors"),this.database.run("DELETE FROM organizations"),this.database.run("DELETE FROM settings");for(let s of e.organizations??[])m(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[s.id,s.slug,s.name,s.createdAt,s.updatedAt]);for(let s of e.projects)m(this.database,`INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, version, created_at, updated_at)
|
|
1498
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.slug,s.name,s.description??null,s.organizationId??null,s.desiredConfigHash??null,s.version,s.createdAt,s.updatedAt]);for(let s of e.environments)m(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, version, created_at, updated_at)
|
|
1499
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.projectId,s.slug,s.name,s.kind,s.region??null,U(s.desiredState),U(s.discoveredState),s.version,s.createdAt,s.updatedAt]);for(let s of e.resources)m(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, version, created_at, updated_at)
|
|
1500
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.projectId,s.environmentId??null,s.kind,s.slug,s.name,s.provider??null,s.providerId??null,U(s.desiredState),U(s.discoveredState),U(s.metadata),s.version,s.createdAt,s.updatedAt]);for(let s of e.actors)m(this.database,`INSERT INTO actors (id, kind, external_id, display_name, metadata, disabled_at, version, created_at, updated_at)
|
|
1501
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.kind,s.externalId??null,s.displayName,U(s.metadata),s.disabledAt??null,s.version,s.createdAt,s.updatedAt]);for(let s of e.memberships??[])m(this.database,`INSERT INTO organization_memberships (id, organization_id, actor_id, role_template, scope_type, scope_id, status, session_version, last_active_at, source, created_at, updated_at)
|
|
1502
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.organizationId,s.actorId,s.roleTemplate,s.scope.type,s.scope.id??null,s.status,s.sessionVersion,s.lastActiveAt??null,s.source??"manual",s.createdAt,s.updatedAt]);for(let s of e.invitations??[]){let n=s.tokenHash??Fe("sha256").update(`revoked:${s.id}:${this.idFn()}`).digest("hex");m(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, accepted_by_actor_id, expires_at, accepted_at, revoked_at, created_at, updated_at)
|
|
1503
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.organizationId,s.email,s.roleTemplate,s.scope.type,s.scope.id??null,n,s.invitedByActorId??null,s.acceptedByActorId??null,s.expiresAt,s.acceptedAt??null,s.tokenHash?s.revokedAt??null:s.revokedAt??this.now(),s.createdAt,s.updatedAt])}for(let s of e.grants??[])m(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
|
|
1504
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.organizationId,s.membershipId,s.effect,s.capability,s.scope.type,s.scope.id??null,s.source??"manual",s.createdAt,s.updatedAt]);for(let s of e.operations)m(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key,
|
|
1505
1505
|
input, output, error, attempt, priority, lease_owner, lease_expires_at, cancel_requested_at, started_at, finished_at, version, created_at, updated_at)
|
|
1506
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
1507
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.sequence,n.id,n.organizationId??null,n.projectId??null,n.operationId??null,n.resourceId??null,n.actorId??null,n.correlationId,n.type,n.level,v(n.payload),n.createdAt]);for(let[n,i]of Object.entries(e.settings))g(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[n,v(i),this.now()]);for(let n of e.tags??[])g(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n.id,n.projectId,n.name,n.normalizedName,n.color,n.createdAt,n.updatedAt]);for(let n of e.resourceTags??[])g(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[n.resourceId,n.tagId,n.createdAt]);for(let n of e.savedFilters??[])g(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n.id,n.actorKey,n.name,n.routeId,v(n.query),n.createdAt,n.updatedAt]);for(let n of e.navigationItems??[])g(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[n.actorKey,n.entityType,n.entityId,n.favorite?1:0,n.lastVisitedAt,n.visitCount])})}}var Wn=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),Jn=new Set(["sha","commit","commitsha","release","releaseid"]);function br(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[n,i]of Object.entries(e)){if(!t.has(n.toLowerCase()))continue;if(typeof i==="string")r.push(i);else if(Array.isArray(i))r.push(...i.filter((o)=>typeof o==="string"))}return r}function St(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function bt(e,t,r){let n=St(e),i=St(t),o=St(r);if(!n)return 0;if(i===n)return 1000;if(i.startsWith(n))return 800-Math.min(100,i.length-n.length);if(i.includes(n))return 650-Math.min(100,i.indexOf(n));let s=n.split(/\s+/).filter(Boolean);if(s.every((d)=>o.includes(d)))return 400+s.length*10;let a=0;for(let d of n){if(a=o.indexOf(d,a),a<0)return 0;a++}return Math.max(1,180-Math.floor(o.length/20))}function Zn(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function ei(e,t){let r=e.getProject(t.projectId);if(!r)return[];let n=e.listEnvironments(r.id),i=new Map(n.map((l)=>[l.id,l])),o=e.listResourceTags(r.id),s=new Map;for(let l of o){let u=s.get(l.resourceId)??[];u.push({id:l.tag.id,name:l.tag.name,color:l.tag.color}),s.set(l.resourceId,u)}let a=[],d=t.allowedResourceSlugs!==void 0;if(!d){a.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let l of n)a.push({type:"environment",id:l.id,title:l.name,subtitle:`${r.name} · ${l.kind}`,href:`/?env=${encodeURIComponent(l.slug)}`,environment:l.slug,tags:[],score:0})}let c=e.listResources(r.id).filter((l)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(l.slug));for(let l of c){let u=l.environmentId?i.get(l.environmentId):void 0,m=s.get(l.id)??[],E=br(l.desiredState,Wn),T=[l.name,l.slug,l.kind,l.provider,l.providerId,u?.slug,...E,...m.map((h)=>h.name)].filter(Boolean).join(" "),_=Zn(l,u?.slug??n[0]?.slug??"");a.push({type:_.type,id:l.id,title:l.name,subtitle:[l.kind,...E.slice(0,2)].join(" · "),href:_.href,environment:u?.slug,provider:l.provider,tags:m,score:bt(t.query,l.name,T)})}if(!d)for(let l of e.listOperations({projectId:r.id,limit:500})){let u=l.environmentId?i.get(l.environmentId):void 0,m=br(l.input,Jn),E=l.kind.includes("deploy"),T=m[0]??l.kind,_=[l.kind,l.id,l.correlationId,l.state,...m].join(" ");a.push({type:E?"deployment":"operation",id:l.id,title:T,subtitle:`${l.kind} · ${l.state}`,href:`/server/activity?env=${encodeURIComponent(u?.slug??n[0]?.slug??"")}&operation=${encodeURIComponent(l.id)}`,environment:u?.slug,status:l.state,tags:[],score:bt(t.query,T,_)})}for(let l of a)if(l.score===0)l.score=bt(t.query,l.title,`${l.title} ${l.subtitle} ${l.environment??""} ${l.provider??""}`);let p={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return a.filter((l)=>l.score>0).sort((l,u)=>u.score-l.score||p[l.type]-p[u.type]||l.title.localeCompare(u.title)||l.id.localeCompare(u.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}var Te=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},F=(e)=>typeof e==="string"&&e!==""?e:void 0,Ke=(e)=>Number(e)===1,Rr=(e)=>e==null?void 0:Number(e);function Cr(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:F(e.project_id),environmentId:F(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:Rr(e.soft_limit_cents),hardLimitCents:Rr(e.hard_limit_cents),thresholds:Te(e.thresholds),meters:Te(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:Ke(e.dry_run),enabled:Ke(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Rt(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:F(e.project_id),environmentId:F(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:Te(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:Ke(e.simulated),appliedAt:F(e.applied_at),releasedAt:F(e.released_at),error:F(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ar(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:F(e.project_id),environmentId:F(e.environment_id),signal:String(e.signal),direction:String(e.direction),observed:Number(e.observed),expected:Number(e.expected),score:Number(e.score),deltaPercent:Number(e.delta_percent),severity:String(e.severity),bucketStart:String(e.bucket_start),evidence:Te(e.evidence),acknowledgedAt:F(e.acknowledged_at),createdAt:String(e.created_at)}}function ri(e){return{organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),provider:String(e.provider),region:String(e.region),meter:String(e.meter),bucketStart:String(e.bucket_start),quantity:Number(e.quantity),costCents:Number(e.cost_cents),sampleCount:Number(e.sample_count),updatedAt:String(e.updated_at)}}function G(e,t,r){return[e,t??"",r??""].join("/")}var ni=[{atPercent:50,actions:["notify"]},{atPercent:80,actions:["notify"]},{atPercent:100,actions:["notify"],onProjection:!0},{atPercent:100,actions:["notify","block_builds","block_deployments"]},{atPercent:115,actions:["notify","block_builds","block_deployments","throttle_requests"]}];class ii{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}get priceBook(){return this.options.priceBook??ur}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}createBudget(e){let t=e.name.trim();if(!t)throw Error("Budgets require a name.");if(e.softLimitCents==null&&e.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(e.softLimitCents!=null&&e.hardLimitCents!=null&&e.softLimitCents>e.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");let r=e.timezone??"UTC";if(!Ue(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...ni]).filter((s)=>Number.isFinite(s.atPercent)&&s.atPercent>=0);if(e.environmentId&&!e.projectId)throw Error("An environment-scoped budget must also name its project.");let i=crypto.randomUUID(),o=this.now();return this.controlPlane.database.run("INSERT INTO spend_budgets (id,organization_id,project_id,environment_id,name,period,timezone,currency,soft_limit_cents,hard_limit_cents,thresholds,meters,grace_seconds,hysteresis_percent,dry_run,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[i,e.organizationId,e.projectId??null,e.environmentId??null,t,e.period,r,e.currency??"USD",e.softLimitCents??null,e.hardLimitCents??null,JSON.stringify(n),JSON.stringify(e.meters??[]),Math.max(0,Math.floor(e.graceSeconds??0)),Math.max(0,e.hysteresisPercent??5),e.dryRun?1:0,e.enabled===!1?0:1,o,o]),this.getBudget(i)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?Cr(t):void 0}listBudgets(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(e.enabledOnly)t.push("enabled = 1");return this.query(`SELECT * FROM spend_budgets WHERE ${t.join(" AND ")} ORDER BY created_at`,r).map(Cr)}budgetsForScope(e,t,r){return this.listBudgets({organizationId:e,enabledOnly:!0}).filter((n)=>{if(n.projectId&&n.projectId!==t)return!1;if(n.environmentId&&n.environmentId!==r)return!1;return!0}).sort((n,i)=>Number(!!n.projectId)-Number(!!i.projectId)||Number(!!n.environmentId)-Number(!!i.environmentId))}updateBudget(e,t,r){let n=this.getBudget(e);if(!n)throw Error("Budget was not found.");if(r!=null&&r!==n.version)throw Error(`Budget was modified concurrently (expected version ${r}, found ${n.version}).`);let i={...n,...t};if(i.softLimitCents==null&&i.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(i.softLimitCents!=null&&i.hardLimitCents!=null&&i.softLimitCents>i.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!Ue(t.timezone))throw Error(`Unknown timezone: ${t.timezone}`);return this.controlPlane.database.run("UPDATE spend_budgets SET name=?,period=?,timezone=?,currency=?,soft_limit_cents=?,hard_limit_cents=?,thresholds=?,meters=?,grace_seconds=?,hysteresis_percent=?,dry_run=?,enabled=?,version=version+1,updated_at=? WHERE id=?",[i.name,i.period,i.timezone,i.currency??"USD",i.softLimitCents??null,i.hardLimitCents??null,JSON.stringify(i.thresholds??[]),JSON.stringify(i.meters??[]),Math.max(0,Math.floor(i.graceSeconds??0)),Math.max(0,i.hysteresisPercent??5),i.dryRun?1:0,i.enabled===!1?0:1,this.now(),e]),this.getBudget(e)}deleteBudget(e){return this.controlPlane.database.run("DELETE FROM spend_budgets WHERE id = ?",[e]).changes>0}ingestUsage(e){let t={applied:0,duplicates:0,costCents:0,unpricedMeters:[]},r=new Set,n=this.now();return this.controlPlane.database.transaction((o)=>{for(let s of o){if(!(s.quantity>0)||!Number.isFinite(s.quantity))continue;let a=s.key??this.deltaFallbackKey(s);if(this.controlPlane.database.run("INSERT OR IGNORE INTO spend_usage_receipts (key,organization_id,bucket_start,created_at) VALUES (?,?,?,?)",[a,s.organizationId,ue(s.timestamp),n]).changes===0){t.duplicates++;continue}let c={projectId:s.projectId??"",environmentId:s.environmentId??"",resourceId:s.resourceId??"",provider:s.provider??"",region:s.region??""},p=this.periodQuantity(s),l=pt(this.priceBook,{meter:s.meter,quantity:s.quantity,provider:s.provider,region:s.region},p);if(l.unpriced)r.add(String(s.meter));this.controlPlane.database.run(`INSERT INTO spend_usage (organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start,quantity,cost_cents,sample_count,updated_at)
|
|
1506
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.projectId??null,s.environmentId??null,s.resourceId??null,s.actorId??null,s.kind,s.state,s.correlationId,s.idempotencyKey??null,U(s.input),U(s.output),gt(s.error)??null,s.attempt,s.priority,s.leaseOwner??null,s.leaseExpiresAt??null,s.cancelRequestedAt??null,s.startedAt??null,s.finishedAt??null,s.version,s.createdAt,s.updatedAt]);for(let s of e.events)m(this.database,`INSERT INTO events (sequence, id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
|
|
1507
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.sequence,s.id,s.organizationId??null,s.projectId??null,s.operationId??null,s.resourceId??null,s.actorId??null,s.correlationId,s.type,s.level,U(s.payload),s.createdAt]);for(let[s,n]of Object.entries(e.settings))m(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[s,U(n),this.now()]);for(let s of e.tags??[])m(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[s.id,s.projectId,s.name,s.normalizedName,s.color,s.createdAt,s.updatedAt]);for(let s of e.resourceTags??[])m(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[s.resourceId,s.tagId,s.createdAt]);for(let s of e.savedFilters??[])m(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[s.id,s.actorKey,s.name,s.routeId,U(s.query),s.createdAt,s.updatedAt]);for(let s of e.navigationItems??[])m(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[s.actorKey,s.entityType,s.entityId,s.favorite?1:0,s.lastVisitedAt,s.visitCount])})}}var Vs=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),Ws=new Set(["sha","commit","commitsha","release","releaseid"]);function fr(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[s,n]of Object.entries(e)){if(!t.has(s.toLowerCase()))continue;if(typeof n==="string")r.push(n);else if(Array.isArray(n))r.push(...n.filter((i)=>typeof i==="string"))}return r}function ht(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function ft(e,t,r){let s=ht(e),n=ht(t),i=ht(r);if(!s)return 0;if(n===s)return 1000;if(n.startsWith(s))return 800-Math.min(100,n.length-s.length);if(n.includes(s))return 650-Math.min(100,n.indexOf(s));let E=s.split(/\s+/).filter(Boolean);if(E.every((d)=>i.includes(d)))return 400+E.length*10;let a=0;for(let d of s){if(a=i.indexOf(d,a),a<0)return 0;a++}return Math.max(1,180-Math.floor(i.length/20))}function Js(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Zs(e,t){let r=e.getProject(t.projectId);if(!r)return[];let s=e.listEnvironments(r.id),n=new Map(s.map((o)=>[o.id,o])),i=e.listResourceTags(r.id),E=new Map;for(let o of i){let c=E.get(o.resourceId)??[];c.push({id:o.tag.id,name:o.tag.name,color:o.tag.color}),E.set(o.resourceId,c)}let a=[],d=t.allowedResourceSlugs!==void 0;if(!d){a.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let o of s)a.push({type:"environment",id:o.id,title:o.name,subtitle:`${r.name} · ${o.kind}`,href:`/?env=${encodeURIComponent(o.slug)}`,environment:o.slug,tags:[],score:0})}let T=e.listResources(r.id).filter((o)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(o.slug));for(let o of T){let c=o.environmentId?n.get(o.environmentId):void 0,l=E.get(o.id)??[],_=fr(o.desiredState,Vs),L=[o.name,o.slug,o.kind,o.provider,o.providerId,c?.slug,..._,...l.map((C)=>C.name)].filter(Boolean).join(" "),u=Js(o,c?.slug??s[0]?.slug??"");a.push({type:u.type,id:o.id,title:o.name,subtitle:[o.kind,..._.slice(0,2)].join(" · "),href:u.href,environment:c?.slug,provider:o.provider,tags:l,score:ft(t.query,o.name,L)})}if(!d)for(let o of e.listOperations({projectId:r.id,limit:500})){let c=o.environmentId?n.get(o.environmentId):void 0,l=fr(o.input,Ws),_=o.kind.includes("deploy"),L=l[0]??o.kind,u=[o.kind,o.id,o.correlationId,o.state,...l].join(" ");a.push({type:_?"deployment":"operation",id:o.id,title:L,subtitle:`${o.kind} · ${o.state}`,href:`/server/activity?env=${encodeURIComponent(c?.slug??s[0]?.slug??"")}&operation=${encodeURIComponent(o.id)}`,environment:c?.slug,status:o.state,tags:[],score:ft(t.query,L,u)})}for(let o of a)if(o.score===0)o.score=ft(t.query,o.title,`${o.title} ${o.subtitle} ${o.environment??""} ${o.provider??""}`);let N={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return a.filter((o)=>o.score>0).sort((o,c)=>c.score-o.score||N[o.type]-N[c.type]||o.title.localeCompare(c.title)||o.id.localeCompare(c.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}var le=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},x=(e)=>typeof e==="string"&&e!==""?e:void 0,Ye=(e)=>Number(e)===1,Sr=(e)=>e==null?void 0:Number(e);function Xr(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:x(e.project_id),environmentId:x(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:Sr(e.soft_limit_cents),hardLimitCents:Sr(e.hard_limit_cents),thresholds:le(e.thresholds),meters:le(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:Ye(e.dry_run),enabled:Ye(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function St(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:x(e.project_id),environmentId:x(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:le(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:Ye(e.simulated),appliedAt:x(e.applied_at),releasedAt:x(e.released_at),error:x(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ir(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:x(e.project_id),environmentId:x(e.environment_id),signal:String(e.signal),direction:String(e.direction),observed:Number(e.observed),expected:Number(e.expected),score:Number(e.score),deltaPercent:Number(e.delta_percent),severity:String(e.severity),bucketStart:String(e.bucket_start),evidence:le(e.evidence),acknowledgedAt:x(e.acknowledged_at),createdAt:String(e.created_at)}}function en(e){return{organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),provider:String(e.provider),region:String(e.region),meter:String(e.meter),bucketStart:String(e.bucket_start),quantity:Number(e.quantity),costCents:Number(e.cost_cents),sampleCount:Number(e.sample_count),updatedAt:String(e.updated_at)}}function V(e,t,r){return[e,t??"",r??""].join("/")}var tn=[{atPercent:50,actions:["notify"]},{atPercent:80,actions:["notify"]},{atPercent:100,actions:["notify"],onProjection:!0},{atPercent:100,actions:["notify","block_builds","block_deployments"]},{atPercent:115,actions:["notify","block_builds","block_deployments","throttle_requests"]}];class rn{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}get priceBook(){return this.options.priceBook??or}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}createBudget(e){let t=e.name.trim();if(!t)throw Error("Budgets require a name.");if(e.softLimitCents==null&&e.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(e.softLimitCents!=null&&e.hardLimitCents!=null&&e.softLimitCents>e.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");let r=e.timezone??"UTC";if(!ye(r))throw Error(`Unknown timezone: ${r}`);let s=(e.thresholds??[...tn]).filter((E)=>Number.isFinite(E.atPercent)&&E.atPercent>=0);if(e.environmentId&&!e.projectId)throw Error("An environment-scoped budget must also name its project.");let n=crypto.randomUUID(),i=this.now();return this.controlPlane.database.run("INSERT INTO spend_budgets (id,organization_id,project_id,environment_id,name,period,timezone,currency,soft_limit_cents,hard_limit_cents,thresholds,meters,grace_seconds,hysteresis_percent,dry_run,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[n,e.organizationId,e.projectId??null,e.environmentId??null,t,e.period,r,e.currency??"USD",e.softLimitCents??null,e.hardLimitCents??null,JSON.stringify(s),JSON.stringify(e.meters??[]),Math.max(0,Math.floor(e.graceSeconds??0)),Math.max(0,e.hysteresisPercent??5),e.dryRun?1:0,e.enabled===!1?0:1,i,i]),this.getBudget(n)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?Xr(t):void 0}listBudgets(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(e.enabledOnly)t.push("enabled = 1");return this.query(`SELECT * FROM spend_budgets WHERE ${t.join(" AND ")} ORDER BY created_at`,r).map(Xr)}budgetsForScope(e,t,r){return this.listBudgets({organizationId:e,enabledOnly:!0}).filter((s)=>{if(s.projectId&&s.projectId!==t)return!1;if(s.environmentId&&s.environmentId!==r)return!1;return!0}).sort((s,n)=>Number(!!s.projectId)-Number(!!n.projectId)||Number(!!s.environmentId)-Number(!!n.environmentId))}updateBudget(e,t,r){let s=this.getBudget(e);if(!s)throw Error("Budget was not found.");if(r!=null&&r!==s.version)throw Error(`Budget was modified concurrently (expected version ${r}, found ${s.version}).`);let n={...s,...t};if(n.softLimitCents==null&&n.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(n.softLimitCents!=null&&n.hardLimitCents!=null&&n.softLimitCents>n.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!ye(t.timezone))throw Error(`Unknown timezone: ${t.timezone}`);return this.controlPlane.database.run("UPDATE spend_budgets SET name=?,period=?,timezone=?,currency=?,soft_limit_cents=?,hard_limit_cents=?,thresholds=?,meters=?,grace_seconds=?,hysteresis_percent=?,dry_run=?,enabled=?,version=version+1,updated_at=? WHERE id=?",[n.name,n.period,n.timezone,n.currency??"USD",n.softLimitCents??null,n.hardLimitCents??null,JSON.stringify(n.thresholds??[]),JSON.stringify(n.meters??[]),Math.max(0,Math.floor(n.graceSeconds??0)),Math.max(0,n.hysteresisPercent??5),n.dryRun?1:0,n.enabled===!1?0:1,this.now(),e]),this.getBudget(e)}deleteBudget(e){return this.controlPlane.database.run("DELETE FROM spend_budgets WHERE id = ?",[e]).changes>0}ingestUsage(e){let t={applied:0,duplicates:0,costCents:0,unpricedMeters:[]},r=new Set,s=this.now();return this.controlPlane.database.transaction((i)=>{for(let E of i){if(!(E.quantity>0)||!Number.isFinite(E.quantity))continue;let a=E.key??this.deltaFallbackKey(E);if(this.controlPlane.database.run("INSERT OR IGNORE INTO spend_usage_receipts (key,organization_id,bucket_start,created_at) VALUES (?,?,?,?)",[a,E.organizationId,oe(E.timestamp),s]).changes===0){t.duplicates++;continue}let T={projectId:E.projectId??"",environmentId:E.environmentId??"",resourceId:E.resourceId??"",provider:E.provider??"",region:E.region??""},N=this.periodQuantity(E),o=ct(this.priceBook,{meter:E.meter,quantity:E.quantity,provider:E.provider,region:E.region},N);if(o.unpriced)r.add(String(E.meter));this.controlPlane.database.run(`INSERT INTO spend_usage (organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start,quantity,cost_cents,sample_count,updated_at)
|
|
1508
1508
|
VALUES (?,?,?,?,?,?,?,?,?,?,1,?)
|
|
1509
1509
|
ON CONFLICT(organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start) DO UPDATE SET
|
|
1510
1510
|
quantity = quantity + excluded.quantity,
|
|
1511
1511
|
cost_cents = cost_cents + excluded.cost_cents,
|
|
1512
1512
|
sample_count = sample_count + 1,
|
|
1513
|
-
updated_at = excluded.updated_at`,[
|
|
1514
|
-
FROM spend_usage WHERE ${t} GROUP BY meter, provider ORDER BY SUM(cost_cents) DESC, meter`,r).map((
|
|
1515
|
-
FROM spend_usage WHERE ${t} GROUP BY bucket_start ORDER BY bucket_start`,r).map((o)=>({bucketStart:String(o.bucket_start),costCents:Number(o.cost_cents),quantity:Number(o.quantity)}));return{from:e.from,to:e.to,totalCents:n.reduce((o,s)=>o+s.costCents,0),byMeter:n,series:i}}listRollups(e,t=1000){let{where:r,bindings:n}=this.usageClauses(e);return this.query(`SELECT * FROM spend_usage WHERE ${r} ORDER BY bucket_start DESC LIMIT ?`,[...n,Math.max(1,Math.min(1e4,t))]).map(ri)}budgetSpendCents(e,t=new Date){let r=Q(e.period,e.timezone,t),n=this.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,meters:e.meters.length>0?e.meters:void 0,from:r.start,to:r.end});return{window:r,summary:n}}pruneUsage(e,t=new Date){let r=new Date(t.getTime()-Math.max(1,e)*86400000).toISOString(),n=this.controlPlane.database.run("DELETE FROM spend_usage WHERE bucket_start < ?",[r]).changes,i=new Date(t.getTime()-604800000).toISOString(),o=this.controlPlane.database.run("DELETE FROM spend_usage_receipts WHERE created_at < ?",[i]).changes;return{rollups:n,receipts:o}}recordDecision(e){this.controlPlane.database.run("INSERT INTO spend_decisions (id,budget_id,level,window_start,window_end,used_percent,projected_percent,actual_cents,projected_cents,actions,simulated,reason,evaluated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[crypto.randomUUID(),e.budgetId,e.level,e.window.start,e.window.end,e.usedPercent,e.projectedPercent,e.projection.actualCents,e.projection.projectedCents,JSON.stringify(e.actions),e.simulated?1:0,e.reason,e.evaluatedAt])}listDecisions(e,t=50){return this.query("SELECT * FROM spend_decisions WHERE budget_id = ? ORDER BY evaluated_at DESC LIMIT ?",[e,Math.max(1,Math.min(500,t))]).map((r)=>({id:r.id,budgetId:r.budget_id,level:r.level,window:{start:r.window_start,end:r.window_end},usedPercent:Number(r.used_percent),projectedPercent:Number(r.projected_percent),actualCents:Number(r.actual_cents),projectedCents:Number(r.projected_cents),actions:Te(r.actions),simulated:Ke(r.simulated),reason:r.reason,evaluatedAt:r.evaluated_at}))}openEnforcement(e){let t=this.activeEnforcement(e.budget.id,e.action);if(t)return t;let r=crypto.randomUUID(),n=this.now();return this.controlPlane.database.run("INSERT INTO spend_enforcements (id,budget_id,organization_id,project_id,environment_id,action,state,reason,restore,triggered_at_percent,simulated,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.budget.id,e.budget.organizationId,e.budget.projectId??null,e.budget.environmentId??null,e.action,"pending",e.reason,JSON.stringify(I(e.restore??{})),e.triggeredAtPercent,e.simulated?1:0,n,n]),this.getEnforcement(r)}getEnforcement(e){let t=this.query("SELECT * FROM spend_enforcements WHERE id = ?",[e])[0];return t?Rt(t):void 0}activeEnforcement(e,t){let r=this.query("SELECT * FROM spend_enforcements WHERE budget_id = ? AND action = ? AND state IN ('pending','active','releasing')",[e,t])[0];return r?Rt(r):void 0}listEnforcements(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.budgetId)t.push("budget_id = ?"),r.push(e.budgetId);if(e.activeOnly)t.push("state IN ('pending','active','releasing')");return this.query(`SELECT * FROM spend_enforcements WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(Rt)}transitionEnforcement(e,t,r={}){let n=this.getEnforcement(e);if(!n)throw Error("Enforcement was not found.");let i=this.now();return this.controlPlane.database.run("UPDATE spend_enforcements SET state=?, error=?, restore=?, applied_at=?, released_at=?, updated_at=? WHERE id=?",[t,r.error??null,JSON.stringify(I(r.restore??n.restore)),t==="active"?n.appliedAt??i:n.appliedAt??null,t==="released"?i:n.releasedAt??null,i,e]),this.getEnforcement(e)}recordAnomaly(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT OR IGNORE INTO spend_anomalies (id,organization_id,project_id,environment_id,scope_key,signal,direction,observed,expected,score,delta_percent,severity,bucket_start,evidence,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId??null,e.environmentId??null,G(e.organizationId,e.projectId,e.environmentId),e.signal,e.direction,e.observed,e.expected,e.score,e.deltaPercent,e.severity,e.bucketStart,JSON.stringify(I(e.evidence??{})),this.now()]).changes>0?this.getAnomaly(t):void 0}getAnomaly(e){let t=this.query("SELECT * FROM spend_anomalies WHERE id = ?",[e])[0];return t?Ar(t):void 0}listAnomalies(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.since)t.push("bucket_start >= ?"),r.push(e.since);if(e.unacknowledgedOnly)t.push("acknowledged_at IS NULL");return this.query(`SELECT * FROM spend_anomalies WHERE ${t.join(" AND ")} ORDER BY bucket_start DESC LIMIT ?`,[...r,Math.max(1,Math.min(1000,e.limit??100))]).map(Ar)}acknowledgeAnomaly(e){return this.controlPlane.database.run("UPDATE spend_anomalies SET acknowledged_at = ? WHERE id = ? AND acknowledged_at IS NULL",[this.now(),e]).changes>0}}function Or(e){if(!(e.totalMs>0))return 1;return Math.min(1,Math.max(0,e.elapsedMs/e.totalMs))}function oi(e){let t=e.window,r=Math.max(1,t.elapsedMs),n=e.actualCents/r,i=e.series??[],o=Math.min(1,Math.max(0,e.recencyWeight??0.6));if(i.length<2||o===0)return n;let s=0.3,a=i[0].costCents;for(let c=1;c<i.length;c++)a=s*i[c].costCents+(1-s)*a;let d=a/3600000;return n*(1-o)+d*o}function si(e,t){let r=Or(e),n=1-Math.exp(-3*r),i=Math.min(1,t/6);return Math.round(n*i*100)/100}function Ur(e){let t=e.window,r=Or(t),n=Math.max(0,e.actualCents),i=oi(e),o=Math.max(0,t.totalMs-t.elapsedMs),s=n+i*o,a=(e.series??[]).filter((c)=>c.costCents>0).length,d={actualCents:n,burnRateCentsPerMs:i,projectedCents:s,elapsedFraction:r,confidence:si(t,a)};if(e.limitCents!=null&&e.limitCents>0&&i>0){let c=e.limitCents-n;if(c<=0)d.timeToExhaustionMs=0,d.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs).toISOString();else{let p=c/i;if(p<=o)d.timeToExhaustionMs=p,d.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs+p).toISOString()}}return d}function Ct(e,t){if(t==null)return 0;if(t<=0)return e>0?1/0:0;return e/t*100}function ge(e){if(e==null)return"";if(e<=0)return"now";let t=Math.floor(e/3600000),r=Math.floor(t/24);if(r>0)return`${r}d ${t%24}h`;if(t>0)return`${t}h ${Math.floor(e%3600000/60000)}m`;return`${Math.max(1,Math.floor(e/60000))}m`}var ai=0.35;function Qe(e){return e.hardLimitCents??e.softLimitCents}function di(e,t,r){if(r.some((s)=>s!=="notify"))return"hard_capped";let i=Qe(e),o=e.softLimitCents;if(o!=null&&i!=null&&i>0&&t>=o/i*100)return"soft_capped";if(t>=50)return"warning";return"ok"}function $e(e){return[...new Set(e)].sort((t,r)=>k[t]-k[r])}function ci(e,t,r,n,i){if(i.length===0)return`Spend is at ${r.toFixed(1)}% of the ${t.period} budget.`;let o=i[i.length-1];if(o.projected)return`Projected spend for this ${t.period} window reaches ${o.observedPercent.toFixed(1)}% of the budget (${n.confidence.toFixed(2)} confidence), crossing the ${o.atPercent}% threshold.`;return`Spend reached ${r.toFixed(1)}% of the ${t.period} budget, crossing the ${o.atPercent}% threshold${e==="hard_capped"?" and triggering enforcement":""}.`}function Dr(e){let{budget:t,window:r}=e,n=e.now??new Date,i=Qe(t),o=Ur({window:r,actualCents:e.actualCents,series:e.series,limitCents:i}),s=Ct(e.actualCents,i),a=Ct(o.projectedCents,i),d=t.graceSeconds*1000,c=d===0||e.breachingSince!=null&&n.getTime()-new Date(e.breachingSince).getTime()>=d,p=o.confidence>=ai,l=[],u=new Set;for(let h of[...t.thresholds].sort((N,f)=>N.atPercent-f.atPercent)){let N=h.onProjection===!0,f=N?a:s;if(!(f>=h.atPercent))continue;let b=h.actions.filter((O)=>O!=="notify");if(N&&!p&&b.length>0)continue;l.push({atPercent:h.atPercent,actions:h.actions,projected:N,observedPercent:f});for(let O of h.actions){if(O!=="notify"&&!c)continue;u.add(O)}}let m=$e(u),E=100-t.hysteresisPercent,T=$e((e.activeActions??[]).filter((h)=>{if(u.has(h))return!1;let N=t.thresholds.filter((b)=>b.actions.includes(h)).reduce((b,O)=>b==null?O.atPercent:Math.min(b,O.atPercent),void 0);if(N==null)return!0;return Math.max(s,p?a:0)<=N*(E/100)})),_=di(t,s,m);return{budgetId:t.id,level:_,window:r,projection:o,usedPercent:s,projectedPercent:a,breaches:l,actions:t.dryRun?m.filter((h)=>h==="notify"):m,releases:T,simulated:t.dryRun,reason:ci(_,t,s,o,l),evaluatedAt:n.toISOString()}}function wr(e){let t=new Set;for(let o of e)for(let s of o.actions)t.add(s);let r=new Set;for(let o of e)for(let s of o.releases)if(!t.has(s))r.add(s);let n={ok:0,warning:1,soft_capped:2,hard_capped:3},i=e.reduce((o,s)=>n[s.level]>n[o]?s.level:o,"ok");return{actions:$e(t),releases:$e(r),level:i}}var Ye={notify:"Send the configured spend notifications.",block_builds:"Refuse new builds. Running builds finish.",block_deployments:"Refuse new deployments. The running release keeps serving.",throttle_requests:"Rate-limit inbound requests at the edge to cap egress and compute.",suspend_functions:"Stop invoking serverless functions; static and cached responses still serve.",serve_static:"Serve the last built static output only; dynamic rendering is off.",suspend_project:"Park all inbound traffic behind a 503. No data is removed."},li=["throttle_requests","suspend_functions","serve_static","suspend_project"],ui=["production"];function kr(e,t,r){let n=li.includes(e),i=r.approvalRequiredFor??ui,o=r.environmentKind!=null&&i.includes(r.environmentKind),s=r.maxAutomaticAction!=null&&k[e]>k[r.maxAutomaticAction];return{action:e,description:Ye[e],userVisible:n,requiresApproval:s||n&&o,reason:t}}function Xr(e,t={}){let r=e.actions.map((i)=>kr(i,e.reason,t)),n=[...e.releases].sort((i,o)=>k[o]-k[i]).map((i)=>kr(i,"Spend fell back below the threshold that armed this action.",t));return{budgetId:e.budgetId,simulated:e.simulated,apply:r.filter((i)=>!i.requiresApproval),release:n.map((i)=>({...i,requiresApproval:!1})),withheld:r.filter((i)=>i.requiresApproval)}}async function Pr(e,t,r,n,i){let o={applied:[],released:[],failed:[],withheld:n.withheld,simulated:n.simulated};for(let s of n.apply){let a=e.openEnforcement({budget:t,action:s.action,reason:s.reason,triggeredAtPercent:r.usedPercent,simulated:n.simulated});if(a.state==="active")continue;if(n.simulated){o.applied.push(e.transitionEnforcement(a.id,"active",{restore:{simulated:!0}}));continue}try{let d=await i.apply(s.action,{budget:t,decision:r,record:a});o.applied.push(e.transitionEnforcement(a.id,"active",{restore:d}))}catch(d){let c=d instanceof Error?d.message:String(d);e.transitionEnforcement(a.id,"failed",{error:c}),o.failed.push({action:s.action,error:c})}}for(let s of n.release){let a=e.activeEnforcement(t.id,s.action);if(!a)continue;if(n.simulated||a.simulated){o.released.push(e.transitionEnforcement(a.id,"released"));continue}e.transitionEnforcement(a.id,"releasing");try{await i.release(s.action,{budget:t,record:a,restore:a.restore}),o.released.push(e.transitionEnforcement(a.id,"released"))}catch(d){let c=d instanceof Error?d.message:String(d);e.transitionEnforcement(a.id,"releasing",{error:c}),o.failed.push({action:s.action,error:c})}}return o}function xr(e){return e.filter((t)=>t.state==="active").map((t)=>t.action).sort((t,r)=>k[r]-k[t])[0]}function jr(e,t){let r=new Set(t.filter((i)=>i.state==="active"&&!i.simulated).map((i)=>i.action)),n={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};for(let i of n[e]??[])if(r.has(i))return{allowed:!1,blockedBy:i,reason:Ye[i]};return{allowed:!0}}function At(e){if(e.length===0)return 0;let t=[...e].sort((n,i)=>n-i),r=t.length>>1;return t.length%2===0?(t[r-1]+t[r])/2:t[r]}function pi(e,t){if(e.length===0)return 0;let r=t??At(e);return 1.4826*At(e.map((n)=>Math.abs(n-r)))}function Ei(e,t){let r=At(t),n=pi(t,r);if(n===0)n=Math.max(Math.abs(r)*0.1,Number.EPSILON);return{score:(e-r)/n,center:r,deviation:n}}function na(e,t=0.3){let r=[],n=e[0]??0;for(let i of e)n=t*i+(1-t)*n,r.push(n);return r}function mi(e,t,r){let n=[];for(let i=t-r;i>=0;i-=r)if(Number.isFinite(e[i]))n.push(e[i]);return n}function Ti(e,t={}){let r=Math.max(1,Math.floor(t.seasonLength??24)),n=t.threshold??3.5,i=t.criticalThreshold??n*2,o=Math.max(2,Math.floor(t.minHistory??3)),s=Math.max(0,t.minAbsoluteDelta??0),a=e.map((p)=>p.value),d=[],c=0;for(let p=0;p<e.length;p++){let l=mi(a,p,r);if(l.length<o)continue;let u=a[p];if(!Number.isFinite(u))continue;c++;let{score:m,center:E,deviation:T}=Ei(u,l),_=m>=0?"spike":"drop";if(_==="drop"&&t.detectDrops!==!0)continue;if(Math.abs(m)<n)continue;if(Math.abs(u-E)<s)continue;d.push({bucketStart:e[p].bucketStart,observed:u,expected:E,score:m,direction:_,deltaPercent:E===0?u===0?0:1/0:(u-E)/E*100,severity:Math.abs(m)>=i?"critical":"warning",historySize:l.length,deviation:T})}return{anomalies:d,warmingUp:c===0,evaluated:c}}function Fr(e,t={}){if(e.length===0)return;let r=Ti(e,t),n=e[e.length-1].bucketStart;return r.anomalies.find((i)=>i.bucketStart===n)}function Ge(e){if(e==="cost")return{seasonLength:24,threshold:3.5,minHistory:3,minAbsoluteDelta:25};if(e.startsWith("edge.")||e.startsWith("function."))return{seasonLength:168,threshold:4,minHistory:3,minAbsoluteDelta:1000};return{seasonLength:24,threshold:3.5,minHistory:3}}var gi={low:6,medium:3.5,high:2.5},W=(e)=>typeof e==="string"&&e!==""?e:void 0;function Ot(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),environmentId:W(e.environment_id),signal:String(e.signal),enabled:Number(e.enabled)===1,sensitivity:String(e.sensitivity),seasonLength:Number(e.season_length),minAbsoluteDelta:Number(e.min_absolute_delta),detectDrops:Number(e.detect_drops)===1,severity:String(e.severity),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function _i(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),signal:W(e.signal),routePattern:W(e.route_pattern),statusCode:e.status_code==null?void 0:Number(e.status_code),reason:String(e.reason),actorId:W(e.actor_id),expiresAt:W(e.expires_at),createdAt:String(e.created_at)}}function hi(e,t){if(e==="*"||e==="**")return!0;let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${r}$`).test(t)}class Ut{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}upsert(e){let t=e.signal.trim();if(!t)throw Error("An anomaly config needs a signal.");if(e.seasonLength!=null&&(!Number.isInteger(e.seasonLength)||e.seasonLength<1))throw Error("seasonLength must be a positive integer.");let r=G(e.organizationId,e.projectId,e.environmentId),n=this.now(),i=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[r,t])[0],o=Ge(t);if(i)return this.controlPlane.database.run("UPDATE anomaly_configs SET enabled=?,sensitivity=?,season_length=?,min_absolute_delta=?,detect_drops=?,severity=?,version=version+1,updated_at=? WHERE id=?",[e.enabled===!1?0:1,e.sensitivity??String(i.sensitivity),e.seasonLength??Number(i.season_length),e.minAbsoluteDelta??Number(i.min_absolute_delta),e.detectDrops==null?Number(i.detect_drops):e.detectDrops?1:0,e.severity??String(i.severity),n,String(i.id)]),this.get(String(i.id));let s=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_configs (id,organization_id,project_id,environment_id,scope_key,signal,enabled,sensitivity,season_length,min_absolute_delta,detect_drops,severity,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[s,e.organizationId,e.projectId??null,e.environmentId??null,r,t,e.enabled===!1?0:1,e.sensitivity??"medium",e.seasonLength??o.seasonLength??24,e.minAbsoluteDelta??o.minAbsoluteDelta??0,e.detectDrops?1:0,e.severity??"warning",n,n]),this.get(s)}get(e){let t=this.query("SELECT * FROM anomaly_configs WHERE id = ?",[e])[0];return t?Ot(t):void 0}list(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);return this.query(`SELECT * FROM anomaly_configs WHERE ${t.join(" AND ")} ORDER BY signal`,r).map(Ot)}delete(e){return this.controlPlane.database.run("DELETE FROM anomaly_configs WHERE id = ?",[e]).changes>0}optionsFor(e,t){let r=[G(e.organizationId,e.projectId,e.environmentId),G(e.organizationId,e.projectId),G(e.organizationId)];for(let n of r){let i=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[n,t])[0];if(!i)continue;let o=Ot(i);return{config:o,enabled:o.enabled,options:{...Ge(t),threshold:gi[o.sensitivity],seasonLength:o.seasonLength,minAbsoluteDelta:o.minAbsoluteDelta,detectDrops:o.detectDrops}}}return{options:Ge(t),enabled:!0}}silence(e){let t=e.reason.trim();if(!t)throw Error("A silence needs a reason: someone will ask why this stopped alerting.");if(!e.signal&&!e.routePattern&&e.statusCode==null)throw Error("A silence needs at least one of signal, routePattern, or statusCode.");let r=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_silences (id,organization_id,project_id,scope_key,signal,route_pattern,status_code,reason,actor_id,expires_at,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId??null,G(e.organizationId,e.projectId),e.signal??null,e.routePattern??null,e.statusCode??null,t,e.actorId??null,e.expiresAt??null,this.now()]),this.listSilences({organizationId:e.organizationId}).find((n)=>n.id===r)}listSilences(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(!e.includeExpired)t.push("(expires_at IS NULL OR expires_at > ?)"),r.push(this.now());return this.query(`SELECT * FROM anomaly_silences WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(_i)}removeSilence(e){return this.controlPlane.database.run("DELETE FROM anomaly_silences WHERE id = ?",[e]).changes>0}isSilenced(e,t){return this.listSilences(e).find((r)=>{if(r.signal&&r.signal!==t.signal)return!1;if(r.statusCode!=null&&r.statusCode!==t.statusCode)return!1;if(r.routePattern){if(!t.route)return!1;if(!hi(r.routePattern,t.route))return!1}return!0})}}var he=[{key:"cost",routeAware:!1,label:"Cost",source:"usage",gapPolicy:"zero",minSamples:0,unit:"cents"},{key:"edge.requests",routeAware:!1,label:"Edge requests",source:"usage",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"edge.egress_gb",routeAware:!1,label:"Edge egress",source:"usage",gapPolicy:"zero",minSamples:0,unit:"GB"},{key:"function.invocations",routeAware:!1,label:"Function invocations",source:"usage",gapPolicy:"zero",minSamples:0,unit:"invocations"},{key:"http.requests",routeAware:!0,label:"HTTP requests",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"http.errors",routeAware:!0,label:"HTTP 5xx",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"responses"},{key:"http.error_rate",routeAware:!0,label:"HTTP error rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.client_error_rate",routeAware:!0,label:"HTTP 4xx rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.latency_p95",routeAware:!0,label:"Latency p95",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ms"}];function wt(e){return he.find((t)=>t.key===e)}var _e=3600000;function Ni(e,t=960){let r=Math.floor(new Date(e.from).getTime()/_e)*_e,n=new Date(e.to).getTime(),i=[];for(let o=r;o<n&&i.length<t;o+=_e)i.push(o);return i}function Dt(e,t,r){let n=[],i=0,o=0;for(let s of Ni(t)){let a=r.get(s),d=new Date(s).toISOString();if(!a){n.push({bucketStart:d,value:e.gapPolicy==="zero"?0:Number.NaN});continue}if(a.samples<e.minSamples){n.push({bucketStart:d,value:Number.NaN}),o++;continue}n.push({bucketStart:d,value:a.value}),i++}return{signal:e.key,points:n,populated:i,suppressed:o,unit:e.unit}}class kt{controlPlane;spend;counterCache=new Map;constructor(e,t){this.controlPlane=e;this.spend=t}query(e,t){return this.controlPlane.database.query(e).all(...t)}usageSeries(e,t,r){let n=this.spend.summarizeUsage({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,meters:e.key==="cost"?void 0:[e.key],from:r.from,to:r.to}),i=new Map;for(let o of n.series)i.set(new Date(o.bucketStart).getTime(),{value:e.key==="cost"?o.costCents:o.quantity,samples:1});return Dt(e,r,i)}requestFilter(e,t){let r=["project_id = ?","kind = 'request'","timestamp >= ?","timestamp < ?"],n=[e.projectId,t.from,t.to];if(e.environmentId)r.push("environment_id = ?"),n.push(e.environmentId);if(e.route)r.push("path_template = ?"),n.push(e.route);return{clauses:r,bindings:n}}counters(e,t){let r=[e.projectId,e.environmentId??"",e.route??"",t.from,t.to].join("\x00"),n=this.counterCache.get(r);if(n)return n;let{clauses:i,bindings:o}=this.requestFilter(e,t),s=this.query(`SELECT
|
|
1513
|
+
updated_at = excluded.updated_at`,[E.organizationId,T.projectId,T.environmentId,T.resourceId,T.provider,T.region,E.meter,oe(E.timestamp),E.quantity,o.costCents,s]),t.applied++,t.costCents+=o.costCents}})(e),t.unpricedMeters=[...r],t}deltaFallbackKey(e){return ws("sha256").update([e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.provider??"",e.region??"",e.meter,e.timestamp,String(e.quantity)].join("\x00")).digest("hex").slice(0,32)}periodQuantity(e){let t=G("monthly","UTC",new Date(e.timestamp)),r=this.query("SELECT COALESCE(SUM(quantity), 0) AS total FROM spend_usage WHERE organization_id = ? AND meter = ? AND provider = ? AND region = ? AND bucket_start >= ? AND bucket_start < ?",[e.organizationId,e.meter,e.provider??"",e.region??"",t.start,t.end])[0];return Number(r?.total??0)}usageClauses(e){let t=["organization_id = ?","bucket_start >= ?","bucket_start < ?"],r=[e.organizationId,e.from,e.to];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.environmentId)t.push("environment_id = ?"),r.push(e.environmentId);if(e.resourceId)t.push("resource_id = ?"),r.push(e.resourceId);if(e.meters?.length)t.push(`meter IN (${e.meters.map(()=>"?").join(",")})`),r.push(...e.meters.map(String));if(e.providers?.length)t.push(`provider IN (${e.providers.map(()=>"?").join(",")})`),r.push(...e.providers);return{where:t.join(" AND "),bindings:r}}summarizeUsage(e){let{where:t,bindings:r}=this.usageClauses(e),s=this.query(`SELECT meter, provider, SUM(quantity) AS quantity, SUM(cost_cents) AS cost_cents, SUM(sample_count) AS sample_count
|
|
1514
|
+
FROM spend_usage WHERE ${t} GROUP BY meter, provider ORDER BY SUM(cost_cents) DESC, meter`,r).map((i)=>({meter:String(i.meter),provider:String(i.provider),quantity:Number(i.quantity),costCents:Number(i.cost_cents),sampleCount:Number(i.sample_count)})),n=this.query(`SELECT bucket_start, SUM(cost_cents) AS cost_cents, SUM(quantity) AS quantity
|
|
1515
|
+
FROM spend_usage WHERE ${t} GROUP BY bucket_start ORDER BY bucket_start`,r).map((i)=>({bucketStart:String(i.bucket_start),costCents:Number(i.cost_cents),quantity:Number(i.quantity)}));return{from:e.from,to:e.to,totalCents:s.reduce((i,E)=>i+E.costCents,0),byMeter:s,series:n}}listRollups(e,t=1000){let{where:r,bindings:s}=this.usageClauses(e);return this.query(`SELECT * FROM spend_usage WHERE ${r} ORDER BY bucket_start DESC LIMIT ?`,[...s,Math.max(1,Math.min(1e4,t))]).map(en)}budgetSpendCents(e,t=new Date){let r=G(e.period,e.timezone,t),s=this.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,meters:e.meters.length>0?e.meters:void 0,from:r.start,to:r.end});return{window:r,summary:s}}pruneUsage(e,t=new Date){let r=new Date(t.getTime()-Math.max(1,e)*86400000).toISOString(),s=this.controlPlane.database.run("DELETE FROM spend_usage WHERE bucket_start < ?",[r]).changes,n=new Date(t.getTime()-604800000).toISOString(),i=this.controlPlane.database.run("DELETE FROM spend_usage_receipts WHERE created_at < ?",[n]).changes;return{rollups:s,receipts:i}}recordDecision(e){this.controlPlane.database.run("INSERT INTO spend_decisions (id,budget_id,level,window_start,window_end,used_percent,projected_percent,actual_cents,projected_cents,actions,simulated,reason,evaluated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[crypto.randomUUID(),e.budgetId,e.level,e.window.start,e.window.end,e.usedPercent,e.projectedPercent,e.projection.actualCents,e.projection.projectedCents,JSON.stringify(e.actions),e.simulated?1:0,e.reason,e.evaluatedAt])}listDecisions(e,t=50){return this.query("SELECT * FROM spend_decisions WHERE budget_id = ? ORDER BY evaluated_at DESC LIMIT ?",[e,Math.max(1,Math.min(500,t))]).map((r)=>({id:r.id,budgetId:r.budget_id,level:r.level,window:{start:r.window_start,end:r.window_end},usedPercent:Number(r.used_percent),projectedPercent:Number(r.projected_percent),actualCents:Number(r.actual_cents),projectedCents:Number(r.projected_cents),actions:le(r.actions),simulated:Ye(r.simulated),reason:r.reason,evaluatedAt:r.evaluated_at}))}openEnforcement(e){let t=this.activeEnforcement(e.budget.id,e.action);if(t)return t;let r=crypto.randomUUID(),s=this.now();return this.controlPlane.database.run("INSERT INTO spend_enforcements (id,budget_id,organization_id,project_id,environment_id,action,state,reason,restore,triggered_at_percent,simulated,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.budget.id,e.budget.organizationId,e.budget.projectId??null,e.budget.environmentId??null,e.action,"pending",e.reason,JSON.stringify(h(e.restore??{})),e.triggeredAtPercent,e.simulated?1:0,s,s]),this.getEnforcement(r)}getEnforcement(e){let t=this.query("SELECT * FROM spend_enforcements WHERE id = ?",[e])[0];return t?St(t):void 0}activeEnforcement(e,t){let r=this.query("SELECT * FROM spend_enforcements WHERE budget_id = ? AND action = ? AND state IN ('pending','active','releasing')",[e,t])[0];return r?St(r):void 0}listEnforcements(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.budgetId)t.push("budget_id = ?"),r.push(e.budgetId);if(e.activeOnly)t.push("state IN ('pending','active','releasing')");return this.query(`SELECT * FROM spend_enforcements WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(St)}transitionEnforcement(e,t,r={}){let s=this.getEnforcement(e);if(!s)throw Error("Enforcement was not found.");let n=this.now();return this.controlPlane.database.run("UPDATE spend_enforcements SET state=?, error=?, restore=?, applied_at=?, released_at=?, updated_at=? WHERE id=?",[t,r.error??null,JSON.stringify(h(r.restore??s.restore)),t==="active"?s.appliedAt??n:s.appliedAt??null,t==="released"?n:s.releasedAt??null,n,e]),this.getEnforcement(e)}recordAnomaly(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT OR IGNORE INTO spend_anomalies (id,organization_id,project_id,environment_id,scope_key,signal,direction,observed,expected,score,delta_percent,severity,bucket_start,evidence,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId??null,e.environmentId??null,V(e.organizationId,e.projectId,e.environmentId),e.signal,e.direction,e.observed,e.expected,e.score,e.deltaPercent,e.severity,e.bucketStart,JSON.stringify(h(e.evidence??{})),this.now()]).changes>0?this.getAnomaly(t):void 0}getAnomaly(e){let t=this.query("SELECT * FROM spend_anomalies WHERE id = ?",[e])[0];return t?Ir(t):void 0}listAnomalies(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.since)t.push("bucket_start >= ?"),r.push(e.since);if(e.unacknowledgedOnly)t.push("acknowledged_at IS NULL");return this.query(`SELECT * FROM spend_anomalies WHERE ${t.join(" AND ")} ORDER BY bucket_start DESC LIMIT ?`,[...r,Math.max(1,Math.min(1000,e.limit??100))]).map(Ir)}acknowledgeAnomaly(e){return this.controlPlane.database.run("UPDATE spend_anomalies SET acknowledged_at = ? WHERE id = ? AND acknowledged_at IS NULL",[this.now(),e]).changes>0}}function vr(e){if(!(e.totalMs>0))return 1;return Math.min(1,Math.max(0,e.elapsedMs/e.totalMs))}function sn(e){let t=e.window,r=Math.max(1,t.elapsedMs),s=e.actualCents/r,n=e.series??[],i=Math.min(1,Math.max(0,e.recencyWeight??0.6));if(n.length<2||i===0)return s;let E=0.3,a=n[0].costCents;for(let T=1;T<n.length;T++)a=E*n[T].costCents+(1-E)*a;let d=a/3600000;return s*(1-i)+d*i}function nn(e,t){let r=vr(e),s=1-Math.exp(-3*r),n=Math.min(1,t/6);return Math.round(s*n*100)/100}function yr(e){let t=e.window,r=vr(t),s=Math.max(0,e.actualCents),n=sn(e),i=Math.max(0,t.totalMs-t.elapsedMs),E=s+n*i,a=(e.series??[]).filter((T)=>T.costCents>0).length,d={actualCents:s,burnRateCentsPerMs:n,projectedCents:E,elapsedFraction:r,confidence:nn(t,a)};if(e.limitCents!=null&&e.limitCents>0&&n>0){let T=e.limitCents-s;if(T<=0)d.timeToExhaustionMs=0,d.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs).toISOString();else{let N=T/n;if(N<=i)d.timeToExhaustionMs=N,d.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs+N).toISOString()}}return d}function Xt(e,t){if(t==null)return 0;if(t<=0)return e>0?1/0:0;return e/t*100}function Le(e){if(e==null)return"";if(e<=0)return"now";let t=Math.floor(e/3600000),r=Math.floor(t/24);if(r>0)return`${r}d ${t%24}h`;if(t>0)return`${t}h ${Math.floor(e%3600000/60000)}m`;return`${Math.max(1,Math.floor(e/60000))}m`}var En=0.35;function Ge(e){return e.hardLimitCents??e.softLimitCents}function an(e,t,r){if(r.some((E)=>E!=="notify"))return"hard_capped";let n=Ge(e),i=e.softLimitCents;if(i!=null&&n!=null&&n>0&&t>=i/n*100)return"soft_capped";if(t>=50)return"warning";return"ok"}function ze(e){return[...new Set(e)].sort((t,r)=>k[t]-k[r])}function dn(e,t,r,s,n){if(n.length===0)return`Spend is at ${r.toFixed(1)}% of the ${t.period} budget.`;let i=n[n.length-1];if(i.projected)return`Projected spend for this ${t.period} window reaches ${i.observedPercent.toFixed(1)}% of the budget (${s.confidence.toFixed(2)} confidence), crossing the ${i.atPercent}% threshold.`;return`Spend reached ${r.toFixed(1)}% of the ${t.period} budget, crossing the ${i.atPercent}% threshold${e==="hard_capped"?" and triggering enforcement":""}.`}function pr(e){let{budget:t,window:r}=e,s=e.now??new Date,n=Ge(t),i=yr({window:r,actualCents:e.actualCents,series:e.series,limitCents:n}),E=Xt(e.actualCents,n),a=Xt(i.projectedCents,n),d=t.graceSeconds*1000,T=d===0||e.breachingSince!=null&&s.getTime()-new Date(e.breachingSince).getTime()>=d,N=i.confidence>=En,o=[],c=new Set;for(let C of[...t.thresholds].sort((g,R)=>g.atPercent-R.atPercent)){let g=C.onProjection===!0,R=g?a:E;if(!(R>=C.atPercent))continue;let S=C.actions.filter((y)=>y!=="notify");if(g&&!N&&S.length>0)continue;o.push({atPercent:C.atPercent,actions:C.actions,projected:g,observedPercent:R});for(let y of C.actions){if(y!=="notify"&&!T)continue;c.add(y)}}let l=ze(c),_=100-t.hysteresisPercent,L=ze((e.activeActions??[]).filter((C)=>{if(c.has(C))return!1;let g=t.thresholds.filter((S)=>S.actions.includes(C)).reduce((S,y)=>S==null?y.atPercent:Math.min(S,y.atPercent),void 0);if(g==null)return!0;return Math.max(E,N?a:0)<=g*(_/100)})),u=an(t,E,l);return{budgetId:t.id,level:u,window:r,projection:i,usedPercent:E,projectedPercent:a,breaches:o,actions:t.dryRun?l.filter((C)=>C==="notify"):l,releases:L,simulated:t.dryRun,reason:dn(u,t,E,i,o),evaluatedAt:s.toISOString()}}function Dr(e){let t=new Set;for(let i of e)for(let E of i.actions)t.add(E);let r=new Set;for(let i of e)for(let E of i.releases)if(!t.has(E))r.add(E);let s={ok:0,warning:1,soft_capped:2,hard_capped:3},n=e.reduce((i,E)=>s[E.level]>s[i]?E.level:i,"ok");return{actions:ze(t),releases:ze(r),level:n}}var Qe={notify:"Send the configured spend notifications.",block_builds:"Refuse new builds. Running builds finish.",block_deployments:"Refuse new deployments. The running release keeps serving.",throttle_requests:"Rate-limit inbound requests at the edge to cap egress and compute.",suspend_functions:"Stop invoking serverless functions; static and cached responses still serve.",serve_static:"Serve the last built static output only; dynamic rendering is off.",suspend_project:"Park all inbound traffic behind a 503. No data is removed."},Tn=["throttle_requests","suspend_functions","serve_static","suspend_project"],on=["production"];function br(e,t,r){let s=Tn.includes(e),n=r.approvalRequiredFor??on,i=r.environmentKind!=null&&n.includes(r.environmentKind),E=r.maxAutomaticAction!=null&&k[e]>k[r.maxAutomaticAction];return{action:e,description:Qe[e],userVisible:s,requiresApproval:E||s&&i,reason:t}}function kr(e,t={}){let r=e.actions.map((n)=>br(n,e.reason,t)),s=[...e.releases].sort((n,i)=>k[i]-k[n]).map((n)=>br(n,"Spend fell back below the threshold that armed this action.",t));return{budgetId:e.budgetId,simulated:e.simulated,apply:r.filter((n)=>!n.requiresApproval),release:s.map((n)=>({...n,requiresApproval:!1})),withheld:r.filter((n)=>n.requiresApproval)}}async function Fr(e,t,r,s,n){let i={applied:[],released:[],failed:[],withheld:s.withheld,simulated:s.simulated};for(let E of s.apply){let a=e.openEnforcement({budget:t,action:E.action,reason:E.reason,triggeredAtPercent:r.usedPercent,simulated:s.simulated});if(a.state==="active")continue;if(s.simulated){i.applied.push(e.transitionEnforcement(a.id,"active",{restore:{simulated:!0}}));continue}try{let d=await n.apply(E.action,{budget:t,decision:r,record:a});i.applied.push(e.transitionEnforcement(a.id,"active",{restore:d}))}catch(d){let T=d instanceof Error?d.message:String(d);e.transitionEnforcement(a.id,"failed",{error:T}),i.failed.push({action:E.action,error:T})}}for(let E of s.release){let a=e.activeEnforcement(t.id,E.action);if(!a)continue;if(s.simulated||a.simulated){i.released.push(e.transitionEnforcement(a.id,"released"));continue}e.transitionEnforcement(a.id,"releasing");try{await n.release(E.action,{budget:t,record:a,restore:a.restore}),i.released.push(e.transitionEnforcement(a.id,"released"))}catch(d){let T=d instanceof Error?d.message:String(d);e.transitionEnforcement(a.id,"releasing",{error:T}),i.failed.push({action:E.action,error:T})}}return i}function Pr(e){return e.filter((t)=>t.state==="active").map((t)=>t.action).sort((t,r)=>k[r]-k[t])[0]}function Hr(e,t){let r=new Set(t.filter((n)=>n.state==="active"&&!n.simulated).map((n)=>n.action)),s={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};for(let n of s[e]??[])if(r.has(n))return{allowed:!1,blockedBy:n,reason:Qe[n]};return{allowed:!0}}function It(e){if(e.length===0)return 0;let t=[...e].sort((s,n)=>s-n),r=t.length>>1;return t.length%2===0?(t[r-1]+t[r])/2:t[r]}function cn(e,t){if(e.length===0)return 0;let r=t??It(e);return 1.4826*It(e.map((s)=>Math.abs(s-r)))}function Nn(e,t){let r=It(t),s=cn(t,r);if(s===0)s=Math.max(Math.abs(r)*0.1,Number.EPSILON);return{score:(e-r)/s,center:r,deviation:s}}function ta(e,t=0.3){let r=[],s=e[0]??0;for(let n of e)s=t*n+(1-t)*s,r.push(s);return r}function _n(e,t,r){let s=[];for(let n=t-r;n>=0;n-=r)if(Number.isFinite(e[n]))s.push(e[n]);return s}function ln(e,t={}){let r=Math.max(1,Math.floor(t.seasonLength??24)),s=t.threshold??3.5,n=t.criticalThreshold??s*2,i=Math.max(2,Math.floor(t.minHistory??3)),E=Math.max(0,t.minAbsoluteDelta??0),a=e.map((N)=>N.value),d=[],T=0;for(let N=0;N<e.length;N++){let o=_n(a,N,r);if(o.length<i)continue;let c=a[N];if(!Number.isFinite(c))continue;T++;let{score:l,center:_,deviation:L}=Nn(c,o),u=l>=0?"spike":"drop";if(u==="drop"&&t.detectDrops!==!0)continue;if(Math.abs(l)<s)continue;if(Math.abs(c-_)<E)continue;d.push({bucketStart:e[N].bucketStart,observed:c,expected:_,score:l,direction:u,deltaPercent:_===0?c===0?0:1/0:(c-_)/_*100,severity:Math.abs(l)>=n?"critical":"warning",historySize:o.length,deviation:L})}return{anomalies:d,warmingUp:T===0,evaluated:T}}function Kr(e,t={}){if(e.length===0)return;let r=ln(e,t),s=e[e.length-1].bucketStart;return r.anomalies.find((n)=>n.bucketStart===s)}function Ve(e){if(e==="cost")return{seasonLength:24,threshold:3.5,minHistory:3,minAbsoluteDelta:25};if(e.startsWith("edge.")||e.startsWith("function."))return{seasonLength:168,threshold:4,minHistory:3,minAbsoluteDelta:1000};return{seasonLength:24,threshold:3.5,minHistory:3}}var Ln={low:6,medium:3.5,high:2.5},W=(e)=>typeof e==="string"&&e!==""?e:void 0;function vt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),environmentId:W(e.environment_id),signal:String(e.signal),enabled:Number(e.enabled)===1,sensitivity:String(e.sensitivity),seasonLength:Number(e.season_length),minAbsoluteDelta:Number(e.min_absolute_delta),detectDrops:Number(e.detect_drops)===1,severity:String(e.severity),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function mn(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),signal:W(e.signal),routePattern:W(e.route_pattern),statusCode:e.status_code==null?void 0:Number(e.status_code),reason:String(e.reason),actorId:W(e.actor_id),expiresAt:W(e.expires_at),createdAt:String(e.created_at)}}function un(e,t){if(e==="*"||e==="**")return!0;let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${r}$`).test(t)}class yt{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}upsert(e){let t=e.signal.trim();if(!t)throw Error("An anomaly config needs a signal.");if(e.seasonLength!=null&&(!Number.isInteger(e.seasonLength)||e.seasonLength<1))throw Error("seasonLength must be a positive integer.");let r=V(e.organizationId,e.projectId,e.environmentId),s=this.now(),n=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[r,t])[0],i=Ve(t);if(n)return this.controlPlane.database.run("UPDATE anomaly_configs SET enabled=?,sensitivity=?,season_length=?,min_absolute_delta=?,detect_drops=?,severity=?,version=version+1,updated_at=? WHERE id=?",[e.enabled===!1?0:1,e.sensitivity??String(n.sensitivity),e.seasonLength??Number(n.season_length),e.minAbsoluteDelta??Number(n.min_absolute_delta),e.detectDrops==null?Number(n.detect_drops):e.detectDrops?1:0,e.severity??String(n.severity),s,String(n.id)]),this.get(String(n.id));let E=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_configs (id,organization_id,project_id,environment_id,scope_key,signal,enabled,sensitivity,season_length,min_absolute_delta,detect_drops,severity,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[E,e.organizationId,e.projectId??null,e.environmentId??null,r,t,e.enabled===!1?0:1,e.sensitivity??"medium",e.seasonLength??i.seasonLength??24,e.minAbsoluteDelta??i.minAbsoluteDelta??0,e.detectDrops?1:0,e.severity??"warning",s,s]),this.get(E)}get(e){let t=this.query("SELECT * FROM anomaly_configs WHERE id = ?",[e])[0];return t?vt(t):void 0}list(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);return this.query(`SELECT * FROM anomaly_configs WHERE ${t.join(" AND ")} ORDER BY signal`,r).map(vt)}delete(e){return this.controlPlane.database.run("DELETE FROM anomaly_configs WHERE id = ?",[e]).changes>0}optionsFor(e,t){let r=[V(e.organizationId,e.projectId,e.environmentId),V(e.organizationId,e.projectId),V(e.organizationId)];for(let s of r){let n=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[s,t])[0];if(!n)continue;let i=vt(n);return{config:i,enabled:i.enabled,options:{...Ve(t),threshold:Ln[i.sensitivity],seasonLength:i.seasonLength,minAbsoluteDelta:i.minAbsoluteDelta,detectDrops:i.detectDrops}}}return{options:Ve(t),enabled:!0}}silence(e){let t=e.reason.trim();if(!t)throw Error("A silence needs a reason: someone will ask why this stopped alerting.");if(!e.signal&&!e.routePattern&&e.statusCode==null)throw Error("A silence needs at least one of signal, routePattern, or statusCode.");let r=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_silences (id,organization_id,project_id,scope_key,signal,route_pattern,status_code,reason,actor_id,expires_at,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId??null,V(e.organizationId,e.projectId),e.signal??null,e.routePattern??null,e.statusCode??null,t,e.actorId??null,e.expiresAt??null,this.now()]),this.listSilences({organizationId:e.organizationId}).find((s)=>s.id===r)}listSilences(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(!e.includeExpired)t.push("(expires_at IS NULL OR expires_at > ?)"),r.push(this.now());return this.query(`SELECT * FROM anomaly_silences WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(mn)}removeSilence(e){return this.controlPlane.database.run("DELETE FROM anomaly_silences WHERE id = ?",[e]).changes>0}isSilenced(e,t){return this.listSilences(e).find((r)=>{if(r.signal&&r.signal!==t.signal)return!1;if(r.statusCode!=null&&r.statusCode!==t.statusCode)return!1;if(r.routePattern){if(!t.route)return!1;if(!un(r.routePattern,t.route))return!1}return!0})}}var ue=[{key:"cost",routeAware:!1,label:"Cost",source:"usage",gapPolicy:"zero",minSamples:0,unit:"cents"},{key:"edge.requests",routeAware:!1,label:"Edge requests",source:"usage",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"edge.egress_gb",routeAware:!1,label:"Edge egress",source:"usage",gapPolicy:"zero",minSamples:0,unit:"GB"},{key:"function.invocations",routeAware:!1,label:"Function invocations",source:"usage",gapPolicy:"zero",minSamples:0,unit:"invocations"},{key:"http.requests",routeAware:!0,label:"HTTP requests",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"http.errors",routeAware:!0,label:"HTTP 5xx",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"responses"},{key:"http.error_rate",routeAware:!0,label:"HTTP error rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.client_error_rate",routeAware:!0,label:"HTTP 4xx rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.latency_p95",routeAware:!0,label:"Latency p95",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ms"}];function Dt(e){return ue.find((t)=>t.key===e)}var me=3600000;function Cn(e,t=960){let r=Math.floor(new Date(e.from).getTime()/me)*me,s=new Date(e.to).getTime(),n=[];for(let i=r;i<s&&n.length<t;i+=me)n.push(i);return n}function pt(e,t,r){let s=[],n=0,i=0;for(let E of Cn(t)){let a=r.get(E),d=new Date(E).toISOString();if(!a){s.push({bucketStart:d,value:e.gapPolicy==="zero"?0:Number.NaN});continue}if(a.samples<e.minSamples){s.push({bucketStart:d,value:Number.NaN}),i++;continue}s.push({bucketStart:d,value:a.value}),n++}return{signal:e.key,points:s,populated:n,suppressed:i,unit:e.unit}}class bt{controlPlane;spend;counterCache=new Map;constructor(e,t){this.controlPlane=e;this.spend=t}query(e,t){return this.controlPlane.database.query(e).all(...t)}usageSeries(e,t,r){let s=this.spend.summarizeUsage({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,meters:e.key==="cost"?void 0:[e.key],from:r.from,to:r.to}),n=new Map;for(let i of s.series)n.set(new Date(i.bucketStart).getTime(),{value:e.key==="cost"?i.costCents:i.quantity,samples:1});return pt(e,r,n)}requestFilter(e,t){let r=["project_id = ?","kind = 'request'","timestamp >= ?","timestamp < ?"],s=[e.projectId,t.from,t.to];if(e.environmentId)r.push("environment_id = ?"),s.push(e.environmentId);if(e.route)r.push("path_template = ?"),s.push(e.route);return{clauses:r,bindings:s}}counters(e,t){let r=[e.projectId,e.environmentId??"",e.route??"",t.from,t.to].join("\x00"),s=this.counterCache.get(r);if(s)return s;let{clauses:n,bindings:i}=this.requestFilter(e,t),E=this.query(`SELECT
|
|
1516
1516
|
CAST(strftime('%s', timestamp) AS INTEGER) / 3600 AS bucket,
|
|
1517
1517
|
COUNT(*) AS total,
|
|
1518
1518
|
SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) AS server_errors,
|
|
1519
1519
|
SUM(CASE WHEN status_code >= 400 AND status_code < 500 THEN 1 ELSE 0 END) AS client_errors
|
|
1520
1520
|
FROM telemetry_records
|
|
1521
|
-
WHERE ${
|
|
1521
|
+
WHERE ${n.join(" AND ")}
|
|
1522
1522
|
GROUP BY bucket
|
|
1523
|
-
ORDER BY bucket`,
|
|
1523
|
+
ORDER BY bucket`,i);return this.counterCache.set(r,E),E}resetCache(){this.counterCache.clear()}telemetrySeries(e,t,r){if(!t.projectId)return{signal:e.key,points:[],populated:0,suppressed:0,unit:e.unit};if(e.key==="http.latency_p95")return this.latencySeries(e,t,r);let s=this.counters(t,r),n=new Map;for(let i of s){let E=Number(i.bucket)*me,a=Number(i.total);if(e.key==="http.requests")n.set(E,{value:a,samples:a});else if(e.key==="http.errors")n.set(E,{value:Number(i.server_errors),samples:a});else if(e.key==="http.error_rate")n.set(E,{value:a>0?Number(i.server_errors)/a:0,samples:a});else if(e.key==="http.client_error_rate")n.set(E,{value:a>0?Number(i.client_errors)/a:0,samples:a})}return pt(e,r,n)}latencySeries(e,t,r){let{clauses:s,bindings:n}=this.requestFilter(t,r),i=this.query(`WITH ranked AS (
|
|
1524
1524
|
SELECT
|
|
1525
1525
|
CAST(strftime('%s', timestamp) AS INTEGER) / 3600 AS bucket,
|
|
1526
1526
|
duration_ms,
|
|
1527
1527
|
ROW_NUMBER() OVER (PARTITION BY CAST(strftime('%s', timestamp) AS INTEGER) / 3600 ORDER BY duration_ms) AS position,
|
|
1528
1528
|
COUNT(*) OVER (PARTITION BY CAST(strftime('%s', timestamp) AS INTEGER) / 3600) AS samples
|
|
1529
1529
|
FROM telemetry_records
|
|
1530
|
-
WHERE ${
|
|
1530
|
+
WHERE ${s.join(" AND ")} AND duration_ms IS NOT NULL
|
|
1531
1531
|
)
|
|
1532
1532
|
SELECT bucket, MIN(duration_ms) AS value, MAX(samples) AS samples
|
|
1533
1533
|
FROM ranked
|
|
1534
1534
|
WHERE position >= CAST(samples * 0.95 AS INTEGER)
|
|
1535
1535
|
GROUP BY bucket
|
|
1536
|
-
ORDER BY bucket`,
|
|
1537
|
-
WHERE ${
|
|
1538
|
-
GROUP BY path_template HAVING total >= ? ORDER BY total DESC LIMIT ?`,[...
|
|
1536
|
+
ORDER BY bucket`,n),E=new Map;for(let a of i)E.set(Number(a.bucket)*me,{value:Number(a.value),samples:Number(a.samples)});return pt(e,r,E)}series(e,t,r){let s=Dt(e);if(!s)return{signal:e,points:[],populated:0,suppressed:0,unit:""};return s.source==="usage"?this.usageSeries(s,t,r):this.telemetrySeries(s,t,r)}busiestRoutes(e,t,r=10,s=500){if(!e.projectId)return[];let n=["kind = 'request'","project_id = ?","timestamp >= ?","timestamp < ?","path_template IS NOT NULL"],i=[e.projectId,t.from,t.to];if(e.environmentId)n.push("environment_id = ?"),i.push(e.environmentId);return this.query(`SELECT path_template, COUNT(*) AS total FROM telemetry_records
|
|
1537
|
+
WHERE ${n.join(" AND ")}
|
|
1538
|
+
GROUP BY path_template HAVING total >= ? ORDER BY total DESC LIMIT ?`,[...i,s,Math.max(1,Math.min(50,r))]).map((E)=>String(E.path_template))}}function kt(e){let t={seasonLength:24,threshold:3.5,minHistory:3,minAbsoluteDelta:0,detectDrops:!1};if(e==="cost")return{...t,minAbsoluteDelta:25};if(e==="edge.requests"||e==="http.requests")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:1000,detectDrops:!0};if(e==="edge.egress_gb")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:5};if(e==="function.invocations")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:1000};if(e==="http.errors")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:25};if(e==="http.error_rate"||e==="http.client_error_rate")return{...t,seasonLength:168,threshold:3.5,minAbsoluteDelta:0.02};if(e==="http.latency_p95")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:100};return t}function xr(e){let t=kt(e),r=t.seasonLength*(t.minHistory+1);return Math.min(960,Math.max(336,r))}var gn="1.3";function Rn(e){if(e.startsWith("edge.")||e.startsWith("object.egress"))return"Networking";if(e.startsWith("function.")||e.startsWith("compute.")||e.startsWith("build."))return"Compute";if(e.startsWith("storage.")||e.startsWith("object."))return"Storage";if(e.startsWith("database."))return"Databases";if(e.startsWith("telemetry."))return"Management and Governance";return"Other"}function Mr(e){return ot[e]?.label??e}function jr(e){let t=ot[e]?.unit;if(t==="gb")return"GB";if(t==="gb_hours")return"GB-Hours";if(t==="gb_seconds")return"GB-Seconds";if(t==="hours")return"Hours";if(t==="minutes")return"Minutes";if(t==="requests")return"Requests";if(t==="invocations")return"Invocations";return"Count"}function On(e){return`${e.slice(0,10)}T00:00:00.000Z`}function An(e){return new Date(new Date(e).getTime()+86400000).toISOString()}function Un(e){return new Date(new Date(e).getTime()+3600000).toISOString()}function Br(e,t){let r=t.currency??"USD",s=(t.granularity??"daily")==="daily",n=new Map;for(let i of e){let E=s?On(i.bucketStart):i.bucketStart,a=[E,i.meter,i.provider,i.region,i.projectId,i.resourceId].join("\x00"),d=n.get(a);if(d)d.quantity+=i.quantity,d.costCents+=i.costCents;else n.set(a,{rollup:i,quantity:i.quantity,costCents:i.costCents,start:E})}return[...n.values()].sort((i,E)=>i.start.localeCompare(E.start)||String(i.rollup.meter).localeCompare(String(E.rollup.meter))).map(({rollup:i,quantity:E,costCents:a,start:d})=>{let T=Math.round(a)/100,N=i.provider||"ts-cloud";return{FocusVersion:gn,ChargePeriodStart:d,ChargePeriodEnd:s?An(d):Un(d),BillingPeriodStart:t.billingPeriodStart,BillingPeriodEnd:t.billingPeriodEnd,BillingCurrency:r,BilledCost:T,EffectiveCost:T,ListCost:T,ChargeCategory:"Usage",ChargeDescription:`${Mr(i.meter)} on ${N}`,ProviderName:N,PublisherName:N,InvoiceIssuerName:N,ServiceName:Mr(i.meter),ServiceCategory:Rn(String(i.meter)),SkuId:String(i.meter),PricingUnit:jr(String(i.meter)),PricingQuantity:E,ConsumedQuantity:E,ConsumedUnit:jr(String(i.meter)),RegionId:i.region||void 0,ResourceId:i.resourceId||void 0,SubAccountId:i.projectId||void 0,SubAccountName:i.projectId?t.projectNames?.[i.projectId]??i.projectId:void 0,Tags:{...i.environmentId?{environment:i.environmentId}:{},...i.projectId?{project:i.projectId}:{}}}})}function Ft(e){return e.map((t)=>JSON.stringify(t)).join(`
|
|
1539
1539
|
`)+(e.length>0?`
|
|
1540
|
-
`:"")}function*la(e,t=500){for(let r=0;r<e.length;r+=t)yield Pt(e.slice(r,r+t))}class xt{store;counters=new mt;breaching=new Map;anomalyConfigs;signals;constructor(e){this.store=e;this.anomalyConfigs=new Ut(e.controlPlane),this.signals=new kt(e.controlPlane,e)}ingestTelemetry(e,t,r){let n=_r(e,t,{counters:this.counters,defaultProvider:r});return this.store.ingestUsage(n)}ingestUsage(e,t=!0){return this.store.ingestUsage(t?hr(e):[...e])}status(e,t=new Date){let{window:r,summary:n}=this.store.budgetSpendCents(e,t),o=this.store.listEnforcements({organizationId:e.organizationId,budgetId:e.id,activeOnly:!0}).filter((a)=>a.state==="active").map((a)=>a.action),s=Dr({budget:e,window:r,actualCents:n.totalCents,series:n.series,activeActions:o,breachingSince:this.breaching.get(e.id),now:t});return{budget:e,decision:s,summary:n,activeActions:o,timeToCap:ge(s.projection.timeToExhaustionMs)}}async runCycle(e){let t=e.now??new Date,r=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId),n=[],i=[];for(let s of r){let a=this.status(s,t);this.trackBreach(s,a.decision,t),this.store.recordDecision(a.decision),n.push(a)}let o=wr(n.map((s)=>s.decision));if(e.handlers){let s={environmentKind:e.environmentKind,...e.policy};for(let a of n){let d=Xr(a.decision,s);if(d.apply.length===0&&d.release.length===0&&d.withheld.length===0)continue;i.push(await Pr(this.store,a.budget,a.decision,d,e.handlers))}}return{organizationId:e.organizationId,statuses:n,level:o.level,actions:o.actions,releases:o.releases,enforcement:i,anomalies:this.detectAnomalies(e,t),evaluatedAt:t.toISOString()}}trackBreach(e,t,r){if(!t.breaches.some((i)=>i.actions.some((o)=>o!=="notify"))){this.breaching.delete(e.id);return}if(!this.breaching.has(e.id))this.breaching.set(e.id,r.toISOString())}detectAnomalies(e,t=new Date,r={}){let n=new Date(Math.floor(t.getTime()/3600000)*3600000).toISOString(),i={organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId},o=e.signals??he.map((d)=>d.key),s=[],a;for(let d of o){let c=r.seasonLength?Math.max(336,r.seasonLength*((r.minHistory??3)+1)):Mr(d),p={from:new Date(new Date(n).getTime()-c*3600000).toISOString(),to:n};if(s.push(...this.detectSignal(d,i,p,r)),!e.routes)continue;if(!wt(d)?.routeAware)continue;a??=this.signals.busiestRoutes(i,p);for(let l of a){if(this.anomalyConfigs.isSilenced(i,{signal:d,route:l}))continue;s.push(...this.detectSignal(d,{...i,route:l},p,r,l))}}return this.signals.resetCache(),s}detectSignal(e,t,r,n,i){let o=this.anomalyConfigs.optionsFor(t,e);if(!o.enabled)return[];if(!i&&this.anomalyConfigs.isSilenced(t,{signal:e}))return[];let s=this.signals.series(e,t,r);if(s.points.length===0)return[];let a=Fr(s.points,{...Xt(e),...o.options,...n});if(!a)return[];let d=this.store.recordAnomaly({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,signal:i?`${e}@${i}`:e,direction:a.direction,observed:a.observed,expected:a.expected,score:a.score,deltaPercent:Number.isFinite(a.deltaPercent)?a.deltaPercent:0,severity:o.config?.severity??a.severity,bucketStart:a.bucketStart,evidence:{historySize:a.historySize,deviation:a.deviation,unit:s.unit,populatedBuckets:s.populated,suppressedBuckets:s.suppressed,route:i??null,lookbackFrom:r.from,lookbackTo:r.to}});return d?[d]:[]}usageReport(e){let t=e.now??new Date,r=Q(e.period??"monthly",e.timezone??"UTC",t),n=this.store.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,from:r.start,to:r.end}),i=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId).map((s)=>{let a=this.status(s,t),d=Qe(s);return{id:s.id,name:s.name,period:s.period,limitCents:d,softLimitCents:s.softLimitCents,hardLimitCents:s.hardLimitCents,spentCents:a.decision.projection.actualCents,remainingCents:d==null?null:Math.max(0,d-a.decision.projection.actualCents),usedPercent:a.decision.usedPercent,projectedCents:a.decision.projection.projectedCents,projectedPercent:a.decision.projectedPercent,projectionConfidence:a.decision.projection.confidence,level:a.decision.level,timeToCap:a.timeToCap,activeActions:a.activeActions,dryRun:s.dryRun}}),o=this.store.listEnforcements({organizationId:e.organizationId,activeOnly:!0});return{organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,window:{start:r.start,end:r.end,label:r.label},currency:this.store.priceBook.currency,totalCents:n.totalCents,byMeter:n.byMeter,series:n.series,budgets:i,enforcement:{strongestAction:xr(o)??null,active:o.map((s)=>({id:s.id,budgetId:s.budgetId,action:s.action,state:s.state,reason:s.reason,simulated:s.simulated,appliedAt:s.appliedAt}))},generatedAt:t.toISOString(),currentBucket:ue(t)}}}function ya(e,t,r,n=1440){let i=new Map(e.map((d)=>[d.bucketStart,d.value])),o=Math.floor(new Date(t).getTime()/3600000)*3600000,s=new Date(r).getTime(),a=[];for(let d=o;d<s&&a.length<n;d+=3600000){let c=new Date(d).toISOString();a.push({bucketStart:c,value:i.get(c)??0})}return a}var Br="spend.gates",Si={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};function We(e){return`${e.budgetId}:${e.action}`}function bi(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function Ri(e,t){if(e.organizationId!==t.organizationId)return!1;if(t.projectId&&e.projectId!==t.projectId)return!1;if(t.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function Ci(e){let t={...e};for(let r of["projectId","environmentId"])if(t[r]==null)delete t[r];return t}class Ne{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}read(){let e=this.controlPlane.getSetting(Br);return Array.isArray(e)?e:[]}write(e){this.controlPlane.setSetting(Br,e)}list(e){return this.read().filter((t)=>!e||bi(t,e)).sort((t,r)=>k[r.action]-k[t.action])}listUnder(e){return this.read().filter((t)=>Ri(t,e)).sort((t,r)=>k[r.action]-k[t.action])}open(e){let t=e.appliedAt??(this.options.now?.()??new Date).toISOString(),r=Ci({...e,appliedAt:t}),n=this.read().filter((i)=>We(i)!==We(r));return n.push(r),this.write(n),r}close(e,t){let r=this.read(),n=r.filter((i)=>We(i)!==We({budgetId:e,action:t}));if(n.length===r.length)return!1;return this.write(n),!0}closeBudget(e){let t=this.read(),r=t.filter((n)=>n.budgetId!==e);return this.write(r),t.length-r.length}check(e,t){let r=Si[e]??[];for(let n of this.list(t)){if(n.simulated)continue;if(!r.includes(n.action))continue;return{allowed:!1,action:n.action,budgetId:n.budgetId,reason:`${n.reason} ${Ye[n.action]}`}}return{allowed:!0}}strongest(e){return this.list(e).find((t)=>!t.simulated)?.action}}class Vr extends Error{operation;verdict;code="spend_cap_exceeded";status=402;constructor(e,t){super(t.reason??`A spend cap is blocking this ${e}.`);this.operation=e;this.verdict=t}}function Sa(e,t,r){let n=e.check(t,r);if(!n.allowed)throw new Vr(t,n)}var Kr=["notify","block_builds","block_deployments"];function $r(e){let t=e.throttleFactor??0.5;return{apply:async(i,o)=>{let{budget:s,record:a,decision:d}=o;e.gate.open({budgetId:s.id,action:i,organizationId:s.organizationId,projectId:s.projectId,environmentId:s.environmentId,reason:d.reason,simulated:a.simulated});let c={gated:!0};if(!a.simulated&&!Kr.includes(i)){let p={projectId:s.projectId,environmentId:s.environmentId},l=e.transport;if(i==="throttle_requests"&&l?.throttleRequests)c={...await l.throttleRequests({...p,factor:t}),gated:!0};else if(i==="suspend_functions"&&l?.suspendFunctions)c={...await l.suspendFunctions(p),gated:!0};else if(i==="serve_static"&&l?.serveStatic)c={...await l.serveStatic(p),gated:!0};else if(i==="suspend_project"&&l?.suspendProject)c={...await l.suspendProject(p),gated:!0};else c={gated:!0,unsupported:!0}}return await e.notify?.({action:i,budgetId:s.id,reason:d.reason,simulated:a.simulated,released:!1}),c},release:async(i,o)=>{let{budget:s,record:a,restore:d}=o,c=e.transport;if(!a.simulated&&!Kr.includes(i)&&d.unsupported!==!0){if(i==="throttle_requests"&&c?.restoreRequests)await c.restoreRequests(d);else if(i==="suspend_functions"&&c?.resumeFunctions)await c.resumeFunctions(d);else if(i==="serve_static"&&c?.restoreDynamic)await c.restoreDynamic(d);else if(i==="suspend_project"&&c?.resumeProject)await c.resumeProject(d)}e.gate.close(s.id,i),await e.notify?.({action:i,budgetId:s.id,reason:a.reason,simulated:a.simulated,released:!0})}}}class Ai{calls=[];record(e,t){return this.calls.push({method:e,input:t}),{recorded:e}}throttleRequests(e){return this.record("throttleRequests",e)}restoreRequests(e){this.record("restoreRequests",e)}suspendFunctions(e){return this.record("suspendFunctions",e)}resumeFunctions(e){this.record("resumeFunctions",e)}serveStatic(e){return this.record("serveStatic",e)}restoreDynamic(e){this.record("restoreDynamic",e)}suspendProject(e){return this.record("suspendProject",e)}resumeProject(e){this.record("resumeProject",e)}}import{createCipheriv as Oi,createDecipheriv as Ui,createHash as en,randomBytes as Di}from"node:crypto";var X=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},S=(e)=>typeof e==="string"?e:void 0,Mt=(e)=>Number(e)===1,M=(e,t,r,n)=>{let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,Math.floor(i))):t},Qr=(e)=>en("sha256").update(e).digest("hex").slice(0,16);function Yr(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:S(e.environment_id),resourceId:S(e.resource_id),name:String(e.name),kind:String(e.kind),target:String(e.target),config:X(e.config),intervalSeconds:Number(e.interval_seconds),timeoutSeconds:Number(e.timeout_seconds),failureThreshold:Number(e.failure_threshold),recoveryThreshold:Number(e.recovery_threshold),regions:X(e.regions),enabled:Mt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Gr(e){return{id:String(e.id),checkId:String(e.check_id),status:String(e.status),agent:String(e.agent),region:S(e.region),statusCode:e.status_code==null?void 0:Number(e.status_code),message:S(e.message),timings:X(e.timings),checkedAt:String(e.checked_at)}}function Wr(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:S(e.environment_id),resourceId:S(e.resource_id),healthCheckId:S(e.health_check_id),name:String(e.name),signal:String(e.signal),operator:String(e.operator),threshold:e.threshold==null?void 0:Number(e.threshold),recoveryThreshold:e.recovery_threshold==null?void 0:Number(e.recovery_threshold),windowMs:Number(e.window_ms),consecutive:Number(e.consecutive),recoveryConsecutive:Number(e.recovery_consecutive),noDataPolicy:String(e.no_data_policy),severity:String(e.severity),groupBy:X(e.group_by),labels:X(e.labels),enabled:Mt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function jt(e){return{id:String(e.id),ruleId:String(e.rule_id),projectId:String(e.project_id),environmentId:S(e.environment_id),resourceId:S(e.resource_id),dedupKey:String(e.dedup_key),groupKey:String(e.group_key),state:String(e.state),severity:String(e.severity),title:String(e.title),evidence:X(e.evidence),failureCount:Number(e.failure_count),recoveryCount:Number(e.recovery_count),occurrenceCount:Number(e.occurrence_count),ownerActorId:S(e.owner_actor_id),acknowledgedByActorId:S(e.acknowledged_by_actor_id),acknowledgedAt:S(e.acknowledged_at),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),firingAt:S(e.firing_at),resolvedAt:S(e.resolved_at),silencedUntil:S(e.silenced_until),updatedAt:String(e.updated_at)}}function Jr(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),kind:String(e.kind),config:X(e.config),credentialFingerprint:S(e.credential_fingerprint),hasCredential:!!e.credential_ciphertext,status:String(e.status),version:Number(e.version),lastTestedAt:S(e.last_tested_at),lastError:S(e.last_error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Zr(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),priority:Number(e.priority),matcher:X(e.matcher),channelIds:X(e.channel_ids),quietHours:e.quiet_hours?X(e.quiet_hours):void 0,groupWaitSeconds:Number(e.group_wait_seconds),reminderSeconds:e.reminder_seconds==null?void 0:Number(e.reminder_seconds),escalation:X(e.escalation),template:S(e.template),rateLimitPerMinute:Number(e.rate_limit_per_minute),enabled:Mt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ft(e){return{id:String(e.id),alertId:S(e.alert_id),channelId:String(e.channel_id),routeId:S(e.route_id),eventType:String(e.event_type),idempotencyKey:String(e.idempotency_key),state:String(e.state),attempt:Number(e.attempt),maxAttempts:Number(e.max_attempts),nextAttemptAt:S(e.next_attempt_at),responseStatus:e.response_status==null?void 0:Number(e.response_status),error:S(e.error),payload:X(e.payload),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deliveredAt:S(e.delivered_at)}}class wi{controlPlane;options;key;constructor(e,t){this.controlPlane=e;this.options=t;this.key=en("sha256").update(t.encryptionKey).digest()}now(){return(this.options.now?.()??new Date).toISOString()}encrypt(e){let t=Di(12),r=Oi("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]=e.split("."),i=Ui("aes-256-gcm",this.key,Buffer.from(t,"base64url"));return i.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([i.update(Buffer.from(n,"base64url")),i.final()]).toString("utf8")}createHealthCheck(e){if(!e.name.trim())throw Error("Health checks require a name.");if(!["http","tcp","command"].includes(e.kind))throw Error("Unsupported health check kind.");if(e.kind==="http"&&!/^https?:\/\//.test(e.target)||e.kind==="tcp"&&!/^[a-zA-Z0-9.-]+$/.test(e.target)||e.kind==="command"&&!e.config.command?.length)throw Error("Health check target is invalid.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO health_checks (id,project_id,environment_id,resource_id,name,kind,target,config,interval_seconds,timeout_seconds,failure_threshold,recovery_threshold,regions,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.name.trim().slice(0,100),e.kind,e.target,JSON.stringify(e.config),M(e.intervalSeconds,60,10,86400),M(e.timeoutSeconds,10,1,300),M(e.failureThreshold,3,1,100),M(e.recoveryThreshold,2,1,100),JSON.stringify(e.regions.slice(0,20)),e.enabled?1:0,1,r,r]),this.getHealthCheck(t)}getHealthCheck(e){let t=this.controlPlane.database.query("SELECT * FROM health_checks WHERE id=?").get(e);return t?Yr(t):void 0}listHealthChecks(e,t){return this.controlPlane.database.query(`SELECT * FROM health_checks WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(Yr)}setHealthCheckEnabled(e,t){this.controlPlane.database.run("UPDATE health_checks SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getHealthCheck(e);if(!r)throw Error("Health check was not found.");return r}appendHealthResult(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO health_results (id,check_id,status,agent,region,status_code,message,timings,checked_at) VALUES (?,?,?,?,?,?,?,?,?)",[t,e.checkId,e.status,e.agent.slice(0,100),e.region??null,e.statusCode??null,e.message?.slice(0,1000)??null,JSON.stringify(e.timings),e.checkedAt]),Gr(this.controlPlane.database.query("SELECT * FROM health_results WHERE id=?").get(t))}listHealthResults(e,t=100){return this.controlPlane.database.query("SELECT * FROM health_results WHERE check_id=? ORDER BY checked_at DESC LIMIT ?").all(e,Math.min(1000,Math.max(1,t))).map(Gr)}createRule(e){if(!e.name.trim())throw Error("Alert rules require a name.");if(e.operator!=="unhealthy"&&e.threshold==null)throw Error("Metric alert rules require a threshold.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO alert_rules (id,project_id,environment_id,resource_id,health_check_id,name,signal,operator,threshold,recovery_threshold,window_ms,consecutive,recovery_consecutive,no_data_policy,severity,group_by,labels,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.healthCheckId??null,e.name.trim().slice(0,120),e.signal,e.operator,e.threshold??null,e.recoveryThreshold??null,M(e.windowMs,300000,1e4,2678400000),M(e.consecutive,3,1,100),M(e.recoveryConsecutive,2,1,100),e.noDataPolicy,e.severity,JSON.stringify(e.groupBy.slice(0,20)),JSON.stringify(e.labels),e.enabled?1:0,1,r,r]),this.getRule(t)}getRule(e){let t=this.controlPlane.database.query("SELECT * FROM alert_rules WHERE id=?").get(e);return t?Wr(t):void 0}listRules(e,t){return this.controlPlane.database.query(`SELECT * FROM alert_rules WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(Wr)}setRuleEnabled(e,t){this.controlPlane.database.run("UPDATE alert_rules SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRule(e);if(!r)throw Error("Alert rule was not found.");return r}getAlertByDedup(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE dedup_key=?").get(e);return t?jt(t):void 0}getAlert(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE id=?").get(e);return t?jt(t):void 0}listAlerts(e,t={}){let r=["project_id=?"],n=[e];if(t.environmentId)r.push("environment_id=?"),n.push(t.environmentId);if(t.states?.length)r.push(`state IN (${t.states.map(()=>"?").join(",")})`),n.push(...t.states);return this.controlPlane.database.query(`SELECT * FROM alerts WHERE ${r.join(" AND ")} ORDER BY updated_at DESC LIMIT ?`).all(...n,Math.min(1000,t.limit??200)).map(jt)}saveAlert(e,t,r){return this.controlPlane.database.run("INSERT INTO alerts (id,rule_id,project_id,environment_id,resource_id,dedup_key,group_key,state,severity,title,evidence,failure_count,recovery_count,occurrence_count,owner_actor_id,acknowledged_by_actor_id,acknowledged_at,first_seen_at,last_seen_at,firing_at,resolved_at,silenced_until,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,severity=excluded.severity,title=excluded.title,evidence=excluded.evidence,failure_count=excluded.failure_count,recovery_count=excluded.recovery_count,occurrence_count=excluded.occurrence_count,owner_actor_id=excluded.owner_actor_id,acknowledged_by_actor_id=excluded.acknowledged_by_actor_id,acknowledged_at=excluded.acknowledged_at,last_seen_at=excluded.last_seen_at,firing_at=excluded.firing_at,resolved_at=excluded.resolved_at,silenced_until=excluded.silenced_until,updated_at=excluded.updated_at",[e.id,e.ruleId,e.projectId,e.environmentId??null,e.resourceId??null,e.dedupKey,e.groupKey,e.state,e.severity,e.title,JSON.stringify(e.evidence),e.failureCount,e.recoveryCount,e.occurrenceCount,e.ownerActorId??null,e.acknowledgedByActorId??null,e.acknowledgedAt??null,e.firstSeenAt,e.lastSeenAt,e.firingAt??null,e.resolvedAt??null,e.silencedUntil??null,e.updatedAt]),this.controlPlane.database.run("INSERT INTO alert_events (id,alert_id,type,actor_id,payload,created_at) VALUES (?,?,?,?,?,?)",[crypto.randomUUID(),e.id,t,r??null,JSON.stringify({state:e.state,severity:e.severity,evidence:e.evidence}),e.updatedAt]),this.getAlert(e.id)}acknowledge(e,t){let r=this.getAlert(e);if(!r)throw Error("Alert was not found.");let n=this.now();return this.saveAlert({...r,acknowledgedByActorId:t,acknowledgedAt:n,updatedAt:n},"acknowledged",t)}assign(e,t,r){let n=this.getAlert(e);if(!n)throw Error("Alert was not found.");let i=this.now();return this.saveAlert({...n,ownerActorId:t,updatedAt:i},"assigned",r)}silenceAlert(e,t,r){let n=this.getAlert(e);if(!n)throw Error("Alert was not found.");let i=new Date(t);if(!Number.isFinite(i.getTime())||i<=new Date)throw Error("Silence end must be in the future.");let o=this.now();return this.saveAlert({...n,state:"silenced",silencedUntil:i.toISOString(),updatedAt:o},"silenced",r)}createSilence(e){let t=new Date(e.startsAt),r=new Date(e.endsAt);if(!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime())||t>=r)throw Error("Silence window is invalid.");try{new Intl.DateTimeFormat("en",{timeZone:e.timezone}).format(t)}catch{throw Error("Silence timezone is invalid.")}let n=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO alert_silences (id,project_id,environment_id,resource_id,matcher,reason,starts_at,ends_at,timezone,created_by_actor_id,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[n,e.projectId,e.environmentId??null,e.resourceId??null,JSON.stringify(e.matcher??{}),e.reason.slice(0,500),t.toISOString(),r.toISOString(),e.timezone,e.actorId??null,this.now()]),n}isSilenced(e,t,r){return this.controlPlane.database.query("SELECT * FROM alert_silences WHERE project_id=? AND starts_at<=? AND ends_at>?").all(e.projectId,r,r).some((i)=>{if(i.environment_id&&i.environment_id!==e.environmentId)return!1;if(i.resource_id&&i.resource_id!==e.resourceId)return!1;let o=X(i.matcher);return Object.entries(o).every(([s,a])=>t[s]===a)})}createChannel(e){if(!e.name.trim())throw Error("Notification channels require a name.");let t=crypto.randomUUID(),r=this.now(),n=e.credential?.trim();return this.controlPlane.database.run("INSERT INTO notification_channels (id,organization_id,name,kind,config,credential_ciphertext,credential_fingerprint,status,version,created_by_actor_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.kind,JSON.stringify(e.config??{}),n?this.encrypt(n):null,n?Qr(n):null,"active",1,e.actorId??null,r,r]),this.getChannel(t)}getChannel(e){let t=this.controlPlane.database.query("SELECT * FROM notification_channels WHERE id=?").get(e);return t?Jr(t):void 0}channelCredential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM notification_channels WHERE id=?").get(e);return t?.credential_ciphertext?this.decrypt(String(t.credential_ciphertext)):void 0}listChannels(e){return this.controlPlane.database.query("SELECT * FROM notification_channels WHERE organization_id=? ORDER BY updated_at DESC").all(e).map(Jr)}rotateChannel(e,t){let r=this.now();this.controlPlane.database.run("UPDATE notification_channels SET credential_ciphertext=?,credential_fingerprint=?,status='active',last_error=NULL,version=version+1,updated_at=? WHERE id=?",[this.encrypt(t),Qr(t),r,e]);let n=this.getChannel(e);if(!n)throw Error("Notification channel was not found.");return n}setChannelStatus(e,t,r){this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_error=?,updated_at=? WHERE id=?",[t,r?.slice(0,1000)??null,this.now(),e]);let n=this.getChannel(e);if(!n)throw Error("Notification channel was not found.");return n}markChannelTest(e,t,r){let n=this.now();return this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_tested_at=?,last_error=?,updated_at=? WHERE id=?",[t?"active":"failing",n,r?.slice(0,1000)??null,n,e]),this.getChannel(e)}createRoute(e){let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO notification_routes (id,organization_id,name,priority,matcher,channel_ids,quiet_hours,group_wait_seconds,reminder_seconds,escalation,template,rate_limit_per_minute,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.priority,JSON.stringify(e.matcher),JSON.stringify(e.channelIds),e.quietHours?JSON.stringify(e.quietHours):null,M(e.groupWaitSeconds,30,0,86400),e.reminderSeconds??null,JSON.stringify(e.escalation),e.template?.trim().slice(0,2000)??null,M(e.rateLimitPerMinute,60,1,1e4),e.enabled?1:0,1,r,r]),this.getRoute(t)}getRoute(e){let t=this.controlPlane.database.query("SELECT * FROM notification_routes WHERE id=?").get(e);return t?Zr(t):void 0}listRoutes(e){return this.controlPlane.database.query("SELECT * FROM notification_routes WHERE organization_id=? ORDER BY priority DESC,created_at ASC").all(e).map(Zr)}countRouteDeliveries(e,t){return Number(this.controlPlane.database.query("SELECT COUNT(*) count FROM notification_deliveries WHERE route_id=? AND created_at>=?").get(e,t)?.count??0)}setRouteEnabled(e,t){this.controlPlane.database.run("UPDATE notification_routes SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRoute(e);if(!r)throw Error("Notification route was not found.");return r}createDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return Ft(t);let r=crypto.randomUUID(),n=this.now();return this.controlPlane.database.run("INSERT INTO notification_deliveries (id,alert_id,channel_id,route_id,event_type,idempotency_key,state,attempt,max_attempts,next_attempt_at,payload,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.alertId??null,e.channelId,e.routeId??null,e.eventType,e.idempotencyKey,"pending",0,M(e.maxAttempts,3,1,10),e.nextAttemptAt??null,JSON.stringify(e.payload),n,n]),this.getDelivery(r)}getDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE id=?").get(e);return t?Ft(t):void 0}listDeliveries(e={}){let t=[],r=[];if(e.alertId)t.push("alert_id=?"),r.push(e.alertId);if(e.states?.length)t.push(`state IN (${e.states.map(()=>"?").join(",")})`),r.push(...e.states);return this.controlPlane.database.query(`SELECT * FROM notification_deliveries${t.length?" WHERE "+t.join(" AND "):""} ORDER BY updated_at DESC LIMIT ?`).all(...r,Math.min(1000,e.limit??200)).map(Ft)}updateDelivery(e,t){return this.controlPlane.database.run("UPDATE notification_deliveries SET state=?,attempt=?,next_attempt_at=?,response_status=?,error=?,delivered_at=?,updated_at=? WHERE id=?",[t.state,t.attempt,t.nextAttemptAt??null,t.responseStatus??null,t.error?.slice(0,1000)??null,t.deliveredAt??null,this.now(),e]),this.getDelivery(e)}}import{createHash as ki}from"node:crypto";function Xi(e,t,r){if(e==="gt")return t>r;if(e==="gte")return t>=r;if(e==="lt")return t<r;if(e==="lte")return t<=r;return t===r}function Pi(e,t,r){if(t.status==="no_data"||t.status==null&&t.value==null)return;if(e.operator==="unhealthy")return t.status==="unhealthy";if(t.value==null||e.threshold==null)return;return Xi(e.operator,t.value,r&&e.recoveryThreshold!=null?e.recoveryThreshold:e.threshold)}function xi(e,t){let r=Object.fromEntries(e.groupBy.flatMap((i)=>t.group?.[i]==null?[]:[[i,String(t.group[i])]]));return{key:Object.entries(r).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${i}=${o}`).join(",")||"default",values:r}}function ji(e,t){return ki("sha256").update(`${e}\x00${t}`).digest("hex")}class fe{store;constructor(e){this.store=e}evaluate(e,t){if(!e.enabled)return{transition:"ignored",notify:!1};let r=xi(e,t),n=ji(e.id,r.key),i=this.store.getAlertByDedup(n),o=i?.state==="firing"||i?.state==="silenced",s=Pi(e,t,o);if(s==null&&e.noDataPolicy==="ignore")return{alert:i,transition:"ignored",notify:!1};let a=s??e.noDataPolicy==="firing",d=s==null&&e.noDataPolicy==="pending",c=new Date(t.timestamp).toISOString(),p=I({...t.evidence??{},...t.value==null?{}:{value:t.value},...t.status?{healthStatus:t.status}:{},group:r.values}),l;if(!i){let T=a||d?1:0,_=a&&T>=e.consecutive?"firing":"pending";l={id:crypto.randomUUID(),ruleId:e.id,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,dedupKey:n,groupKey:r.key,state:_,severity:e.severity,title:e.name,evidence:p,failureCount:T,recoveryCount:0,occurrenceCount:1,firstSeenAt:c,lastSeenAt:c,firingAt:_==="firing"?c:void 0,updatedAt:c}}else if(a||d){let T=i.state==="resolved",_=(T?0:i.failureCount)+1,h=i.silencedUntil&&new Date(i.silencedUntil)>new Date(c),N=d?"pending":_>=e.consecutive?"firing":"pending";if((h||this.store.isSilenced(e,r.values,c))&&N==="firing")N="silenced";l={...i,state:N,severity:e.severity,title:e.name,evidence:p,failureCount:_,recoveryCount:0,occurrenceCount:i.occurrenceCount+1,firstSeenAt:T?c:i.firstSeenAt,lastSeenAt:c,firingAt:N==="firing"||N==="silenced"?i.firingAt??c:void 0,resolvedAt:void 0,updatedAt:c}}else{let T=i.recoveryCount+1,_=T>=e.recoveryConsecutive;l={...i,state:_?"resolved":i.state,evidence:p,failureCount:_?0:i.failureCount,recoveryCount:T,lastSeenAt:c,resolvedAt:_?c:i.resolvedAt,silencedUntil:_?void 0:i.silencedUntil,updatedAt:c}}let u=i?.state!==l.state,m=l.state==="pending"?"pending":l.state==="firing"?u?"firing":"updated":l.state==="silenced"?"silenced":u?"resolved":"updated";return{alert:this.store.saveAlert(l,u||!i?m:"observed"),transition:m,notify:m==="firing"||m==="resolved"}}}import{createHmac as Fi}from"node:crypto";function Mi(e,t){let r=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e).map((i)=>[i.type,i.value])),n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{minute:Number(r.hour)*60+Number(r.minute),weekday:n.indexOf(r.weekday)}}function tn(e){let t=/^(\d{2}):(\d{2})$/.exec(e);if(!t)throw Error("Quiet hours require HH:MM times.");let r=Number(t[1])*60+Number(t[2]);if(Number(t[1])>23||Number(t[2])>59)throw Error("Quiet hours require valid HH:MM times.");return r}function qt(e,t){if(!e.quietHours)return!1;let r=Mi(t,e.quietHours.timezone),n=tn(e.quietHours.start),i=tn(e.quietHours.end);if(e.quietHours.weekdays?.length&&!e.quietHours.weekdays.includes(r.weekday))return!1;return n<=i?r.minute>=n&&r.minute<i:r.minute>=n||r.minute<i}function zi(e,t,r){let n=e.matcher;return(!n.projectIds?.length||n.projectIds.includes(t.projectId))&&(!n.environmentIds?.length||!!t.environmentId&&n.environmentIds.includes(t.environmentId))&&(!n.resourceIds?.length||!!t.resourceId&&n.resourceIds.includes(t.resourceId))&&(!n.severities?.length||n.severities.includes(t.severity))&&(!n.eventTypes?.length||n.eventTypes.includes(r))}function qi(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"?t:{value:e}}catch{return{value:e}}}function Hi(e,t,r){let n={severity:e.severity.toUpperCase(),title:e.title,state:e.state,event:t,projectId:e.projectId,environmentId:e.environmentId??"",resourceId:e.resourceId??"",groupKey:e.groupKey};return(r?.trim()||"[{{severity}}] {{title}} · {{state}}").replace(/\{\{(severity|title|state|event|projectId|environmentId|resourceId|groupKey)\}\}/g,(i,o)=>n[o]).slice(0,2000)}function zt(e,t,r){return{schemaVersion:1,event:t,notificationText:Hi(e,t,r),alert:{id:e.id,state:e.state,severity:e.severity,title:e.title,projectId:e.projectId,environmentId:e.environmentId??null,resourceId:e.resourceId??null,groupKey:e.groupKey,firstSeenAt:e.firstSeenAt,lastSeenAt:e.lastSeenAt,firingAt:e.firingAt??null,resolvedAt:e.resolvedAt??null,evidence:e.evidence}}}class Bi{store;options;fetchImpl;constructor(e,t={}){this.store=e;this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch}now(){return this.options.now?.()??new Date}preview(e,t,r){let n=[];for(let i of this.store.listRoutes(e)){if(!i.enabled||!zi(i,t,r))continue;let o=[];for(let s of i.channelIds){let a=this.store.getChannel(s);if(a?.status==="active")o.push(a)}n.push({route:i,channels:o,quiet:qt(i,this.now())})}return n}enqueue(e,t,r){let n=r==="resolved"?t.resolvedAt:r==="firing"?t.firingAt:t.updatedAt,i=[];for(let o of this.preview(e,t,r)){if(o.quiet&&r!=="resolved")continue;let s=r==="resolved"||o.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+o.route.groupWaitSeconds*1000).toISOString(),a=r==="resolved"?Number.POSITIVE_INFINITY:Math.max(0,o.route.rateLimitPerMinute-this.store.countRouteDeliveries(o.route.id,new Date(this.now().getTime()-60000).toISOString()));for(let d of o.channels){if(a<=0)break;i.push(this.store.createDelivery({alertId:t.id,channelId:d.id,routeId:o.route.id,eventType:r,idempotencyKey:`${t.id}:${r}:${n}:${d.id}`,payload:zt(t,r,o.route.template),nextAttemptAt:s})),a--}}return i}enqueueRemindersAndEscalations(e,t){let r=this.now(),n=[];for(let i of t.filter((o)=>o.state==="firing"&&!o.acknowledgedAt&&o.firingAt)){let o=Math.max(0,(r.getTime()-new Date(i.firingAt).getTime())/1000);for(let s of this.preview(e,i,"reminder")){if(s.quiet)continue;if(s.route.reminderSeconds&&o>=s.route.reminderSeconds){let a=Math.floor(o/s.route.reminderSeconds);for(let d of s.channels)n.push(this.store.createDelivery({alertId:i.id,channelId:d.id,routeId:s.route.id,eventType:"reminder",idempotencyKey:`${i.id}:reminder:${s.route.id}:${a}:${d.id}`,payload:zt(i,"reminder")}))}for(let[a,d]of s.route.escalation.entries())if(o>=d.afterSeconds){for(let c of d.channelIds)if(this.store.getChannel(c)?.status==="active")n.push(this.store.createDelivery({alertId:i.id,channelId:c,routeId:s.route.id,eventType:"escalation",idempotencyKey:`${i.id}:escalation:${s.route.id}:${a}:${c}`,payload:zt(i,"escalation")}))}}}return n}async send(e,t){let r=qi(this.store.channelCredential(e.id)),n=typeof t.notificationText==="string"?t.notificationText:`[${String(t.alert?.severity??"info").toUpperCase()}] ${String(t.alert?.title??"ts-cloud alert")} · ${String(t.alert?.state??t.event)}`;try{if(e.kind==="email"){if(!this.options.emailImpl)return{ok:!1,error:"Email adapter is not configured."};return await this.options.emailImpl({to:e.config.to,from:e.config.from,subject:`[ts-cloud] ${String(t.alert?.title??t.event)}`,text:`${n}
|
|
1540
|
+
`:"")}function*da(e,t=500){for(let r=0;r<e.length;r+=t)yield Ft(e.slice(r,r+t))}class Pt{store;counters=new _t;breaching=new Map;anomalyConfigs;signals;constructor(e){this.store=e;this.anomalyConfigs=new yt(e.controlPlane),this.signals=new bt(e.controlPlane,e)}ingestTelemetry(e,t,r){let s=mr(e,t,{counters:this.counters,defaultProvider:r});return this.store.ingestUsage(s)}ingestUsage(e,t=!0){return this.store.ingestUsage(t?ur(e):[...e])}status(e,t=new Date){let{window:r,summary:s}=this.store.budgetSpendCents(e,t),i=this.store.listEnforcements({organizationId:e.organizationId,budgetId:e.id,activeOnly:!0}).filter((a)=>a.state==="active").map((a)=>a.action),E=pr({budget:e,window:r,actualCents:s.totalCents,series:s.series,activeActions:i,breachingSince:this.breaching.get(e.id),now:t});return{budget:e,decision:E,summary:s,activeActions:i,timeToCap:Le(E.projection.timeToExhaustionMs)}}async runCycle(e){let t=e.now??new Date,r=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId),s=[],n=[];for(let E of r){let a=this.status(E,t);this.trackBreach(E,a.decision,t),this.store.recordDecision(a.decision),s.push(a)}let i=Dr(s.map((E)=>E.decision));if(e.handlers){let E={environmentKind:e.environmentKind,...e.policy};for(let a of s){let d=kr(a.decision,E);if(d.apply.length===0&&d.release.length===0&&d.withheld.length===0)continue;n.push(await Fr(this.store,a.budget,a.decision,d,e.handlers))}}return{organizationId:e.organizationId,statuses:s,level:i.level,actions:i.actions,releases:i.releases,enforcement:n,anomalies:this.detectAnomalies(e,t),evaluatedAt:t.toISOString()}}trackBreach(e,t,r){if(!t.breaches.some((n)=>n.actions.some((i)=>i!=="notify"))){this.breaching.delete(e.id);return}if(!this.breaching.has(e.id))this.breaching.set(e.id,r.toISOString())}detectAnomalies(e,t=new Date,r={}){let s=new Date(Math.floor(t.getTime()/3600000)*3600000).toISOString(),n={organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId},i=e.signals??ue.map((d)=>d.key),E=[],a;for(let d of i){let T=r.seasonLength?Math.max(336,r.seasonLength*((r.minHistory??3)+1)):xr(d),N={from:new Date(new Date(s).getTime()-T*3600000).toISOString(),to:s};if(E.push(...this.detectSignal(d,n,N,r)),!e.routes)continue;if(!Dt(d)?.routeAware)continue;a??=this.signals.busiestRoutes(n,N);for(let o of a){if(this.anomalyConfigs.isSilenced(n,{signal:d,route:o}))continue;E.push(...this.detectSignal(d,{...n,route:o},N,r,o))}}return this.signals.resetCache(),E}detectSignal(e,t,r,s,n){let i=this.anomalyConfigs.optionsFor(t,e);if(!i.enabled)return[];if(!n&&this.anomalyConfigs.isSilenced(t,{signal:e}))return[];let E=this.signals.series(e,t,r);if(E.points.length===0)return[];let a=Kr(E.points,{...kt(e),...i.options,...s});if(!a)return[];let d=this.store.recordAnomaly({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,signal:n?`${e}@${n}`:e,direction:a.direction,observed:a.observed,expected:a.expected,score:a.score,deltaPercent:Number.isFinite(a.deltaPercent)?a.deltaPercent:0,severity:i.config?.severity??a.severity,bucketStart:a.bucketStart,evidence:{historySize:a.historySize,deviation:a.deviation,unit:E.unit,populatedBuckets:E.populated,suppressedBuckets:E.suppressed,route:n??null,lookbackFrom:r.from,lookbackTo:r.to}});return d?[d]:[]}usageReport(e){let t=e.now??new Date,r=G(e.period??"monthly",e.timezone??"UTC",t),s=this.store.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,from:r.start,to:r.end}),n=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId).map((E)=>{let a=this.status(E,t),d=Ge(E);return{id:E.id,name:E.name,period:E.period,limitCents:d,softLimitCents:E.softLimitCents,hardLimitCents:E.hardLimitCents,spentCents:a.decision.projection.actualCents,remainingCents:d==null?null:Math.max(0,d-a.decision.projection.actualCents),usedPercent:a.decision.usedPercent,projectedCents:a.decision.projection.projectedCents,projectedPercent:a.decision.projectedPercent,projectionConfidence:a.decision.projection.confidence,level:a.decision.level,timeToCap:a.timeToCap,activeActions:a.activeActions,dryRun:E.dryRun}}),i=this.store.listEnforcements({organizationId:e.organizationId,activeOnly:!0});return{organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,window:{start:r.start,end:r.end,label:r.label},currency:this.store.priceBook.currency,totalCents:s.totalCents,byMeter:s.byMeter,series:s.series,budgets:n,enforcement:{strongestAction:Pr(i)??null,active:i.map((E)=>({id:E.id,budgetId:E.budgetId,action:E.action,state:E.state,reason:E.reason,simulated:E.simulated,appliedAt:E.appliedAt}))},generatedAt:t.toISOString(),currentBucket:oe(t)}}}function ga(e,t,r,s=1440){let n=new Map(e.map((d)=>[d.bucketStart,d.value])),i=Math.floor(new Date(t).getTime()/3600000)*3600000,E=new Date(r).getTime(),a=[];for(let d=i;d<E&&a.length<s;d+=3600000){let T=new Date(d).toISOString();a.push({bucketStart:T,value:n.get(T)??0})}return a}var $r="spend.gates",hn={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};function We(e){return`${e.budgetId}:${e.action}`}function fn(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function Sn(e,t){if(e.organizationId!==t.organizationId)return!1;if(t.projectId&&e.projectId!==t.projectId)return!1;if(t.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function Xn(e){let t={...e};for(let r of["projectId","environmentId"])if(t[r]==null)delete t[r];return t}class Ce{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}read(){let e=this.controlPlane.getSetting($r);return Array.isArray(e)?e:[]}write(e){this.controlPlane.setSetting($r,e)}list(e){return this.read().filter((t)=>!e||fn(t,e)).sort((t,r)=>k[r.action]-k[t.action])}listUnder(e){return this.read().filter((t)=>Sn(t,e)).sort((t,r)=>k[r.action]-k[t.action])}open(e){let t=e.appliedAt??(this.options.now?.()??new Date).toISOString(),r=Xn({...e,appliedAt:t}),s=this.read().filter((n)=>We(n)!==We(r));return s.push(r),this.write(s),r}close(e,t){let r=this.read(),s=r.filter((n)=>We(n)!==We({budgetId:e,action:t}));if(s.length===r.length)return!1;return this.write(s),!0}closeBudget(e){let t=this.read(),r=t.filter((s)=>s.budgetId!==e);return this.write(r),t.length-r.length}check(e,t){let r=hn[e]??[];for(let s of this.list(t)){if(s.simulated)continue;if(!r.includes(s.action))continue;return{allowed:!1,action:s.action,budgetId:s.budgetId,reason:`${s.reason} ${Qe[s.action]}`}}return{allowed:!0}}strongest(e){return this.list(e).find((t)=>!t.simulated)?.action}}class qr extends Error{operation;verdict;code="spend_cap_exceeded";status=402;constructor(e,t){super(t.reason??`A spend cap is blocking this ${e}.`);this.operation=e;this.verdict=t}}function Ua(e,t,r){let s=e.check(t,r);if(!s.allowed)throw new qr(t,s)}var Yr=["notify","block_builds","block_deployments"];function zr(e){let t=e.throttleFactor??0.5;return{apply:async(n,i)=>{let{budget:E,record:a,decision:d}=i;e.gate.open({budgetId:E.id,action:n,organizationId:E.organizationId,projectId:E.projectId,environmentId:E.environmentId,reason:d.reason,simulated:a.simulated});let T={gated:!0};if(!a.simulated&&!Yr.includes(n)){let N={projectId:E.projectId,environmentId:E.environmentId},o=e.transport;if(n==="throttle_requests"&&o?.throttleRequests)T={...await o.throttleRequests({...N,factor:t}),gated:!0};else if(n==="suspend_functions"&&o?.suspendFunctions)T={...await o.suspendFunctions(N),gated:!0};else if(n==="serve_static"&&o?.serveStatic)T={...await o.serveStatic(N),gated:!0};else if(n==="suspend_project"&&o?.suspendProject)T={...await o.suspendProject(N),gated:!0};else T={gated:!0,unsupported:!0}}return await e.notify?.({action:n,budgetId:E.id,reason:d.reason,simulated:a.simulated,released:!1}),T},release:async(n,i)=>{let{budget:E,record:a,restore:d}=i,T=e.transport;if(!a.simulated&&!Yr.includes(n)&&d.unsupported!==!0){if(n==="throttle_requests"&&T?.restoreRequests)await T.restoreRequests(d);else if(n==="suspend_functions"&&T?.resumeFunctions)await T.resumeFunctions(d);else if(n==="serve_static"&&T?.restoreDynamic)await T.restoreDynamic(d);else if(n==="suspend_project"&&T?.resumeProject)await T.resumeProject(d)}e.gate.close(E.id,n),await e.notify?.({action:n,budgetId:E.id,reason:a.reason,simulated:a.simulated,released:!0})}}}class In{calls=[];record(e,t){return this.calls.push({method:e,input:t}),{recorded:e}}throttleRequests(e){return this.record("throttleRequests",e)}restoreRequests(e){this.record("restoreRequests",e)}suspendFunctions(e){return this.record("suspendFunctions",e)}resumeFunctions(e){this.record("resumeFunctions",e)}serveStatic(e){return this.record("serveStatic",e)}restoreDynamic(e){this.record("restoreDynamic",e)}suspendProject(e){return this.record("suspendProject",e)}resumeProject(e){this.record("resumeProject",e)}}import{createCipheriv as vn,createDecipheriv as yn,createHash as wr,randomBytes as pn}from"node:crypto";var F=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},f=(e)=>typeof e==="string"?e:void 0,xt=(e)=>Number(e)===1,M=(e,t,r,s)=>{let n=Number(e);return Number.isFinite(n)?Math.min(s,Math.max(r,Math.floor(n))):t},Gr=(e)=>wr("sha256").update(e).digest("hex").slice(0,16);function Qr(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:f(e.environment_id),resourceId:f(e.resource_id),name:String(e.name),kind:String(e.kind),target:String(e.target),config:F(e.config),intervalSeconds:Number(e.interval_seconds),timeoutSeconds:Number(e.timeout_seconds),failureThreshold:Number(e.failure_threshold),recoveryThreshold:Number(e.recovery_threshold),regions:F(e.regions),enabled:xt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Vr(e){return{id:String(e.id),checkId:String(e.check_id),status:String(e.status),agent:String(e.agent),region:f(e.region),statusCode:e.status_code==null?void 0:Number(e.status_code),message:f(e.message),timings:F(e.timings),checkedAt:String(e.checked_at)}}function Wr(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:f(e.environment_id),resourceId:f(e.resource_id),healthCheckId:f(e.health_check_id),name:String(e.name),signal:String(e.signal),operator:String(e.operator),threshold:e.threshold==null?void 0:Number(e.threshold),recoveryThreshold:e.recovery_threshold==null?void 0:Number(e.recovery_threshold),windowMs:Number(e.window_ms),consecutive:Number(e.consecutive),recoveryConsecutive:Number(e.recovery_consecutive),noDataPolicy:String(e.no_data_policy),severity:String(e.severity),groupBy:F(e.group_by),labels:F(e.labels),enabled:xt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ht(e){return{id:String(e.id),ruleId:String(e.rule_id),projectId:String(e.project_id),environmentId:f(e.environment_id),resourceId:f(e.resource_id),dedupKey:String(e.dedup_key),groupKey:String(e.group_key),state:String(e.state),severity:String(e.severity),title:String(e.title),evidence:F(e.evidence),failureCount:Number(e.failure_count),recoveryCount:Number(e.recovery_count),occurrenceCount:Number(e.occurrence_count),ownerActorId:f(e.owner_actor_id),acknowledgedByActorId:f(e.acknowledged_by_actor_id),acknowledgedAt:f(e.acknowledged_at),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),firingAt:f(e.firing_at),resolvedAt:f(e.resolved_at),silencedUntil:f(e.silenced_until),updatedAt:String(e.updated_at)}}function Jr(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),kind:String(e.kind),config:F(e.config),credentialFingerprint:f(e.credential_fingerprint),hasCredential:!!e.credential_ciphertext,status:String(e.status),version:Number(e.version),lastTestedAt:f(e.last_tested_at),lastError:f(e.last_error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Zr(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),priority:Number(e.priority),matcher:F(e.matcher),channelIds:F(e.channel_ids),quietHours:e.quiet_hours?F(e.quiet_hours):void 0,groupWaitSeconds:Number(e.group_wait_seconds),reminderSeconds:e.reminder_seconds==null?void 0:Number(e.reminder_seconds),escalation:F(e.escalation),template:f(e.template),rateLimitPerMinute:Number(e.rate_limit_per_minute),enabled:xt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Kt(e){return{id:String(e.id),alertId:f(e.alert_id),channelId:String(e.channel_id),routeId:f(e.route_id),eventType:String(e.event_type),idempotencyKey:String(e.idempotency_key),state:String(e.state),attempt:Number(e.attempt),maxAttempts:Number(e.max_attempts),nextAttemptAt:f(e.next_attempt_at),responseStatus:e.response_status==null?void 0:Number(e.response_status),error:f(e.error),payload:F(e.payload),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deliveredAt:f(e.delivered_at)}}class Dn{controlPlane;options;key;constructor(e,t){this.controlPlane=e;this.options=t;this.key=wr("sha256").update(t.encryptionKey).digest()}now(){return(this.options.now?.()??new Date).toISOString()}encrypt(e){let t=pn(12),r=vn("aes-256-gcm",this.key,t),s=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${s.toString("base64url")}`}decrypt(e){let[,t,r,s]=e.split("."),n=yn("aes-256-gcm",this.key,Buffer.from(t,"base64url"));return n.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([n.update(Buffer.from(s,"base64url")),n.final()]).toString("utf8")}createHealthCheck(e){if(!e.name.trim())throw Error("Health checks require a name.");if(!["http","tcp","command"].includes(e.kind))throw Error("Unsupported health check kind.");if(e.kind==="http"&&!/^https?:\/\//.test(e.target)||e.kind==="tcp"&&!/^[a-zA-Z0-9.-]+$/.test(e.target)||e.kind==="command"&&!e.config.command?.length)throw Error("Health check target is invalid.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO health_checks (id,project_id,environment_id,resource_id,name,kind,target,config,interval_seconds,timeout_seconds,failure_threshold,recovery_threshold,regions,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.name.trim().slice(0,100),e.kind,e.target,JSON.stringify(e.config),M(e.intervalSeconds,60,10,86400),M(e.timeoutSeconds,10,1,300),M(e.failureThreshold,3,1,100),M(e.recoveryThreshold,2,1,100),JSON.stringify(e.regions.slice(0,20)),e.enabled?1:0,1,r,r]),this.getHealthCheck(t)}getHealthCheck(e){let t=this.controlPlane.database.query("SELECT * FROM health_checks WHERE id=?").get(e);return t?Qr(t):void 0}listHealthChecks(e,t){return this.controlPlane.database.query(`SELECT * FROM health_checks WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(Qr)}setHealthCheckEnabled(e,t){this.controlPlane.database.run("UPDATE health_checks SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getHealthCheck(e);if(!r)throw Error("Health check was not found.");return r}appendHealthResult(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO health_results (id,check_id,status,agent,region,status_code,message,timings,checked_at) VALUES (?,?,?,?,?,?,?,?,?)",[t,e.checkId,e.status,e.agent.slice(0,100),e.region??null,e.statusCode??null,e.message?.slice(0,1000)??null,JSON.stringify(e.timings),e.checkedAt]),Vr(this.controlPlane.database.query("SELECT * FROM health_results WHERE id=?").get(t))}listHealthResults(e,t=100){return this.controlPlane.database.query("SELECT * FROM health_results WHERE check_id=? ORDER BY checked_at DESC LIMIT ?").all(e,Math.min(1000,Math.max(1,t))).map(Vr)}createRule(e){if(!e.name.trim())throw Error("Alert rules require a name.");if(e.operator!=="unhealthy"&&e.threshold==null)throw Error("Metric alert rules require a threshold.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO alert_rules (id,project_id,environment_id,resource_id,health_check_id,name,signal,operator,threshold,recovery_threshold,window_ms,consecutive,recovery_consecutive,no_data_policy,severity,group_by,labels,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.healthCheckId??null,e.name.trim().slice(0,120),e.signal,e.operator,e.threshold??null,e.recoveryThreshold??null,M(e.windowMs,300000,1e4,2678400000),M(e.consecutive,3,1,100),M(e.recoveryConsecutive,2,1,100),e.noDataPolicy,e.severity,JSON.stringify(e.groupBy.slice(0,20)),JSON.stringify(e.labels),e.enabled?1:0,1,r,r]),this.getRule(t)}getRule(e){let t=this.controlPlane.database.query("SELECT * FROM alert_rules WHERE id=?").get(e);return t?Wr(t):void 0}listRules(e,t){return this.controlPlane.database.query(`SELECT * FROM alert_rules WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(Wr)}setRuleEnabled(e,t){this.controlPlane.database.run("UPDATE alert_rules SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRule(e);if(!r)throw Error("Alert rule was not found.");return r}getAlertByDedup(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE dedup_key=?").get(e);return t?Ht(t):void 0}getAlert(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE id=?").get(e);return t?Ht(t):void 0}listAlerts(e,t={}){let r=["project_id=?"],s=[e];if(t.environmentId)r.push("environment_id=?"),s.push(t.environmentId);if(t.states?.length)r.push(`state IN (${t.states.map(()=>"?").join(",")})`),s.push(...t.states);return this.controlPlane.database.query(`SELECT * FROM alerts WHERE ${r.join(" AND ")} ORDER BY updated_at DESC LIMIT ?`).all(...s,Math.min(1000,t.limit??200)).map(Ht)}saveAlert(e,t,r){return this.controlPlane.database.run("INSERT INTO alerts (id,rule_id,project_id,environment_id,resource_id,dedup_key,group_key,state,severity,title,evidence,failure_count,recovery_count,occurrence_count,owner_actor_id,acknowledged_by_actor_id,acknowledged_at,first_seen_at,last_seen_at,firing_at,resolved_at,silenced_until,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,severity=excluded.severity,title=excluded.title,evidence=excluded.evidence,failure_count=excluded.failure_count,recovery_count=excluded.recovery_count,occurrence_count=excluded.occurrence_count,owner_actor_id=excluded.owner_actor_id,acknowledged_by_actor_id=excluded.acknowledged_by_actor_id,acknowledged_at=excluded.acknowledged_at,last_seen_at=excluded.last_seen_at,firing_at=excluded.firing_at,resolved_at=excluded.resolved_at,silenced_until=excluded.silenced_until,updated_at=excluded.updated_at",[e.id,e.ruleId,e.projectId,e.environmentId??null,e.resourceId??null,e.dedupKey,e.groupKey,e.state,e.severity,e.title,JSON.stringify(e.evidence),e.failureCount,e.recoveryCount,e.occurrenceCount,e.ownerActorId??null,e.acknowledgedByActorId??null,e.acknowledgedAt??null,e.firstSeenAt,e.lastSeenAt,e.firingAt??null,e.resolvedAt??null,e.silencedUntil??null,e.updatedAt]),this.controlPlane.database.run("INSERT INTO alert_events (id,alert_id,type,actor_id,payload,created_at) VALUES (?,?,?,?,?,?)",[crypto.randomUUID(),e.id,t,r??null,JSON.stringify({state:e.state,severity:e.severity,evidence:e.evidence}),e.updatedAt]),this.getAlert(e.id)}acknowledge(e,t){let r=this.getAlert(e);if(!r)throw Error("Alert was not found.");let s=this.now();return this.saveAlert({...r,acknowledgedByActorId:t,acknowledgedAt:s,updatedAt:s},"acknowledged",t)}assign(e,t,r){let s=this.getAlert(e);if(!s)throw Error("Alert was not found.");let n=this.now();return this.saveAlert({...s,ownerActorId:t,updatedAt:n},"assigned",r)}silenceAlert(e,t,r){let s=this.getAlert(e);if(!s)throw Error("Alert was not found.");let n=new Date(t);if(!Number.isFinite(n.getTime())||n<=new Date)throw Error("Silence end must be in the future.");let i=this.now();return this.saveAlert({...s,state:"silenced",silencedUntil:n.toISOString(),updatedAt:i},"silenced",r)}createSilence(e){let t=new Date(e.startsAt),r=new Date(e.endsAt);if(!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime())||t>=r)throw Error("Silence window is invalid.");try{new Intl.DateTimeFormat("en",{timeZone:e.timezone}).format(t)}catch{throw Error("Silence timezone is invalid.")}let s=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO alert_silences (id,project_id,environment_id,resource_id,matcher,reason,starts_at,ends_at,timezone,created_by_actor_id,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[s,e.projectId,e.environmentId??null,e.resourceId??null,JSON.stringify(e.matcher??{}),e.reason.slice(0,500),t.toISOString(),r.toISOString(),e.timezone,e.actorId??null,this.now()]),s}isSilenced(e,t,r){return this.controlPlane.database.query("SELECT * FROM alert_silences WHERE project_id=? AND starts_at<=? AND ends_at>?").all(e.projectId,r,r).some((n)=>{if(n.environment_id&&n.environment_id!==e.environmentId)return!1;if(n.resource_id&&n.resource_id!==e.resourceId)return!1;let i=F(n.matcher);return Object.entries(i).every(([E,a])=>t[E]===a)})}createChannel(e){if(!e.name.trim())throw Error("Notification channels require a name.");let t=crypto.randomUUID(),r=this.now(),s=e.credential?.trim();return this.controlPlane.database.run("INSERT INTO notification_channels (id,organization_id,name,kind,config,credential_ciphertext,credential_fingerprint,status,version,created_by_actor_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.kind,JSON.stringify(e.config??{}),s?this.encrypt(s):null,s?Gr(s):null,"active",1,e.actorId??null,r,r]),this.getChannel(t)}getChannel(e){let t=this.controlPlane.database.query("SELECT * FROM notification_channels WHERE id=?").get(e);return t?Jr(t):void 0}channelCredential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM notification_channels WHERE id=?").get(e);return t?.credential_ciphertext?this.decrypt(String(t.credential_ciphertext)):void 0}listChannels(e){return this.controlPlane.database.query("SELECT * FROM notification_channels WHERE organization_id=? ORDER BY updated_at DESC").all(e).map(Jr)}rotateChannel(e,t){let r=this.now();this.controlPlane.database.run("UPDATE notification_channels SET credential_ciphertext=?,credential_fingerprint=?,status='active',last_error=NULL,version=version+1,updated_at=? WHERE id=?",[this.encrypt(t),Gr(t),r,e]);let s=this.getChannel(e);if(!s)throw Error("Notification channel was not found.");return s}setChannelStatus(e,t,r){this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_error=?,updated_at=? WHERE id=?",[t,r?.slice(0,1000)??null,this.now(),e]);let s=this.getChannel(e);if(!s)throw Error("Notification channel was not found.");return s}markChannelTest(e,t,r){let s=this.now();return this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_tested_at=?,last_error=?,updated_at=? WHERE id=?",[t?"active":"failing",s,r?.slice(0,1000)??null,s,e]),this.getChannel(e)}createRoute(e){let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO notification_routes (id,organization_id,name,priority,matcher,channel_ids,quiet_hours,group_wait_seconds,reminder_seconds,escalation,template,rate_limit_per_minute,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.priority,JSON.stringify(e.matcher),JSON.stringify(e.channelIds),e.quietHours?JSON.stringify(e.quietHours):null,M(e.groupWaitSeconds,30,0,86400),e.reminderSeconds??null,JSON.stringify(e.escalation),e.template?.trim().slice(0,2000)??null,M(e.rateLimitPerMinute,60,1,1e4),e.enabled?1:0,1,r,r]),this.getRoute(t)}getRoute(e){let t=this.controlPlane.database.query("SELECT * FROM notification_routes WHERE id=?").get(e);return t?Zr(t):void 0}listRoutes(e){return this.controlPlane.database.query("SELECT * FROM notification_routes WHERE organization_id=? ORDER BY priority DESC,created_at ASC").all(e).map(Zr)}countRouteDeliveries(e,t){return Number(this.controlPlane.database.query("SELECT COUNT(*) count FROM notification_deliveries WHERE route_id=? AND created_at>=?").get(e,t)?.count??0)}setRouteEnabled(e,t){this.controlPlane.database.run("UPDATE notification_routes SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRoute(e);if(!r)throw Error("Notification route was not found.");return r}createDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return Kt(t);let r=crypto.randomUUID(),s=this.now();return this.controlPlane.database.run("INSERT INTO notification_deliveries (id,alert_id,channel_id,route_id,event_type,idempotency_key,state,attempt,max_attempts,next_attempt_at,payload,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.alertId??null,e.channelId,e.routeId??null,e.eventType,e.idempotencyKey,"pending",0,M(e.maxAttempts,3,1,10),e.nextAttemptAt??null,JSON.stringify(e.payload),s,s]),this.getDelivery(r)}getDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE id=?").get(e);return t?Kt(t):void 0}listDeliveries(e={}){let t=[],r=[];if(e.alertId)t.push("alert_id=?"),r.push(e.alertId);if(e.states?.length)t.push(`state IN (${e.states.map(()=>"?").join(",")})`),r.push(...e.states);return this.controlPlane.database.query(`SELECT * FROM notification_deliveries${t.length?" WHERE "+t.join(" AND "):""} ORDER BY updated_at DESC LIMIT ?`).all(...r,Math.min(1000,e.limit??200)).map(Kt)}updateDelivery(e,t){return this.controlPlane.database.run("UPDATE notification_deliveries SET state=?,attempt=?,next_attempt_at=?,response_status=?,error=?,delivered_at=?,updated_at=? WHERE id=?",[t.state,t.attempt,t.nextAttemptAt??null,t.responseStatus??null,t.error?.slice(0,1000)??null,t.deliveredAt??null,this.now(),e]),this.getDelivery(e)}}import{createHash as bn}from"node:crypto";function kn(e,t,r){if(e==="gt")return t>r;if(e==="gte")return t>=r;if(e==="lt")return t<r;if(e==="lte")return t<=r;return t===r}function Fn(e,t,r){if(t.status==="no_data"||t.status==null&&t.value==null)return;if(e.operator==="unhealthy")return t.status==="unhealthy";if(t.value==null||e.threshold==null)return;return kn(e.operator,t.value,r&&e.recoveryThreshold!=null?e.recoveryThreshold:e.threshold)}function Pn(e,t){let r=Object.fromEntries(e.groupBy.flatMap((n)=>t.group?.[n]==null?[]:[[n,String(t.group[n])]]));return{key:Object.entries(r).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>`${n}=${i}`).join(",")||"default",values:r}}function Hn(e,t){return bn("sha256").update(`${e}\x00${t}`).digest("hex")}class ge{store;constructor(e){this.store=e}evaluate(e,t){if(!e.enabled)return{transition:"ignored",notify:!1};let r=Pn(e,t),s=Hn(e.id,r.key),n=this.store.getAlertByDedup(s),i=n?.state==="firing"||n?.state==="silenced",E=Fn(e,t,i);if(E==null&&e.noDataPolicy==="ignore")return{alert:n,transition:"ignored",notify:!1};let a=E??e.noDataPolicy==="firing",d=E==null&&e.noDataPolicy==="pending",T=new Date(t.timestamp).toISOString(),N=h({...t.evidence??{},...t.value==null?{}:{value:t.value},...t.status?{healthStatus:t.status}:{},group:r.values}),o;if(!n){let L=a||d?1:0,u=a&&L>=e.consecutive?"firing":"pending";o={id:crypto.randomUUID(),ruleId:e.id,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,dedupKey:s,groupKey:r.key,state:u,severity:e.severity,title:e.name,evidence:N,failureCount:L,recoveryCount:0,occurrenceCount:1,firstSeenAt:T,lastSeenAt:T,firingAt:u==="firing"?T:void 0,updatedAt:T}}else if(a||d){let L=n.state==="resolved",u=(L?0:n.failureCount)+1,C=n.silencedUntil&&new Date(n.silencedUntil)>new Date(T),g=d?"pending":u>=e.consecutive?"firing":"pending";if((C||this.store.isSilenced(e,r.values,T))&&g==="firing")g="silenced";o={...n,state:g,severity:e.severity,title:e.name,evidence:N,failureCount:u,recoveryCount:0,occurrenceCount:n.occurrenceCount+1,firstSeenAt:L?T:n.firstSeenAt,lastSeenAt:T,firingAt:g==="firing"||g==="silenced"?n.firingAt??T:void 0,resolvedAt:void 0,updatedAt:T}}else{let L=n.recoveryCount+1,u=L>=e.recoveryConsecutive;o={...n,state:u?"resolved":n.state,evidence:N,failureCount:u?0:n.failureCount,recoveryCount:L,lastSeenAt:T,resolvedAt:u?T:n.resolvedAt,silencedUntil:u?void 0:n.silencedUntil,updatedAt:T}}let c=n?.state!==o.state,l=o.state==="pending"?"pending":o.state==="firing"?c?"firing":"updated":o.state==="silenced"?"silenced":c?"resolved":"updated";return{alert:this.store.saveAlert(o,c||!n?l:"observed"),transition:l,notify:l==="firing"||l==="resolved"}}}import{createHmac as Kn}from"node:crypto";function xn(e,t){let r=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e).map((n)=>[n.type,n.value])),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{minute:Number(r.hour)*60+Number(r.minute),weekday:s.indexOf(r.weekday)}}function es(e){let t=/^(\d{2}):(\d{2})$/.exec(e);if(!t)throw Error("Quiet hours require HH:MM times.");let r=Number(t[1])*60+Number(t[2]);if(Number(t[1])>23||Number(t[2])>59)throw Error("Quiet hours require valid HH:MM times.");return r}function jt(e,t){if(!e.quietHours)return!1;let r=xn(t,e.quietHours.timezone),s=es(e.quietHours.start),n=es(e.quietHours.end);if(e.quietHours.weekdays?.length&&!e.quietHours.weekdays.includes(r.weekday))return!1;return s<=n?r.minute>=s&&r.minute<n:r.minute>=s||r.minute<n}function Mn(e,t,r){let s=e.matcher;return(!s.projectIds?.length||s.projectIds.includes(t.projectId))&&(!s.environmentIds?.length||!!t.environmentId&&s.environmentIds.includes(t.environmentId))&&(!s.resourceIds?.length||!!t.resourceId&&s.resourceIds.includes(t.resourceId))&&(!s.severities?.length||s.severities.includes(t.severity))&&(!s.eventTypes?.length||s.eventTypes.includes(r))}function jn(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"?t:{value:e}}catch{return{value:e}}}function Bn(e,t,r){let s={severity:e.severity.toUpperCase(),title:e.title,state:e.state,event:t,projectId:e.projectId,environmentId:e.environmentId??"",resourceId:e.resourceId??"",groupKey:e.groupKey};return(r?.trim()||"[{{severity}}] {{title}} · {{state}}").replace(/\{\{(severity|title|state|event|projectId|environmentId|resourceId|groupKey)\}\}/g,(n,i)=>s[i]).slice(0,2000)}function Mt(e,t,r){return{schemaVersion:1,event:t,notificationText:Bn(e,t,r),alert:{id:e.id,state:e.state,severity:e.severity,title:e.title,projectId:e.projectId,environmentId:e.environmentId??null,resourceId:e.resourceId??null,groupKey:e.groupKey,firstSeenAt:e.firstSeenAt,lastSeenAt:e.lastSeenAt,firingAt:e.firingAt??null,resolvedAt:e.resolvedAt??null,evidence:e.evidence}}}class $n{store;options;fetchImpl;constructor(e,t={}){this.store=e;this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch}now(){return this.options.now?.()??new Date}preview(e,t,r){let s=[];for(let n of this.store.listRoutes(e)){if(!n.enabled||!Mn(n,t,r))continue;let i=[];for(let E of n.channelIds){let a=this.store.getChannel(E);if(a?.status==="active")i.push(a)}s.push({route:n,channels:i,quiet:jt(n,this.now())})}return s}enqueue(e,t,r){let s=r==="resolved"?t.resolvedAt:r==="firing"?t.firingAt:t.updatedAt,n=[];for(let i of this.preview(e,t,r)){if(i.quiet&&r!=="resolved")continue;let E=r==="resolved"||i.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+i.route.groupWaitSeconds*1000).toISOString(),a=r==="resolved"?Number.POSITIVE_INFINITY:Math.max(0,i.route.rateLimitPerMinute-this.store.countRouteDeliveries(i.route.id,new Date(this.now().getTime()-60000).toISOString()));for(let d of i.channels){if(a<=0)break;n.push(this.store.createDelivery({alertId:t.id,channelId:d.id,routeId:i.route.id,eventType:r,idempotencyKey:`${t.id}:${r}:${s}:${d.id}`,payload:Mt(t,r,i.route.template),nextAttemptAt:E})),a--}}return n}enqueueRemindersAndEscalations(e,t){let r=this.now(),s=[];for(let n of t.filter((i)=>i.state==="firing"&&!i.acknowledgedAt&&i.firingAt)){let i=Math.max(0,(r.getTime()-new Date(n.firingAt).getTime())/1000);for(let E of this.preview(e,n,"reminder")){if(E.quiet)continue;if(E.route.reminderSeconds&&i>=E.route.reminderSeconds){let a=Math.floor(i/E.route.reminderSeconds);for(let d of E.channels)s.push(this.store.createDelivery({alertId:n.id,channelId:d.id,routeId:E.route.id,eventType:"reminder",idempotencyKey:`${n.id}:reminder:${E.route.id}:${a}:${d.id}`,payload:Mt(n,"reminder")}))}for(let[a,d]of E.route.escalation.entries())if(i>=d.afterSeconds){for(let T of d.channelIds)if(this.store.getChannel(T)?.status==="active")s.push(this.store.createDelivery({alertId:n.id,channelId:T,routeId:E.route.id,eventType:"escalation",idempotencyKey:`${n.id}:escalation:${E.route.id}:${a}:${T}`,payload:Mt(n,"escalation")}))}}}return s}async send(e,t){let r=jn(this.store.channelCredential(e.id)),s=typeof t.notificationText==="string"?t.notificationText:`[${String(t.alert?.severity??"info").toUpperCase()}] ${String(t.alert?.title??"ts-cloud alert")} · ${String(t.alert?.state??t.event)}`;try{if(e.kind==="email"){if(!this.options.emailImpl)return{ok:!1,error:"Email adapter is not configured."};return await this.options.emailImpl({to:e.config.to,from:e.config.from,subject:`[ts-cloud] ${String(t.alert?.title??t.event)}`,text:`${s}
|
|
1541
1541
|
|
|
1542
|
-
${JSON.stringify(t,null,2)}`}),{ok:!0,status:202}}if(e.kind==="sms"){if(!this.options.smsImpl)return{ok:!1,error:"SMS adapter is not configured."};let p=e.config.to;if(typeof p!=="string"||!p.trim())return{ok:!1,error:"SMS channels need a `to` number."};return await this.options.smsImpl({to:p,from:e.config.from,text:n.slice(0,300)}),{ok:!0,status:202}}let i=r.url??r.value,o=t,s={"content-type":"application/json"};if(e.kind==="slack")o={text:n};if(e.kind==="discord")o={content:n};if(e.kind==="teams")o={text:n};if(e.kind==="telegram")i=`https://api.telegram.org/bot${r.botToken??r.value}/sendMessage`,o={chat_id:e.config.chatId,text:n};if(!i||!/^https:\/\//.test(i))return{ok:!1,error:"Channel endpoint is unavailable or not HTTPS."};let a=JSON.stringify(o);if(e.kind==="webhook"&&r.signingSecret){let p=Math.floor(this.now().getTime()/1000).toString();s["x-ts-cloud-timestamp"]=p,s["x-ts-cloud-signature"]=`v1=${Fi("sha256",r.signingSecret).update(`${p}.${a}`).digest("hex")}`}let d=new AbortController,c=setTimeout(()=>d.abort(),1e4);try{let p=await this.fetchImpl(i,{method:"POST",headers:s,body:a,signal:d.signal});return p.ok?{ok:!0,status:p.status}:{ok:!1,status:p.status,error:`Channel returned HTTP ${p.status}.`}}finally{clearTimeout(c)}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}}async deliver(e){let t=this.store.getDelivery(e);if(!t)throw Error("Notification delivery was not found.");if(t.state==="delivered"||t.state==="dead"||t.nextAttemptAt&&t.nextAttemptAt>this.now().toISOString())return t;let r=this.store.getChannel(t.channelId);if(!r||r.status==="disabled"||r.status==="paused")return this.store.updateDelivery(e,{state:"failed",attempt:t.attempt+1,error:"Notification channel is unavailable."});let n=t.attempt+1,i=await this.send(r,t.payload);if(i.ok)return this.store.setChannelStatus(r.id,"active"),this.store.updateDelivery(e,{state:"delivered",attempt:n,responseStatus:i.status,deliveredAt:this.now().toISOString()});let s=!(!i.status||i.status===429||i.status>=500)||n>=t.maxAttempts,a=s?void 0:new Date(this.now().getTime()+Math.min(3600000,30000*2**(n-1))).toISOString();return this.store.setChannelStatus(r.id,"failing",i.error),this.store.updateDelivery(e,{state:s?"dead":"retrying",attempt:n,nextAttemptAt:a,responseStatus:i.status,error:i.error})}async deliverAll(e){return Promise.all(e.map((t)=>this.deliver(t.id)))}async retryDue(){let e=this.now().toISOString(),t=this.store.listDeliveries({states:["pending","retrying"]}).filter((r)=>!r.nextAttemptAt||r.nextAttemptAt<=e);return this.deliverAll(t)}async testChannel(e){let t=this.store.getChannel(e);if(!t)throw Error("Notification channel was not found.");let r=await this.send(t,{schemaVersion:1,event:"test",message:"ts-cloud notification channel test. No incident was created."});return this.store.markChannelTest(e,r.ok,r.error),r}}import{lookup as Vi}from"node:dns/promises";import{connect as Ki}from"node:net";async function $i(e,t){let r=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),n=setTimeout(()=>r.kill(),t);try{return{exitCode:await r.exited,stdout:await new Response(r.stdout).text(),stderr:await new Response(r.stderr).text()}}finally{clearTimeout(n)}}class Qi{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}async probe(e){let t=performance.now(),r=this.now().toISOString(),n=this.options.agent??"local";try{if(e.kind==="http"){let s=new URL(e.target),a=performance.now();await(this.options.lookupImpl??Vi)(s.hostname);let d=performance.now()-a,c=new AbortController,p=setTimeout(()=>c.abort(),e.timeoutSeconds*1000);try{let l=performance.now(),u=await(this.options.fetchImpl??fetch)(s.toString(),{method:e.config.method??"GET",headers:e.config.headers,signal:c.signal,redirect:"manual"}),m=performance.now()-l,E=e.config.expectedBody?await u.text():"",T=e.config.expectedStatuses??[200,201,202,204],_=T.includes(u.status)&&(!e.config.expectedBody||E.includes(e.config.expectedBody));return{checkId:e.id,status:_?"healthy":"unhealthy",agent:n,region:this.options.region,statusCode:u.status,message:_?void 0:`Expected ${T.join("/")} and configured body match.`,timings:{dnsMs:d,ttfbMs:m,totalMs:performance.now()-t},checkedAt:r}}finally{clearTimeout(p)}}if(e.kind==="tcp"){let s=Number(e.config.port);if(!Number.isInteger(s)||s<1||s>65535)throw Error("TCP health check requires a valid port.");let a=performance.now();return await new Promise((d,c)=>{let p=Ki({host:e.target,port:s}),l=setTimeout(()=>{p.destroy(),c(Error("TCP health check timed out."))},e.timeoutSeconds*1000);p.once("connect",()=>{clearTimeout(l),p.destroy(),d()}),p.once("error",(u)=>{clearTimeout(l),c(u)})}),{checkId:e.id,status:"healthy",agent:n,region:this.options.region,timings:{connectMs:performance.now()-a,totalMs:performance.now()-t},checkedAt:r}}let i=e.config.command??[];if(!i.length)throw Error("Command health check is not configured.");let o=await(this.options.commandImpl??$i)(i,e.timeoutSeconds*1000);return{checkId:e.id,status:o.exitCode===0?"healthy":"unhealthy",agent:n,region:this.options.region,message:o.exitCode===0?void 0:(o.stderr||o.stdout||`Command exited ${o.exitCode}`).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}catch(i){return{checkId:e.id,status:"unhealthy",agent:n,region:this.options.region,message:(i instanceof Error?i.message:String(i)).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}}async run(e){return this.store.appendHealthResult(await this.probe(e))}async runAndEvaluate(e){let t=await this.run(e),r=new fe(this.store),n=this.store.listRules(e.projectId,e.environmentId).filter((i)=>i.healthCheckId===e.id);return{result:t,evaluations:n.map((i)=>r.evaluate(i,{status:t.status,timestamp:t.checkedAt,group:{agent:t.agent,region:t.region??""},evidence:{healthResultId:t.id,statusCode:t.statusCode??null,message:t.message??null,timings:t.timings}}))}}}var Yi=Object.freeze({rawDays:30,downsampleAfterDays:7,downsampleBucketMs:3600000,maxRecords:1e6,samplingRate:1,collectLogs:!0,collectTraces:!0,collectRequestAnalytics:!0,estimatedStorageUsdPerGbMonth:0});function Je(e,t,r,n){let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,Math.floor(i))):t}function rn(e,t,r,n){let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,i)):t}function Ht(e,t){return typeof e==="boolean"?e:t}function nn(e,t={...Yi}){let r=e&&typeof e==="object"&&!Array.isArray(e)?e:{},n=Je(r.rawDays,t.rawDays,1,3650),i=Je(r.downsampleAfterDays,t.downsampleAfterDays,1,n);return{rawDays:n,downsampleAfterDays:i,downsampleBucketMs:Je(r.downsampleBucketMs,t.downsampleBucketMs,60000,86400000),maxRecords:Je(r.maxRecords,t.maxRecords,1000,1e8),samplingRate:rn(r.samplingRate,t.samplingRate,0.01,1),collectLogs:Ht(r.collectLogs,t.collectLogs),collectTraces:Ht(r.collectTraces,t.collectTraces),collectRequestAnalytics:Ht(r.collectRequestAnalytics,t.collectRequestAnalytics),estimatedStorageUsdPerGbMonth:rn(r.estimatedStorageUsdPerGbMonth,t.estimatedStorageUsdPerGbMonth,0,1e4)}}function on(e){return`telemetry.policy:${e}`}function Gi(e,t){return nn(e.getSetting(on(t)))}function Fa(e,t,r){let n=nn(r,Gi(e,t));return e.setSetting(on(t),n),n}function Ma(e,t){return Number((Math.max(0,e)/1073741824*t.estimatedStorageUsdPerGbMonth).toFixed(4))}var Wi=/(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key|session)/i,Ji=/\b(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;&\[]+/gi,Zi=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,eo=/\b(?:\d{1,3}\.){3}\d{1,3}\b/g;function Bt(e,t={}){let r=e.replace(/([?&][^=&#\s]+)=([^&#\s]*)/g,"$1=[REDACTED]").replace(Ji,"[REDACTED]");if(t.redactEmail!==!1)r=r.replace(Zi,"[EMAIL]");if(t.redactIp)r=r.replace(eo,"[IP]");for(let n of t.patterns??[])r=r.replace(n,"[REDACTED]");return r}function ye(e,t={},r){if(r&&Wi.test(r))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return Bt(e,t);if(Array.isArray(e))return e.map((n)=>ye(n,t));if(e&&typeof e==="object"){let n={};for(let[i,o]of Object.entries(e))n[i]=ye(o,t,i);return n}return String(e??"")}function sn(e){if(!e)return;return e.split("?",1)[0].replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi,":id").replace(/\/(?:(?:\d{4,})|(?:[0-9a-f]{16,}))(?:\/|$)/gi,(r)=>r.endsWith("/")?"/:id/":"/:id").slice(0,512)}var an=65536,to=2678400000,ro=new Set(["metric","log","trace","request","event"]);function U(e){return typeof e==="string"?e:void 0}function Le(e){return e==null?void 0:Number(e)}function no(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function Ze(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:U(e.environment_id),resourceId:U(e.resource_id),kind:String(e.kind),source:String(e.source),name:String(e.name),timestamp:String(e.timestamp),observedAt:String(e.observed_at),value:Le(e.value),unit:U(e.unit),level:U(e.level),message:U(e.message),durationMs:Le(e.duration_ms),statusCode:Le(e.status_code),method:U(e.method),host:U(e.host),pathTemplate:U(e.path_template),bytesIn:Le(e.bytes_in),bytesOut:Le(e.bytes_out),region:U(e.region),cacheResult:U(e.cache_result),upstream:U(e.upstream),traceId:U(e.trace_id),requestId:U(e.request_id),deploymentId:U(e.deployment_id),releaseId:U(e.release_id),workloadId:U(e.workload_id),sampled:Number(e.sampled)===1,attributes:no(e.attributes),ingestedBytes:Number(e.ingested_bytes)}}function ne(e,t){let r=new Date(e);if(!e||!Number.isFinite(r.getTime()))throw Error(`${t} must be a valid ISO-8601 instant.`);return r}function et(e){let t=ne(e.from,"from"),r=ne(e.to,"to");if(t>=r)throw Error("Telemetry from must be earlier than to.");if(r.getTime()-t.getTime()>to)throw Error("Telemetry queries are limited to 31 days.");return{from:t,to:r}}function dn(e){if(!e)return;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(typeof t?.timestamp!=="string"||typeof t?.id!=="string")throw Error();return t}catch{throw Error("Telemetry cursor is invalid.")}}function cn(e){return e?Buffer.from(JSON.stringify({timestamp:e.timestamp,id:e.id})).toString("base64url"):void 0}function io(e,t){if(!e.length)return;let r=[...e].sort((i,o)=>i-o),n=Math.max(0,Math.min(r.length-1,Math.ceil(t/100*r.length)-1));return r[n]}function ve(e,t){if(t==="count")return e.length;if(!e.length)return;if(t==="sum")return e.reduce((r,n)=>r+n,0);if(t==="avg")return e.reduce((r,n)=>r+n,0)/e.length;if(t==="min")return Math.min(...e);if(t==="max")return Math.max(...e);return io(e,Number(t.slice(1)))}function oo(e,t="UTC"){try{return new Intl.DateTimeFormat("en-US",{timeZone:t,month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZoneName:"short"}).format(e)}catch{throw Error(`Unknown telemetry timezone: ${t}`)}}class Vt{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return this.options.now?.()??new Date}append(e){if(!ro.has(e.kind))throw Error(`Unsupported telemetry kind: ${e.kind}`);let t=ne(e.timestamp,"timestamp").toISOString(),r=e.observedAt?ne(e.observedAt,"observedAt").toISOString():this.now().toISOString(),n=ye(e.attributes??{},this.options.redaction),i=e.message?Bt(e.message,this.options.redaction).slice(0,32768):void 0,o=sn(e.pathTemplate),s=e.id??crypto.randomUUID(),a=JSON.stringify({...e,id:s,timestamp:t,observedAt:r,attributes:n,message:i,pathTemplate:o}),d=Buffer.byteLength(a);if(d>an)throw Error(`Telemetry records are limited to ${an} bytes.`);return this.controlPlane.database.run("INSERT OR IGNORE INTO telemetry_records (id, project_id, environment_id, resource_id, kind, source, name, timestamp, observed_at, value, unit, level, message, duration_ms, status_code, method, host, path_template, bytes_in, bytes_out, region, cache_result, upstream, trace_id, request_id, deployment_id, release_id, workload_id, sampled, attributes, ingested_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[s,e.projectId,e.environmentId??null,e.resourceId??null,e.kind,e.source.slice(0,128),e.name.slice(0,256),t,r,e.value??null,e.unit??null,e.level??null,i??null,e.durationMs??null,e.statusCode??null,e.method?.slice(0,16)??null,e.host?.slice(0,256)??null,o??null,e.bytesIn??null,e.bytesOut??null,e.region?.slice(0,64)??null,e.cacheResult?.slice(0,64)??null,e.upstream?.slice(0,256)??null,e.traceId?.slice(0,256)??null,e.requestId?.slice(0,256)??null,e.deploymentId?.slice(0,256)??null,e.releaseId?.slice(0,256)??null,e.workloadId?.slice(0,512)??null,e.sampled===!1?0:1,JSON.stringify(n),d]),this.get(s)}appendMany(e){if(e.length>1e4)throw Error("Telemetry batches are limited to 10,000 records.");return this.controlPlane.database.transaction((r)=>r.map((n)=>this.append(n)))(e)}get(e){let t=this.controlPlane.database.query("SELECT * FROM telemetry_records WHERE id=?").get(e);return t?Ze(t):void 0}query(e){let{from:t,to:r}=et(e),n=Math.min(5000,Math.max(1,Math.floor(e.limit??500))),i=["project_id=?","timestamp>=?","timestamp<?"],o=[e.projectId,t.toISOString(),r.toISOString()],s=(h,N)=>{if(N)i.push(`${h}=?`),o.push(N)},a=(h,N)=>{let f=[...new Set(N??[])].slice(0,100);if(f.length)i.push(`${h} IN (${f.map(()=>"?").join(",")})`),o.push(...f)};if(s("environment_id",e.environmentId),a("resource_id",e.resourceIds),a("kind",e.kinds),a("name",e.names),a("source",e.sources),a("level",e.levels),s("trace_id",e.traceId),s("request_id",e.requestId),s("deployment_id",e.deploymentId),s("release_id",e.releaseId),s("workload_id",e.workloadId),e.text)i.push("(message LIKE ? OR name LIKE ?)"),o.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let d=dn(e.cursor);if(d)i.push("(timestamp<? OR (timestamp=? AND id<?))"),o.push(d.timestamp,d.timestamp,d.id);let c=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${i.join(" AND ")} ORDER BY timestamp DESC, id DESC LIMIT ?`).all(...o,n+1),p=c.slice(0,n).map(Ze),l=c.length>n,u=new Map;for(let h of p)u.set(h.source,[...u.get(h.source)??[],h]);let m=this.now().getTime(),E=[...u].map(([h,N])=>{let f=N.reduce((O,R)=>R.observedAt>O?R.observedAt:O,N[0].observedAt),b=m-new Date(f).getTime();return{source:h,latestAt:f,freshness:b<=120000?"live":b<=600000?"stale":"unavailable",count:N.length}}),T=Math.max(60000,(r.getTime()-t.getTime())/100),_=[...u].flatMap(([h,N])=>{let f=[...new Set(N.map((b)=>new Date(b.timestamp).getTime()))].sort((b,O)=>b-O);return f.slice(1).flatMap((b,O)=>b-f[O]>T?[{from:new Date(f[O]).toISOString(),to:new Date(b).toISOString(),source:h}]:[])});return{records:p,nextCursor:l?cn(p.at(-1)):void 0,truncated:l,scannedRange:{from:t.toISOString(),to:r.toISOString()},sources:E,gaps:_}}tail(e,t){let{from:r,to:n}=et(e),i=Math.min(1000,Math.max(1,Math.floor(e.limit??200))),o=["project_id=?","timestamp>=?","timestamp<?"],s=[e.projectId,r.toISOString(),n.toISOString()],a=(u,m)=>{if(m)o.push(`${u}=?`),s.push(m)},d=(u,m)=>{let E=[...new Set(m??[])].slice(0,100);if(E.length)o.push(`${u} IN (${E.map(()=>"?").join(",")})`),s.push(...E)};if(a("environment_id",e.environmentId),d("resource_id",e.resourceIds),d("kind",e.kinds),d("name",e.names),d("source",e.sources),d("level",e.levels),a("trace_id",e.traceId),a("request_id",e.requestId),a("deployment_id",e.deploymentId),a("release_id",e.releaseId),a("workload_id",e.workloadId),e.text)o.push("(message LIKE ? OR name LIKE ?)"),s.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let c=dn(t);if(c)o.push("(timestamp>? OR (timestamp=? AND id>?))"),s.push(c.timestamp,c.timestamp,c.id);let p=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${o.join(" AND ")} ORDER BY timestamp ASC, id ASC LIMIT ?`).all(...s,i+1),l=p.slice(0,i).map(Ze);return{records:l,cursor:cn(l.at(-1))??t,truncated:p.length>i}}series(e){let{from:t,to:r}=et(e),n=Math.min(86400000,Math.max(1000,Math.floor(e.bucketMs)));if((r.getTime()-t.getTime())/n>2000)throw Error("Telemetry series are limited to 2,000 buckets.");let i=this.query({...e,kinds:["metric"],limit:5000,cursor:void 0}),o=new Map;for(let a of i.records)o.set(`${a.source}\x00${a.name}`,[...o.get(`${a.source}\x00${a.name}`)??[],a]);let s=(a,d,c)=>{let p=new Map;for(let u of a){let m=d.getTime()+Math.floor((new Date(u.timestamp).getTime()-d.getTime())/n)*n;if(m>=d.getTime()&&m<c.getTime()&&u.value!=null)p.set(m,[...p.get(m)??[],u.value])}let l=[];for(let u=d.getTime();u<c.getTime();u+=n){let m=p.get(u)??[],E=ve(m,e.aggregation);l.push({timestamp:new Date(u).toISOString(),label:oo(new Date(u),e.timezone),value:E,count:m.length,gap:E==null})}return l};return[...o].map(([a,d])=>{let[c,p]=a.split("\x00"),l={name:p,source:c,unit:d.find((u)=>u.unit)?.unit,aggregation:e.aggregation,bucketMs:n,points:s(d,t,r)};if(e.compareFrom&&e.compareTo){let u=this.query({...e,from:e.compareFrom,to:e.compareTo,kinds:["metric"],limit:5000,cursor:void 0}).records.filter((m)=>m.source===c&&m.name===p);l.comparison=s(u,ne(e.compareFrom,"compareFrom"),ne(e.compareTo,"compareTo"))}return l})}status(e,t,r=30,n=1,i){let o=[e],s=t?" AND environment_id=?":"";if(t)o.push(t);let a=[...new Set(i??[])].slice(0,100);if(i&&a.length===0)return[];let d=i?` AND resource_id IN (${a.map(()=>"?").join(",")||"''"})`:"";o.push(...a);let c=this.controlPlane.database.query(`SELECT source, MAX(latest_observed_at) latest, SUM(ingested_bytes) bytes, SUM(record_count) count, MIN(first_observed_at) first FROM telemetry_source_rollups WHERE project_id=?${s}${d} GROUP BY source`).all(...o),p=this.now().getTime();return c.map((l)=>{let u=String(l.latest),m=Math.max(0,Math.floor((p-new Date(u).getTime())/1000)),E=Math.max(1,(new Date(u).getTime()-new Date(String(l.first)).getTime())/86400000);return{source:String(l.source),freshness:m<=120?"live":m<=600?"stale":"unavailable",lastObservedAt:u,lagSeconds:m,samplingRate:n,retentionDays:r,estimatedDailyBytes:Math.round(Number(l.bytes)/E)}})}saveQuery(e,t,r,n){let i=r.trim().slice(0,80);if(!i)throw Error("Saved telemetry queries require a name.");if(et(n),n.projectId!==e)throw Error("Saved telemetry queries cannot cross project scope.");let o=this.now().toISOString(),s=JSON.stringify(ye(n,this.options.redaction));if(Buffer.byteLength(s)>16384)throw Error("Saved telemetry queries are limited to 16 KB.");let a=this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? AND name=?").get(e,t??null,i),d=a?String(a.id):crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO telemetry_saved_queries (id, project_id, actor_id, name, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, actor_id, name) DO UPDATE SET query=excluded.query, updated_at=excluded.updated_at",[d,e,t??null,i,s,a?String(a.created_at):o,o]),{id:d,projectId:e,actorId:t,name:i,query:JSON.parse(s),createdAt:a?String(a.created_at):o,updatedAt:o}}listSavedQueries(e,t){return this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? ORDER BY updated_at DESC").all(e,t??null).map((r)=>({id:String(r.id),projectId:String(r.project_id),actorId:U(r.actor_id),name:String(r.name),query:JSON.parse(String(r.query)),createdAt:String(r.created_at),updatedAt:String(r.updated_at)}))}deleteSavedQuery(e,t,r){return this.controlPlane.database.run("DELETE FROM telemetry_saved_queries WHERE id=? AND project_id=? AND actor_id IS ?",[r,e,t??null]).changes>0}downsample(e,t){let r=Math.min(86400000,Math.max(60000,Math.floor(e.downsampleBucketMs))),n=new Date(this.now().getTime()-Math.max(1,e.downsampleAfterDays)*86400000).toISOString(),i=new Date(this.now().getTime()-Math.max(1,e.rawDays)*86400000).toISOString(),o=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE kind='metric' AND source NOT LIKE '%:rollup' AND timestamp>=? AND timestamp<?${t?" AND project_id=?":""} ORDER BY timestamp ASC LIMIT 50001`).all(i,n,...t?[t]:[]);if(o.length>50000)throw Error("Telemetry downsampling is limited to 50,000 raw points per pass; run compaction more frequently.");let s=o.map(Ze),a=new Map;for(let c of s){let p=Math.floor(new Date(c.timestamp).getTime()/r)*r,l=JSON.stringify([c.projectId,c.environmentId??"",c.resourceId??"",c.source,c.name,c.unit??"",p]);a.set(l,[...a.get(l)??[],c])}return this.controlPlane.database.transaction(()=>{for(let c=0;c<s.length;c+=500){let p=s.slice(c,c+500).map((l)=>l.id);if(p.length)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (${p.map(()=>"?").join(",")})`,p)}for(let[c,p]of a){let[l,u,m,E,T,_,h]=JSON.parse(c),N=p.flatMap((f)=>f.value==null?[]:[f.value]);this.append({projectId:l,environmentId:u||void 0,resourceId:m||void 0,kind:"metric",source:`${E}:rollup`,name:T,unit:_||void 0,timestamp:new Date(h).toISOString(),value:ve(N,"avg"),attributes:{downsampled:!0,count:N.length,min:ve(N,"min"),max:ve(N,"max"),p95:ve(N,"p95"),bucketMs:r}})}})(),{compacted:s.length,rollups:a.size}}enforceRetention(e,t){let r=this.downsample(e,t),n=Math.min(3650,Math.max(1,Math.floor(e.rawDays))),i=new Date(this.now().getTime()-n*86400000).toISOString(),o=t?" AND project_id=?":"",s=this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE timestamp<?${o}`,t?[i,t]:[i]).changes,a=Number(this.controlPlane.database.query(`SELECT MAX(0, COUNT(*)-?) excess FROM telemetry_records${t?" WHERE project_id=?":""}`).get(e.maxRecords,...t?[t]:[])?.excess??0);if(a>0)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (SELECT id FROM telemetry_records${t?" WHERE project_id=?":""} ORDER BY timestamp ASC LIMIT ?)`,t?[t,a]:[a]);return this.rebuildStatusRollups(t),{deleted:s+a,...r}}rebuildStatusRollups(e){let t=e?" WHERE project_id=?":"",r=e?[e]:[];this.controlPlane.database.transaction(()=>{this.controlPlane.database.run(`DELETE FROM telemetry_source_rollups${t}`,r),this.controlPlane.database.run(`INSERT INTO telemetry_source_rollups (
|
|
1542
|
+
${JSON.stringify(t,null,2)}`}),{ok:!0,status:202}}if(e.kind==="sms"){if(!this.options.smsImpl)return{ok:!1,error:"SMS adapter is not configured."};let N=e.config.to;if(typeof N!=="string"||!N.trim())return{ok:!1,error:"SMS channels need a `to` number."};return await this.options.smsImpl({to:N,from:e.config.from,text:s.slice(0,300)}),{ok:!0,status:202}}let n=r.url??r.value,i=t,E={"content-type":"application/json"};if(e.kind==="slack")i={text:s};if(e.kind==="discord")i={content:s};if(e.kind==="teams")i={text:s};if(e.kind==="telegram")n=`https://api.telegram.org/bot${r.botToken??r.value}/sendMessage`,i={chat_id:e.config.chatId,text:s};if(!n||!/^https:\/\//.test(n))return{ok:!1,error:"Channel endpoint is unavailable or not HTTPS."};let a=JSON.stringify(i);if(e.kind==="webhook"&&r.signingSecret){let N=Math.floor(this.now().getTime()/1000).toString();E["x-ts-cloud-timestamp"]=N,E["x-ts-cloud-signature"]=`v1=${Kn("sha256",r.signingSecret).update(`${N}.${a}`).digest("hex")}`}let d=new AbortController,T=setTimeout(()=>d.abort(),1e4);try{let N=await this.fetchImpl(n,{method:"POST",headers:E,body:a,signal:d.signal});return N.ok?{ok:!0,status:N.status}:{ok:!1,status:N.status,error:`Channel returned HTTP ${N.status}.`}}finally{clearTimeout(T)}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async deliver(e){let t=this.store.getDelivery(e);if(!t)throw Error("Notification delivery was not found.");if(t.state==="delivered"||t.state==="dead"||t.nextAttemptAt&&t.nextAttemptAt>this.now().toISOString())return t;let r=this.store.getChannel(t.channelId);if(!r||r.status==="disabled"||r.status==="paused")return this.store.updateDelivery(e,{state:"failed",attempt:t.attempt+1,error:"Notification channel is unavailable."});let s=t.attempt+1,n=await this.send(r,t.payload);if(n.ok)return this.store.setChannelStatus(r.id,"active"),this.store.updateDelivery(e,{state:"delivered",attempt:s,responseStatus:n.status,deliveredAt:this.now().toISOString()});let E=!(!n.status||n.status===429||n.status>=500)||s>=t.maxAttempts,a=E?void 0:new Date(this.now().getTime()+Math.min(3600000,30000*2**(s-1))).toISOString();return this.store.setChannelStatus(r.id,"failing",n.error),this.store.updateDelivery(e,{state:E?"dead":"retrying",attempt:s,nextAttemptAt:a,responseStatus:n.status,error:n.error})}async deliverAll(e){return Promise.all(e.map((t)=>this.deliver(t.id)))}async retryDue(){let e=this.now().toISOString(),t=this.store.listDeliveries({states:["pending","retrying"]}).filter((r)=>!r.nextAttemptAt||r.nextAttemptAt<=e);return this.deliverAll(t)}async testChannel(e){let t=this.store.getChannel(e);if(!t)throw Error("Notification channel was not found.");let r=await this.send(t,{schemaVersion:1,event:"test",message:"ts-cloud notification channel test. No incident was created."});return this.store.markChannelTest(e,r.ok,r.error),r}}import{lookup as qn}from"node:dns/promises";import{connect as Yn}from"node:net";async function zn(e,t){let r=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),s=setTimeout(()=>r.kill(),t);try{return{exitCode:await r.exited,stdout:await new Response(r.stdout).text(),stderr:await new Response(r.stderr).text()}}finally{clearTimeout(s)}}class Gn{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}async probe(e){let t=performance.now(),r=this.now().toISOString(),s=this.options.agent??"local";try{if(e.kind==="http"){let E=new URL(e.target),a=performance.now();await(this.options.lookupImpl??qn)(E.hostname);let d=performance.now()-a,T=new AbortController,N=setTimeout(()=>T.abort(),e.timeoutSeconds*1000);try{let o=performance.now(),c=await(this.options.fetchImpl??fetch)(E.toString(),{method:e.config.method??"GET",headers:e.config.headers,signal:T.signal,redirect:"manual"}),l=performance.now()-o,_=e.config.expectedBody?await c.text():"",L=e.config.expectedStatuses??[200,201,202,204],u=L.includes(c.status)&&(!e.config.expectedBody||_.includes(e.config.expectedBody));return{checkId:e.id,status:u?"healthy":"unhealthy",agent:s,region:this.options.region,statusCode:c.status,message:u?void 0:`Expected ${L.join("/")} and configured body match.`,timings:{dnsMs:d,ttfbMs:l,totalMs:performance.now()-t},checkedAt:r}}finally{clearTimeout(N)}}if(e.kind==="tcp"){let E=Number(e.config.port);if(!Number.isInteger(E)||E<1||E>65535)throw Error("TCP health check requires a valid port.");let a=performance.now();return await new Promise((d,T)=>{let N=Yn({host:e.target,port:E}),o=setTimeout(()=>{N.destroy(),T(Error("TCP health check timed out."))},e.timeoutSeconds*1000);N.once("connect",()=>{clearTimeout(o),N.destroy(),d()}),N.once("error",(c)=>{clearTimeout(o),T(c)})}),{checkId:e.id,status:"healthy",agent:s,region:this.options.region,timings:{connectMs:performance.now()-a,totalMs:performance.now()-t},checkedAt:r}}let n=e.config.command??[];if(!n.length)throw Error("Command health check is not configured.");let i=await(this.options.commandImpl??zn)(n,e.timeoutSeconds*1000);return{checkId:e.id,status:i.exitCode===0?"healthy":"unhealthy",agent:s,region:this.options.region,message:i.exitCode===0?void 0:(i.stderr||i.stdout||`Command exited ${i.exitCode}`).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}catch(n){return{checkId:e.id,status:"unhealthy",agent:s,region:this.options.region,message:(n instanceof Error?n.message:String(n)).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}}async run(e){return this.store.appendHealthResult(await this.probe(e))}async runAndEvaluate(e){let t=await this.run(e),r=new ge(this.store),s=this.store.listRules(e.projectId,e.environmentId).filter((n)=>n.healthCheckId===e.id);return{result:t,evaluations:s.map((n)=>r.evaluate(n,{status:t.status,timestamp:t.checkedAt,group:{agent:t.agent,region:t.region??""},evidence:{healthResultId:t.id,statusCode:t.statusCode??null,message:t.message??null,timings:t.timings}}))}}}var Qn=Object.freeze({rawDays:30,downsampleAfterDays:7,downsampleBucketMs:3600000,maxRecords:1e6,samplingRate:1,collectLogs:!0,collectTraces:!0,collectRequestAnalytics:!0,estimatedStorageUsdPerGbMonth:0});function Je(e,t,r,s){let n=Number(e);return Number.isFinite(n)?Math.min(s,Math.max(r,Math.floor(n))):t}function ts(e,t,r,s){let n=Number(e);return Number.isFinite(n)?Math.min(s,Math.max(r,n)):t}function Bt(e,t){return typeof e==="boolean"?e:t}function rs(e,t={...Qn}){let r=e&&typeof e==="object"&&!Array.isArray(e)?e:{},s=Je(r.rawDays,t.rawDays,1,3650),n=Je(r.downsampleAfterDays,t.downsampleAfterDays,1,s);return{rawDays:s,downsampleAfterDays:n,downsampleBucketMs:Je(r.downsampleBucketMs,t.downsampleBucketMs,60000,86400000),maxRecords:Je(r.maxRecords,t.maxRecords,1000,1e8),samplingRate:ts(r.samplingRate,t.samplingRate,0.01,1),collectLogs:Bt(r.collectLogs,t.collectLogs),collectTraces:Bt(r.collectTraces,t.collectTraces),collectRequestAnalytics:Bt(r.collectRequestAnalytics,t.collectRequestAnalytics),estimatedStorageUsdPerGbMonth:ts(r.estimatedStorageUsdPerGbMonth,t.estimatedStorageUsdPerGbMonth,0,1e4)}}function ss(e){return`telemetry.policy:${e}`}function Vn(e,t){return rs(e.getSetting(ss(t)))}function Ha(e,t,r){let s=rs(r,Vn(e,t));return e.setSetting(ss(t),s),s}function Ka(e,t){return Number((Math.max(0,e)/1073741824*t.estimatedStorageUsdPerGbMonth).toFixed(4))}var Wn=/(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key|session)/i,Jn=/\b(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;&\[]+/gi,Zn=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,wn=/\b(?:\d{1,3}\.){3}\d{1,3}\b/g;function $t(e,t={}){let r=e.replace(/([?&][^=&#\s]+)=([^&#\s]*)/g,"$1=[REDACTED]").replace(Jn,"[REDACTED]");if(t.redactEmail!==!1)r=r.replace(Zn,"[EMAIL]");if(t.redactIp)r=r.replace(wn,"[IP]");for(let s of t.patterns??[])r=r.replace(s,"[REDACTED]");return r}function Re(e,t={},r){if(r&&Wn.test(r))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return $t(e,t);if(Array.isArray(e))return e.map((s)=>Re(s,t));if(e&&typeof e==="object"){let s={};for(let[n,i]of Object.entries(e))s[n]=Re(i,t,n);return s}return String(e??"")}function ns(e){if(!e)return;return e.split("?",1)[0].replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi,":id").replace(/\/(?:(?:\d{4,})|(?:[0-9a-f]{16,}))(?:\/|$)/gi,(r)=>r.endsWith("/")?"/:id/":"/:id").slice(0,512)}var is=65536,ei=2678400000,ti=new Set(["metric","log","trace","request","event"]);function p(e){return typeof e==="string"?e:void 0}function Oe(e){return e==null?void 0:Number(e)}function ri(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function Ze(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:p(e.environment_id),resourceId:p(e.resource_id),kind:String(e.kind),source:String(e.source),name:String(e.name),timestamp:String(e.timestamp),observedAt:String(e.observed_at),value:Oe(e.value),unit:p(e.unit),level:p(e.level),message:p(e.message),durationMs:Oe(e.duration_ms),statusCode:Oe(e.status_code),method:p(e.method),host:p(e.host),pathTemplate:p(e.path_template),bytesIn:Oe(e.bytes_in),bytesOut:Oe(e.bytes_out),region:p(e.region),cacheResult:p(e.cache_result),upstream:p(e.upstream),traceId:p(e.trace_id),requestId:p(e.request_id),deploymentId:p(e.deployment_id),releaseId:p(e.release_id),workloadId:p(e.workload_id),sampled:Number(e.sampled)===1,attributes:ri(e.attributes),ingestedBytes:Number(e.ingested_bytes)}}function re(e,t){let r=new Date(e);if(!e||!Number.isFinite(r.getTime()))throw Error(`${t} must be a valid ISO-8601 instant.`);return r}function we(e){let t=re(e.from,"from"),r=re(e.to,"to");if(t>=r)throw Error("Telemetry from must be earlier than to.");if(r.getTime()-t.getTime()>ei)throw Error("Telemetry queries are limited to 31 days.");return{from:t,to:r}}function Es(e){if(!e)return;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(typeof t?.timestamp!=="string"||typeof t?.id!=="string")throw Error();return t}catch{throw Error("Telemetry cursor is invalid.")}}function as(e){return e?Buffer.from(JSON.stringify({timestamp:e.timestamp,id:e.id})).toString("base64url"):void 0}function si(e,t){if(!e.length)return;let r=[...e].sort((n,i)=>n-i),s=Math.max(0,Math.min(r.length-1,Math.ceil(t/100*r.length)-1));return r[s]}function Ae(e,t){if(t==="count")return e.length;if(!e.length)return;if(t==="sum")return e.reduce((r,s)=>r+s,0);if(t==="avg")return e.reduce((r,s)=>r+s,0)/e.length;if(t==="min")return Math.min(...e);if(t==="max")return Math.max(...e);return si(e,Number(t.slice(1)))}function ni(e,t="UTC"){try{return new Intl.DateTimeFormat("en-US",{timeZone:t,month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZoneName:"short"}).format(e)}catch{throw Error(`Unknown telemetry timezone: ${t}`)}}class qt{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return this.options.now?.()??new Date}append(e){if(!ti.has(e.kind))throw Error(`Unsupported telemetry kind: ${e.kind}`);let t=re(e.timestamp,"timestamp").toISOString(),r=e.observedAt?re(e.observedAt,"observedAt").toISOString():this.now().toISOString(),s=Re(e.attributes??{},this.options.redaction),n=e.message?$t(e.message,this.options.redaction).slice(0,32768):void 0,i=ns(e.pathTemplate),E=e.id??crypto.randomUUID(),a=JSON.stringify({...e,id:E,timestamp:t,observedAt:r,attributes:s,message:n,pathTemplate:i}),d=Buffer.byteLength(a);if(d>is)throw Error(`Telemetry records are limited to ${is} bytes.`);return this.controlPlane.database.run("INSERT OR IGNORE INTO telemetry_records (id, project_id, environment_id, resource_id, kind, source, name, timestamp, observed_at, value, unit, level, message, duration_ms, status_code, method, host, path_template, bytes_in, bytes_out, region, cache_result, upstream, trace_id, request_id, deployment_id, release_id, workload_id, sampled, attributes, ingested_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[E,e.projectId,e.environmentId??null,e.resourceId??null,e.kind,e.source.slice(0,128),e.name.slice(0,256),t,r,e.value??null,e.unit??null,e.level??null,n??null,e.durationMs??null,e.statusCode??null,e.method?.slice(0,16)??null,e.host?.slice(0,256)??null,i??null,e.bytesIn??null,e.bytesOut??null,e.region?.slice(0,64)??null,e.cacheResult?.slice(0,64)??null,e.upstream?.slice(0,256)??null,e.traceId?.slice(0,256)??null,e.requestId?.slice(0,256)??null,e.deploymentId?.slice(0,256)??null,e.releaseId?.slice(0,256)??null,e.workloadId?.slice(0,512)??null,e.sampled===!1?0:1,JSON.stringify(s),d]),this.get(E)}appendMany(e){if(e.length>1e4)throw Error("Telemetry batches are limited to 10,000 records.");return this.controlPlane.database.transaction((r)=>r.map((s)=>this.append(s)))(e)}get(e){let t=this.controlPlane.database.query("SELECT * FROM telemetry_records WHERE id=?").get(e);return t?Ze(t):void 0}query(e){let{from:t,to:r}=we(e),s=Math.min(5000,Math.max(1,Math.floor(e.limit??500))),n=["project_id=?","timestamp>=?","timestamp<?"],i=[e.projectId,t.toISOString(),r.toISOString()],E=(C,g)=>{if(g)n.push(`${C}=?`),i.push(g)},a=(C,g)=>{let R=[...new Set(g??[])].slice(0,100);if(R.length)n.push(`${C} IN (${R.map(()=>"?").join(",")})`),i.push(...R)};if(E("environment_id",e.environmentId),a("resource_id",e.resourceIds),a("kind",e.kinds),a("name",e.names),a("source",e.sources),a("level",e.levels),E("trace_id",e.traceId),E("request_id",e.requestId),E("deployment_id",e.deploymentId),E("release_id",e.releaseId),E("workload_id",e.workloadId),e.text)n.push("(message LIKE ? OR name LIKE ?)"),i.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let d=Es(e.cursor);if(d)n.push("(timestamp<? OR (timestamp=? AND id<?))"),i.push(d.timestamp,d.timestamp,d.id);let T=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${n.join(" AND ")} ORDER BY timestamp DESC, id DESC LIMIT ?`).all(...i,s+1),N=T.slice(0,s).map(Ze),o=T.length>s,c=new Map;for(let C of N)c.set(C.source,[...c.get(C.source)??[],C]);let l=this.now().getTime(),_=[...c].map(([C,g])=>{let R=g.reduce((y,X)=>X.observedAt>y?X.observedAt:y,g[0].observedAt),S=l-new Date(R).getTime();return{source:C,latestAt:R,freshness:S<=120000?"live":S<=600000?"stale":"unavailable",count:g.length}}),L=Math.max(60000,(r.getTime()-t.getTime())/100),u=[...c].flatMap(([C,g])=>{let R=[...new Set(g.map((S)=>new Date(S.timestamp).getTime()))].sort((S,y)=>S-y);return R.slice(1).flatMap((S,y)=>S-R[y]>L?[{from:new Date(R[y]).toISOString(),to:new Date(S).toISOString(),source:C}]:[])});return{records:N,nextCursor:o?as(N.at(-1)):void 0,truncated:o,scannedRange:{from:t.toISOString(),to:r.toISOString()},sources:_,gaps:u}}tail(e,t){let{from:r,to:s}=we(e),n=Math.min(1000,Math.max(1,Math.floor(e.limit??200))),i=["project_id=?","timestamp>=?","timestamp<?"],E=[e.projectId,r.toISOString(),s.toISOString()],a=(c,l)=>{if(l)i.push(`${c}=?`),E.push(l)},d=(c,l)=>{let _=[...new Set(l??[])].slice(0,100);if(_.length)i.push(`${c} IN (${_.map(()=>"?").join(",")})`),E.push(..._)};if(a("environment_id",e.environmentId),d("resource_id",e.resourceIds),d("kind",e.kinds),d("name",e.names),d("source",e.sources),d("level",e.levels),a("trace_id",e.traceId),a("request_id",e.requestId),a("deployment_id",e.deploymentId),a("release_id",e.releaseId),a("workload_id",e.workloadId),e.text)i.push("(message LIKE ? OR name LIKE ?)"),E.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let T=Es(t);if(T)i.push("(timestamp>? OR (timestamp=? AND id>?))"),E.push(T.timestamp,T.timestamp,T.id);let N=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${i.join(" AND ")} ORDER BY timestamp ASC, id ASC LIMIT ?`).all(...E,n+1),o=N.slice(0,n).map(Ze);return{records:o,cursor:as(o.at(-1))??t,truncated:N.length>n}}series(e){let{from:t,to:r}=we(e),s=Math.min(86400000,Math.max(1000,Math.floor(e.bucketMs)));if((r.getTime()-t.getTime())/s>2000)throw Error("Telemetry series are limited to 2,000 buckets.");let n=this.query({...e,kinds:["metric"],limit:5000,cursor:void 0}),i=new Map;for(let a of n.records)i.set(`${a.source}\x00${a.name}`,[...i.get(`${a.source}\x00${a.name}`)??[],a]);let E=(a,d,T)=>{let N=new Map;for(let c of a){let l=d.getTime()+Math.floor((new Date(c.timestamp).getTime()-d.getTime())/s)*s;if(l>=d.getTime()&&l<T.getTime()&&c.value!=null)N.set(l,[...N.get(l)??[],c.value])}let o=[];for(let c=d.getTime();c<T.getTime();c+=s){let l=N.get(c)??[],_=Ae(l,e.aggregation);o.push({timestamp:new Date(c).toISOString(),label:ni(new Date(c),e.timezone),value:_,count:l.length,gap:_==null})}return o};return[...i].map(([a,d])=>{let[T,N]=a.split("\x00"),o={name:N,source:T,unit:d.find((c)=>c.unit)?.unit,aggregation:e.aggregation,bucketMs:s,points:E(d,t,r)};if(e.compareFrom&&e.compareTo){let c=this.query({...e,from:e.compareFrom,to:e.compareTo,kinds:["metric"],limit:5000,cursor:void 0}).records.filter((l)=>l.source===T&&l.name===N);o.comparison=E(c,re(e.compareFrom,"compareFrom"),re(e.compareTo,"compareTo"))}return o})}status(e,t,r=30,s=1,n){let i=[e],E=t?" AND environment_id=?":"";if(t)i.push(t);let a=[...new Set(n??[])].slice(0,100);if(n&&a.length===0)return[];let d=n?` AND resource_id IN (${a.map(()=>"?").join(",")||"''"})`:"";i.push(...a);let T=this.controlPlane.database.query(`SELECT source, MAX(latest_observed_at) latest, SUM(ingested_bytes) bytes, SUM(record_count) count, MIN(first_observed_at) first FROM telemetry_source_rollups WHERE project_id=?${E}${d} GROUP BY source`).all(...i),N=this.now().getTime();return T.map((o)=>{let c=String(o.latest),l=Math.max(0,Math.floor((N-new Date(c).getTime())/1000)),_=Math.max(1,(new Date(c).getTime()-new Date(String(o.first)).getTime())/86400000);return{source:String(o.source),freshness:l<=120?"live":l<=600?"stale":"unavailable",lastObservedAt:c,lagSeconds:l,samplingRate:s,retentionDays:r,estimatedDailyBytes:Math.round(Number(o.bytes)/_)}})}saveQuery(e,t,r,s){let n=r.trim().slice(0,80);if(!n)throw Error("Saved telemetry queries require a name.");if(we(s),s.projectId!==e)throw Error("Saved telemetry queries cannot cross project scope.");let i=this.now().toISOString(),E=JSON.stringify(Re(s,this.options.redaction));if(Buffer.byteLength(E)>16384)throw Error("Saved telemetry queries are limited to 16 KB.");let a=this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? AND name=?").get(e,t??null,n),d=a?String(a.id):crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO telemetry_saved_queries (id, project_id, actor_id, name, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, actor_id, name) DO UPDATE SET query=excluded.query, updated_at=excluded.updated_at",[d,e,t??null,n,E,a?String(a.created_at):i,i]),{id:d,projectId:e,actorId:t,name:n,query:JSON.parse(E),createdAt:a?String(a.created_at):i,updatedAt:i}}listSavedQueries(e,t){return this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? ORDER BY updated_at DESC").all(e,t??null).map((r)=>({id:String(r.id),projectId:String(r.project_id),actorId:p(r.actor_id),name:String(r.name),query:JSON.parse(String(r.query)),createdAt:String(r.created_at),updatedAt:String(r.updated_at)}))}deleteSavedQuery(e,t,r){return this.controlPlane.database.run("DELETE FROM telemetry_saved_queries WHERE id=? AND project_id=? AND actor_id IS ?",[r,e,t??null]).changes>0}downsample(e,t){let r=Math.min(86400000,Math.max(60000,Math.floor(e.downsampleBucketMs))),s=new Date(this.now().getTime()-Math.max(1,e.downsampleAfterDays)*86400000).toISOString(),n=new Date(this.now().getTime()-Math.max(1,e.rawDays)*86400000).toISOString(),i=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE kind='metric' AND source NOT LIKE '%:rollup' AND timestamp>=? AND timestamp<?${t?" AND project_id=?":""} ORDER BY timestamp ASC LIMIT 50001`).all(n,s,...t?[t]:[]);if(i.length>50000)throw Error("Telemetry downsampling is limited to 50,000 raw points per pass; run compaction more frequently.");let E=i.map(Ze),a=new Map;for(let T of E){let N=Math.floor(new Date(T.timestamp).getTime()/r)*r,o=JSON.stringify([T.projectId,T.environmentId??"",T.resourceId??"",T.source,T.name,T.unit??"",N]);a.set(o,[...a.get(o)??[],T])}return this.controlPlane.database.transaction(()=>{for(let T=0;T<E.length;T+=500){let N=E.slice(T,T+500).map((o)=>o.id);if(N.length)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (${N.map(()=>"?").join(",")})`,N)}for(let[T,N]of a){let[o,c,l,_,L,u,C]=JSON.parse(T),g=N.flatMap((R)=>R.value==null?[]:[R.value]);this.append({projectId:o,environmentId:c||void 0,resourceId:l||void 0,kind:"metric",source:`${_}:rollup`,name:L,unit:u||void 0,timestamp:new Date(C).toISOString(),value:Ae(g,"avg"),attributes:{downsampled:!0,count:g.length,min:Ae(g,"min"),max:Ae(g,"max"),p95:Ae(g,"p95"),bucketMs:r}})}})(),{compacted:E.length,rollups:a.size}}enforceRetention(e,t){let r=this.downsample(e,t),s=Math.min(3650,Math.max(1,Math.floor(e.rawDays))),n=new Date(this.now().getTime()-s*86400000).toISOString(),i=t?" AND project_id=?":"",E=this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE timestamp<?${i}`,t?[n,t]:[n]).changes,a=Number(this.controlPlane.database.query(`SELECT MAX(0, COUNT(*)-?) excess FROM telemetry_records${t?" WHERE project_id=?":""}`).get(e.maxRecords,...t?[t]:[])?.excess??0);if(a>0)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (SELECT id FROM telemetry_records${t?" WHERE project_id=?":""} ORDER BY timestamp ASC LIMIT ?)`,t?[t,a]:[a]);return this.rebuildStatusRollups(t),{deleted:E+a,...r}}rebuildStatusRollups(e){let t=e?" WHERE project_id=?":"",r=e?[e]:[];this.controlPlane.database.transaction(()=>{this.controlPlane.database.run(`DELETE FROM telemetry_source_rollups${t}`,r),this.controlPlane.database.run(`INSERT INTO telemetry_source_rollups (
|
|
1543
1543
|
project_id, environment_id, resource_id, source,
|
|
1544
1544
|
first_observed_at, latest_observed_at, ingested_bytes, record_count
|
|
1545
1545
|
)
|
|
@@ -1547,14 +1547,14 @@ ${JSON.stringify(t,null,2)}`}),{ok:!0,status:202}}if(e.kind==="sms"){if(!this.op
|
|
|
1547
1547
|
project_id, COALESCE(environment_id, ''), COALESCE(resource_id, ''), source,
|
|
1548
1548
|
MIN(observed_at), MAX(observed_at), SUM(ingested_bytes), COUNT(*)
|
|
1549
1549
|
FROM telemetry_records${t}
|
|
1550
|
-
GROUP BY project_id, COALESCE(environment_id, ''), COALESCE(resource_id, ''), source`,r)})()}}function Ja(e,t,r,n=new Date){let i=new Vt(e.controlPlane,{now:()=>n}),o=new fe(e);return e.listRules(t,r).filter((s)=>s.enabled&&!s.healthCheckId).map((s)=>{let a=new Date(n.getTime()-s.windowMs).toISOString(),d=i.query({projectId:t,environmentId:r,resourceIds:s.resourceId?[s.resourceId]:void 0,kinds:["metric"],names:[s.signal],from:a,to:new Date(n.getTime()+1).toISOString(),limit:5000}),c=d.records.flatMap((l)=>l.value==null?[]:[l.value]),p=c.length?s.operator==="gt"||s.operator==="gte"?Math.max(...c):s.operator==="lt"||s.operator==="lte"?Math.min(...c):c.at(0):void 0;return o.evaluate(s,{value:p,status:p==null?"no_data":void 0,timestamp:n.toISOString(),group:{resourceId:s.resourceId??"",source:d.records[0]?.source??""},evidence:{signal:s.signal,windowMs:s.windowMs,sampleCount:c.length,source:d.records[0]?.source??null}})})}var cd=["spend.enforced"];function so(e){if(e.level==="hard_capped")return"critical";if(e.level==="soft_capped")return"warning";return"info"}function Ie(e,t="USD"){let r=e/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:t}).format(r)}catch{return`${r.toFixed(2)} ${t}`}}function ao(e,t,r){let n=Ie(t.projection.actualCents,e.currency),i=e.hardLimitCents??e.softLimitCents,o=i==null?"":` of ${Ie(i,e.currency)}`,s=t.simulated?" [dry run]":"";if(r==="spend.released")return`[RESOLVED] ${e.name}: spend fell back to ${n}${o}.${s}`;if(r==="spend.enforced"){let c=t.actions.filter((p)=>p!=="notify").join(", ");return`[CAP] ${e.name}: ${n}${o} (${t.usedPercent.toFixed(0)}%). Enforcing ${c||"notifications only"}.${s}`}let a=ge(t.projection.timeToExhaustionMs),d=a?` Projected to reach the limit in ${a}.`:` Projected ${Ie(t.projection.projectedCents,e.currency)} by period end.`;return`[SPEND] ${e.name}: ${n}${o} (${t.usedPercent.toFixed(0)}%).${d}${s}`}function ln(e,t,r){return{schemaVersion:1,event:r,notificationText:ao(e,t,r),spend:{budgetId:e.id,budgetName:e.name,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,period:e.period,currency:e.currency,level:t.level,simulated:t.simulated,usedPercent:Math.round(t.usedPercent*10)/10,projectedPercent:Math.round(t.projectedPercent*10)/10,actualCents:Math.round(t.projection.actualCents),projectedCents:Math.round(t.projection.projectedCents),projectionConfidence:t.projection.confidence,softLimitCents:e.softLimitCents??null,hardLimitCents:e.hardLimitCents??null,timeToCap:ge(t.projection.timeToExhaustionMs),actions:t.actions,window:{start:t.window.start,end:t.window.end,label:t.window.label},reason:t.reason}}}function co(e,t){return{schemaVersion:1,event:"spend.anomaly",notificationText:`[ANOMALY] Hourly spend ${Number.isFinite(e.deltaPercent)?`${e.deltaPercent>0?"+":""}${e.deltaPercent.toFixed(0)}%`:"new"} vs the usual ${Ie(e.expected,t)} for this hour (observed ${Ie(e.observed,t)}).`,spend:{anomalyId:e.id,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,signal:e.signal,direction:e.direction,severity:e.severity,observedCents:Math.round(e.observed),expectedCents:Math.round(e.expected),score:Math.round(e.score*10)/10,bucketStart:e.bucketStart}}}function lo(e,t,r,n){let i=e.matcher;if(i.projectIds?.length&&(!t.projectId||!i.projectIds.includes(t.projectId)))return!1;if(i.environmentIds?.length&&(!t.environmentId||!i.environmentIds.includes(t.environmentId)))return!1;if(i.severities?.length&&!i.severities.includes(r))return!1;if(i.eventTypes?.length&&!i.eventTypes.includes(n))return!1;return!0}class Kt{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}channelsFor(e,t,r,n){let i=[];for(let o of this.store.listRoutes(e)){if(!o.enabled||!lo(o,t,r,n))continue;let s=o.channelIds.map((a)=>this.store.getChannel(a)).filter((a)=>a?.status==="active");i.push({route:o,channels:s,quiet:qt(o,this.now())})}return i}dispatch(e,t,r,n,i,o){let s=[],a=[];for(let d of this.channelsFor(e,t,r,n)){if(d.quiet&&n!=="spend.released"){a.push(d.route.id);continue}let c=this.store.countRouteDeliveries(d.route.id,new Date(this.now().getTime()-60000).toISOString()),p=Math.max(0,d.route.rateLimitPerMinute-c);for(let l of d.channels){if(p<=0)break;s.push(this.store.createDelivery({channelId:l.id,routeId:d.route.id,eventType:n,idempotencyKey:`spend:${n}:${o}:${l.id}`,payload:i,nextAttemptAt:d.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+d.route.groupWaitSeconds*1000).toISOString()})),p--}}return{deliveries:s,suppressed:a}}notifyDecision(e,t){if(t.breaches.length===0)return{deliveries:[],suppressed:[]};let n=t.actions.some((o)=>o!=="notify")?"spend.enforced":"spend.threshold",i=t.breaches[t.breaches.length-1].atPercent;return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},so(t),n,ln(e,t,n),`${e.id}:${t.window.start}:${i}`)}notifyRelease(e,t,r){if(r.length===0)return{deliveries:[],suppressed:[]};return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},"info","spend.released",{...ln(e,t,"spend.released"),released:[...r]},`${e.id}:${t.window.start}:${[...r].sort().join("+")}`)}notifyAnomaly(e,t="USD"){return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},e.severity,"spend.anomaly",co(e,t),e.id)}}var ud="spend.loop.lease";function uo(){return`${typeof process>"u"?"unknown":String(process.pid)}:${crypto.randomUUID().slice(0,8)}`}class po{controlPlane;owner;ttlMs;constructor(e,t={}){this.controlPlane=e;this.owner=t.owner??uo(),this.ttlMs=Math.max(5000,(t.ttlSeconds??120)*1000),this.nowFn=t.now??(()=>new Date)}nowFn;read(){let e=this.controlPlane.getSetting("spend.loop.lease");if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.owner!=="string"||typeof t.expiresAt!=="string")return;return t}current(){let e=this.read();if(!e)return;return new Date(e.expiresAt).getTime()>this.nowFn().getTime()?e:void 0}acquire(){let e=this.nowFn();return this.controlPlane.database.transaction(()=>{let r=this.read(),n=r&&new Date(r.expiresAt).getTime()>e.getTime();if(n&&r.owner!==this.owner)return!1;let i={owner:this.owner,acquiredAt:n?r.acquiredAt:e.toISOString(),expiresAt:new Date(e.getTime()+this.ttlMs).toISOString()};return this.controlPlane.setSetting("spend.loop.lease",i),!0})()}release(){return this.controlPlane.database.transaction(()=>{let t=this.read();if(!t||t.owner!==this.owner)return!1;return this.controlPlane.setSetting("spend.loop.lease",null),!0})()}held(){return this.current()?.owner===this.owner}}var un={applied:0,duplicates:0,costCents:0,unpricedMeters:[]};class Eo{options;gate;service;notifications;constructor(e){this.options=e;this.gate=new Ne(e.controlPlane,{now:e.now}),this.service=new xt(e.store),this.notifications=e.alerts?new Kt(e.alerts,{now:e.now}):void 0}now(){return this.options.now?.()??new Date}ingest(e,t,r){if(t.length===0)return{...un};return this.service.ingestTelemetry(e,t,r)}async run(e,t=[]){let r=this.now(),n=[],i={scope:e,ingested:{...un},decisions:[],applied:[],released:[],failed:[],withheld:[],anomalies:[],notificationsSent:0,ranAt:r.toISOString(),durationMs:0,warnings:n};try{if(i.ingested=this.ingest(e.organizationId,t),i.ingested.unpricedMeters.length>0)n.push(`No price entry for ${i.ingested.unpricedMeters.join(", ")}; that usage is metered but counts as zero against every budget.`)}catch(a){n.push(`Usage ingest failed: ${Se(a)}`)}let o=$r({gate:this.gate,transport:this.options.transport}),s;try{s=await this.service.runCycle({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,environmentKind:e.environmentKind,policy:this.options.policy,now:r,handlers:o})}catch(a){return n.push(`Spend evaluation failed: ${Se(a)}`),i.durationMs=this.now().getTime()-r.getTime(),i}i.decisions=s.statuses.map((a)=>a.decision),i.anomalies=s.anomalies;for(let a of s.enforcement)i.applied.push(...a.applied.map((d)=>d.action)),i.released.push(...a.released.map((d)=>d.action)),i.failed.push(...a.failed),i.withheld.push(...a.withheld.map((d)=>d.action));for(let a of i.failed)n.push(`Enforcement for ${a.action} did not complete: ${a.error}`);if(i.withheld.length>0)n.push(`${i.withheld.join(", ")} require approval on this environment and were not applied automatically.`);try{i.released.push(...this.reconcileGate(e))}catch(a){n.push(`Gate reconciliation failed: ${Se(a)}`)}if(this.notifications)try{for(let a of s.statuses)if(i.notificationsSent+=this.notifications.notifyDecision(a.budget,a.decision).deliveries.length,a.decision.releases.length>0)i.notificationsSent+=this.notifications.notifyRelease(a.budget,a.decision,a.decision.releases).deliveries.length;for(let a of s.anomalies)i.notificationsSent+=this.notifications.notifyAnomaly(a,this.options.store.priceBook.currency).deliveries.length}catch(a){n.push(`Spend notifications failed: ${Se(a)}`)}try{this.options.store.pruneUsage(this.options.retentionDays??400,r)}catch(a){n.push(`Usage pruning failed: ${Se(a)}`)}return i.durationMs=this.now().getTime()-r.getTime(),i}reconcileGate(e){let t=new Map(this.options.store.listBudgets({organizationId:e.organizationId}).filter((n)=>n.enabled).map((n)=>[n.id,n])),r=[];for(let n of this.gate.listUnder({organizationId:e.organizationId})){if(t.has(n.budgetId))continue;this.gate.close(n.budgetId,n.action),r.push(n.action)}return r}async runAll(e=[]){let t=[];for(let r of this.options.controlPlane.listOrganizations()){t.push(await this.run({organizationId:r.id},e));for(let n of this.options.controlPlane.listProjects().filter((i)=>i.organizationId===r.id))for(let i of this.options.controlPlane.listEnvironments(n.id))t.push(await this.run({organizationId:r.id,projectId:n.id,environmentId:i.id,environmentKind:i.kind}))}return t}}function Se(e){return e instanceof Error?e.message:String(e)}var mo=60;function _d(e,t={}){let r=Math.max(10,t.intervalSeconds??mo)*1000,n=!1,i=!1,o=async()=>{if(n||i)return;if(t.lease&&!t.lease.acquire()){t.onSkip?.(t.lease.current()?.owner??"another process");return}n=!0;try{let a=await e.runAll();t.onResult?.(a)}catch(a){t.onError?.(a)}finally{n=!1}},s=setInterval(()=>void o(),r);if(s.unref?.(),t.immediate)o();return()=>{i=!0,clearInterval(s),t.lease?.release()}}function be(e,t){if(t.code!==0)throw Error(`${e} failed (exit ${t.code}): ${t.stderr.trim().slice(0,400)}`)}class To{options;constructor(e){this.options=e}async targets(e){let t=await this.options.functions(e);if(t.length===0)throw Error("No Lambda functions were resolved for this scope.");return t}async suspendFunctions(e){let t=await this.targets(e),r={};for(let n of t)r[n]=await this.options.lambda.getFunctionConcurrency(n),await this.options.lambda.putFunctionConcurrency(n,0);return{kind:"lambda_reserved_concurrency",previous:r}}async resumeFunctions(e){let t=e.previous??{};for(let[r,n]of Object.entries(t))if(typeof n==="number")await this.options.lambda.putFunctionConcurrency(r,n);else await this.options.lambda.deleteFunctionConcurrency(r)}async serveStatic(e){return{...await this.suspendFunctions(e),via:"serve_static"}}async restoreDynamic(e){await this.resumeFunctions(e)}async suspendProject(e){let t=await this.targets(e),r={};for(let n of t){let o={...(await this.options.lambda.getFunction(n)).Configuration?.Environment?.Variables??{}};r[n]=o.MAINTENANCE_MODE??null,await this.options.lambda.updateFunctionConfiguration({FunctionName:n,Environment:{Variables:{...o,MAINTENANCE_MODE:"1"}}}),await this.options.republish?.(n)}return{kind:"lambda_maintenance_mode",previous:r}}async resumeProject(e){let t=e.previous??{};for(let r of Object.keys(t)){let i={...(await this.options.lambda.getFunction(r)).Configuration?.Environment?.Variables??{}};i.MAINTENANCE_MODE=typeof t[r]==="string"?t[r]:"0",await this.options.lambda.updateFunctionConfiguration({FunctionName:r,Environment:{Variables:i}}),await this.options.republish?.(r)}}}class go{options;constructor(e){this.options=e}async unitsFor(e){let t=await this.options.units(e);if(t.length===0)throw Error("No systemd units were resolved for this scope.");for(let r of t)if(!/^[A-Za-z0-9@._-]+$/.test(r))throw Error(`Refusing to act on an unsafe unit name: ${r}`);return t}async stopUnits(e,t){let r=await this.unitsFor(e),n=[];for(let i of r){let o=await this.options.exec(this.options.host,`systemctl list-units --plain --no-legend --state=active --type=service '${i}@*.service' '${i}.service' 2>/dev/null | awk '{print $1}'`);be(`listing units for ${i}`,o);let s=o.stdout.split(`
|
|
1551
|
-
`).map((a)=>a.trim()).filter((a)=>/^[A-Za-z0-9@._-]+\.service$/.test(a));for(let a of
|
|
1552
|
-
${o}
|
|
1553
|
-
TS_CLOUD_THROTTLE_EOF`);return be("applying the throttled firewall ruleset",s),{kind:"nftables_throttle",factor:e.factor,previousThresholds:r.thresholds??{}}}async restoreRequests(e){let t=this.options.renderDdos,r=this.options.ddos;if(!t||!r)return;let n=e.previousThresholds??{},i=t({...r,thresholds:n}),o=await this.options.exec(this.options.host,`bash -s <<'TS_CLOUD_THROTTLE_EOF'
|
|
1550
|
+
GROUP BY project_id, COALESCE(environment_id, ''), COALESCE(resource_id, ''), source`,r)})()}}function Wa(e,t,r,s=new Date){let n=new qt(e.controlPlane,{now:()=>s}),i=new ge(e);return e.listRules(t,r).filter((E)=>E.enabled&&!E.healthCheckId).map((E)=>{let a=new Date(s.getTime()-E.windowMs).toISOString(),d=n.query({projectId:t,environmentId:r,resourceIds:E.resourceId?[E.resourceId]:void 0,kinds:["metric"],names:[E.signal],from:a,to:new Date(s.getTime()+1).toISOString(),limit:5000}),T=d.records.flatMap((o)=>o.value==null?[]:[o.value]),N=T.length?E.operator==="gt"||E.operator==="gte"?Math.max(...T):E.operator==="lt"||E.operator==="lte"?Math.min(...T):T.at(0):void 0;return i.evaluate(E,{value:N,status:N==null?"no_data":void 0,timestamp:s.toISOString(),group:{resourceId:E.resourceId??"",source:d.records[0]?.source??""},evidence:{signal:E.signal,windowMs:E.windowMs,sampleCount:T.length,source:d.records[0]?.source??null}})})}var ad=["spend.enforced"];function ii(e){if(e.level==="hard_capped")return"critical";if(e.level==="soft_capped")return"warning";return"info"}function Ue(e,t="USD"){let r=e/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:t}).format(r)}catch{return`${r.toFixed(2)} ${t}`}}function Ei(e,t,r){let s=Ue(t.projection.actualCents,e.currency),n=e.hardLimitCents??e.softLimitCents,i=n==null?"":` of ${Ue(n,e.currency)}`,E=t.simulated?" [dry run]":"";if(r==="spend.released")return`[RESOLVED] ${e.name}: spend fell back to ${s}${i}.${E}`;if(r==="spend.enforced"){let T=t.actions.filter((N)=>N!=="notify").join(", ");return`[CAP] ${e.name}: ${s}${i} (${t.usedPercent.toFixed(0)}%). Enforcing ${T||"notifications only"}.${E}`}let a=Le(t.projection.timeToExhaustionMs),d=a?` Projected to reach the limit in ${a}.`:` Projected ${Ue(t.projection.projectedCents,e.currency)} by period end.`;return`[SPEND] ${e.name}: ${s}${i} (${t.usedPercent.toFixed(0)}%).${d}${E}`}function ds(e,t,r){return{schemaVersion:1,event:r,notificationText:Ei(e,t,r),spend:{budgetId:e.id,budgetName:e.name,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,period:e.period,currency:e.currency,level:t.level,simulated:t.simulated,usedPercent:Math.round(t.usedPercent*10)/10,projectedPercent:Math.round(t.projectedPercent*10)/10,actualCents:Math.round(t.projection.actualCents),projectedCents:Math.round(t.projection.projectedCents),projectionConfidence:t.projection.confidence,softLimitCents:e.softLimitCents??null,hardLimitCents:e.hardLimitCents??null,timeToCap:Le(t.projection.timeToExhaustionMs),actions:t.actions,window:{start:t.window.start,end:t.window.end,label:t.window.label},reason:t.reason}}}function ai(e,t){return{schemaVersion:1,event:"spend.anomaly",notificationText:`[ANOMALY] Hourly spend ${Number.isFinite(e.deltaPercent)?`${e.deltaPercent>0?"+":""}${e.deltaPercent.toFixed(0)}%`:"new"} vs the usual ${Ue(e.expected,t)} for this hour (observed ${Ue(e.observed,t)}).`,spend:{anomalyId:e.id,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,signal:e.signal,direction:e.direction,severity:e.severity,observedCents:Math.round(e.observed),expectedCents:Math.round(e.expected),score:Math.round(e.score*10)/10,bucketStart:e.bucketStart}}}function di(e,t,r,s){let n=e.matcher;if(n.projectIds?.length&&(!t.projectId||!n.projectIds.includes(t.projectId)))return!1;if(n.environmentIds?.length&&(!t.environmentId||!n.environmentIds.includes(t.environmentId)))return!1;if(n.severities?.length&&!n.severities.includes(r))return!1;if(n.eventTypes?.length&&!n.eventTypes.includes(s))return!1;return!0}class Yt{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}channelsFor(e,t,r,s){let n=[];for(let i of this.store.listRoutes(e)){if(!i.enabled||!di(i,t,r,s))continue;let E=i.channelIds.map((a)=>this.store.getChannel(a)).filter((a)=>a?.status==="active");n.push({route:i,channels:E,quiet:jt(i,this.now())})}return n}dispatch(e,t,r,s,n,i){let E=[],a=[];for(let d of this.channelsFor(e,t,r,s)){if(d.quiet&&s!=="spend.released"){a.push(d.route.id);continue}let T=this.store.countRouteDeliveries(d.route.id,new Date(this.now().getTime()-60000).toISOString()),N=Math.max(0,d.route.rateLimitPerMinute-T);for(let o of d.channels){if(N<=0)break;E.push(this.store.createDelivery({channelId:o.id,routeId:d.route.id,eventType:s,idempotencyKey:`spend:${s}:${i}:${o.id}`,payload:n,nextAttemptAt:d.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+d.route.groupWaitSeconds*1000).toISOString()})),N--}}return{deliveries:E,suppressed:a}}notifyDecision(e,t){if(t.breaches.length===0)return{deliveries:[],suppressed:[]};let s=t.actions.some((i)=>i!=="notify")?"spend.enforced":"spend.threshold",n=t.breaches[t.breaches.length-1].atPercent;return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},ii(t),s,ds(e,t,s),`${e.id}:${t.window.start}:${n}`)}notifyRelease(e,t,r){if(r.length===0)return{deliveries:[],suppressed:[]};return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},"info","spend.released",{...ds(e,t,"spend.released"),released:[...r]},`${e.id}:${t.window.start}:${[...r].sort().join("+")}`)}notifyAnomaly(e,t="USD"){return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},e.severity,"spend.anomaly",ai(e,t),e.id)}}var Td="spend.loop.lease";function Ti(){return`${typeof process>"u"?"unknown":String(process.pid)}:${crypto.randomUUID().slice(0,8)}`}class oi{controlPlane;owner;ttlMs;constructor(e,t={}){this.controlPlane=e;this.owner=t.owner??Ti(),this.ttlMs=Math.max(5000,(t.ttlSeconds??120)*1000),this.nowFn=t.now??(()=>new Date)}nowFn;read(){let e=this.controlPlane.getSetting("spend.loop.lease");if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.owner!=="string"||typeof t.expiresAt!=="string")return;return t}current(){let e=this.read();if(!e)return;return new Date(e.expiresAt).getTime()>this.nowFn().getTime()?e:void 0}acquire(){let e=this.nowFn();return this.controlPlane.database.transaction(()=>{let r=this.read(),s=r&&new Date(r.expiresAt).getTime()>e.getTime();if(s&&r.owner!==this.owner)return!1;let n={owner:this.owner,acquiredAt:s?r.acquiredAt:e.toISOString(),expiresAt:new Date(e.getTime()+this.ttlMs).toISOString()};return this.controlPlane.setSetting("spend.loop.lease",n),!0})()}release(){return this.controlPlane.database.transaction(()=>{let t=this.read();if(!t||t.owner!==this.owner)return!1;return this.controlPlane.setSetting("spend.loop.lease",null),!0})()}held(){return this.current()?.owner===this.owner}}var Ts={applied:0,duplicates:0,costCents:0,unpricedMeters:[]};class ci{options;gate;service;notifications;constructor(e){this.options=e;this.gate=new Ce(e.controlPlane,{now:e.now}),this.service=new Pt(e.store),this.notifications=e.alerts?new Yt(e.alerts,{now:e.now}):void 0}now(){return this.options.now?.()??new Date}ingest(e,t,r){if(t.length===0)return{...Ts};return this.service.ingestTelemetry(e,t,r)}async run(e,t=[]){let r=this.now(),s=[],n={scope:e,ingested:{...Ts},decisions:[],applied:[],released:[],failed:[],withheld:[],anomalies:[],notificationsSent:0,ranAt:r.toISOString(),durationMs:0,warnings:s};try{if(n.ingested=this.ingest(e.organizationId,t),n.ingested.unpricedMeters.length>0)s.push(`No price entry for ${n.ingested.unpricedMeters.join(", ")}; that usage is metered but counts as zero against every budget.`)}catch(a){s.push(`Usage ingest failed: ${he(a)}`)}let i=zr({gate:this.gate,transport:this.options.transport}),E;try{E=await this.service.runCycle({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,environmentKind:e.environmentKind,policy:this.options.policy,now:r,handlers:i})}catch(a){return s.push(`Spend evaluation failed: ${he(a)}`),n.durationMs=this.now().getTime()-r.getTime(),n}n.decisions=E.statuses.map((a)=>a.decision),n.anomalies=E.anomalies;for(let a of E.enforcement)n.applied.push(...a.applied.map((d)=>d.action)),n.released.push(...a.released.map((d)=>d.action)),n.failed.push(...a.failed),n.withheld.push(...a.withheld.map((d)=>d.action));for(let a of n.failed)s.push(`Enforcement for ${a.action} did not complete: ${a.error}`);if(n.withheld.length>0)s.push(`${n.withheld.join(", ")} require approval on this environment and were not applied automatically.`);try{n.released.push(...this.reconcileGate(e))}catch(a){s.push(`Gate reconciliation failed: ${he(a)}`)}if(this.notifications)try{for(let a of E.statuses)if(n.notificationsSent+=this.notifications.notifyDecision(a.budget,a.decision).deliveries.length,a.decision.releases.length>0)n.notificationsSent+=this.notifications.notifyRelease(a.budget,a.decision,a.decision.releases).deliveries.length;for(let a of E.anomalies)n.notificationsSent+=this.notifications.notifyAnomaly(a,this.options.store.priceBook.currency).deliveries.length}catch(a){s.push(`Spend notifications failed: ${he(a)}`)}try{this.options.store.pruneUsage(this.options.retentionDays??400,r)}catch(a){s.push(`Usage pruning failed: ${he(a)}`)}return n.durationMs=this.now().getTime()-r.getTime(),n}reconcileGate(e){let t=new Map(this.options.store.listBudgets({organizationId:e.organizationId}).filter((s)=>s.enabled).map((s)=>[s.id,s])),r=[];for(let s of this.gate.listUnder({organizationId:e.organizationId})){if(t.has(s.budgetId))continue;this.gate.close(s.budgetId,s.action),r.push(s.action)}return r}async runAll(e=[]){let t=[];for(let r of this.options.controlPlane.listOrganizations()){t.push(await this.run({organizationId:r.id},e));for(let s of this.options.controlPlane.listProjects().filter((n)=>n.organizationId===r.id))for(let n of this.options.controlPlane.listEnvironments(s.id))t.push(await this.run({organizationId:r.id,projectId:s.id,environmentId:n.id,environmentKind:n.kind}))}return t}}function he(e){return e instanceof Error?e.message:String(e)}var Ni=60;function Ld(e,t={}){let r=Math.max(10,t.intervalSeconds??Ni)*1000,s=!1,n=!1,i=async()=>{if(s||n)return;if(t.lease&&!t.lease.acquire()){t.onSkip?.(t.lease.current()?.owner??"another process");return}s=!0;try{let a=await e.runAll();t.onResult?.(a)}catch(a){t.onError?.(a)}finally{s=!1}},E=setInterval(()=>void i(),r);if(E.unref?.(),t.immediate)i();return()=>{n=!0,clearInterval(E),t.lease?.release()}}function fe(e,t){if(t.code!==0)throw Error(`${e} failed (exit ${t.code}): ${t.stderr.trim().slice(0,400)}`)}class _i{options;constructor(e){this.options=e}async targets(e){let t=await this.options.functions(e);if(t.length===0)throw Error("No Lambda functions were resolved for this scope.");return t}async suspendFunctions(e){let t=await this.targets(e),r={};for(let s of t)r[s]=await this.options.lambda.getFunctionConcurrency(s),await this.options.lambda.putFunctionConcurrency(s,0);return{kind:"lambda_reserved_concurrency",previous:r}}async resumeFunctions(e){let t=e.previous??{};for(let[r,s]of Object.entries(t))if(typeof s==="number")await this.options.lambda.putFunctionConcurrency(r,s);else await this.options.lambda.deleteFunctionConcurrency(r)}async serveStatic(e){return{...await this.suspendFunctions(e),via:"serve_static"}}async restoreDynamic(e){await this.resumeFunctions(e)}async suspendProject(e){let t=await this.targets(e),r={};for(let s of t){let i={...(await this.options.lambda.getFunction(s)).Configuration?.Environment?.Variables??{}};r[s]=i.MAINTENANCE_MODE??null,await this.options.lambda.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:{...i,MAINTENANCE_MODE:"1"}}}),await this.options.republish?.(s)}return{kind:"lambda_maintenance_mode",previous:r}}async resumeProject(e){let t=e.previous??{};for(let r of Object.keys(t)){let n={...(await this.options.lambda.getFunction(r)).Configuration?.Environment?.Variables??{}};n.MAINTENANCE_MODE=typeof t[r]==="string"?t[r]:"0",await this.options.lambda.updateFunctionConfiguration({FunctionName:r,Environment:{Variables:n}}),await this.options.republish?.(r)}}}class li{options;constructor(e){this.options=e}async unitsFor(e){let t=await this.options.units(e);if(t.length===0)throw Error("No systemd units were resolved for this scope.");for(let r of t)if(!/^[A-Za-z0-9@._-]+$/.test(r))throw Error(`Refusing to act on an unsafe unit name: ${r}`);return t}async stopUnits(e,t){let r=await this.unitsFor(e),s=[];for(let n of r){let i=await this.options.exec(this.options.host,`systemctl list-units --plain --no-legend --state=active --type=service '${n}@*.service' '${n}.service' 2>/dev/null | awk '{print $1}'`);fe(`listing units for ${n}`,i);let E=i.stdout.split(`
|
|
1551
|
+
`).map((a)=>a.trim()).filter((a)=>/^[A-Za-z0-9@._-]+\.service$/.test(a));for(let a of E){let d=await this.options.exec(this.options.host,`systemctl stop '${a}'`);fe(`stopping ${a}`,d),s.push(a)}}return{kind:"systemd_units",via:t,stopped:s}}async startUnits(e){let t=Array.isArray(e.stopped)?e.stopped:[];for(let r of t){if(!/^[A-Za-z0-9@._-]+$/.test(r))continue;let s=await this.options.exec(this.options.host,`systemctl start '${r}'`);fe(`starting ${r}`,s)}}async suspendFunctions(e){return this.stopUnits(e,"suspend_functions")}async resumeFunctions(e){await this.startUnits(e)}async serveStatic(e){return this.stopUnits(e,"serve_static")}async restoreDynamic(e){await this.startUnits(e)}async suspendProject(e){return this.stopUnits(e,"suspend_project")}async resumeProject(e){await this.startUnits(e)}async throttleRequests(e){let t=this.options.renderDdos,r=this.options.ddos;if(!t||!r)throw Error("Request throttling needs a DDoS config and renderer on this transport.");let s={rateLimitFactor:e.factor},n={...r.thresholds,newConnectionsPerSecond:zt(r.thresholds?.newConnectionsPerSecond??50,s),concurrentPerSource:zt(r.thresholds?.concurrentPerSource??100,s)},i=t({...r,thresholds:n}),E=await this.options.exec(this.options.host,`bash -s <<'TS_CLOUD_THROTTLE_EOF'
|
|
1554
1552
|
${i}
|
|
1555
|
-
TS_CLOUD_THROTTLE_EOF`);
|
|
1556
|
-
|
|
1557
|
-
[output truncated]`;let d=this.idFn(),c=this.now();return this.controlPlane.database.run("INSERT INTO operation_logs (id, operation_id, stream, step, message, redacted, truncated, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[d,e,r.stream??"stdout",r.step??null,n,i?1:0,a?1:0,c]),Tn(this.controlPlane.database.query("SELECT * FROM operation_logs WHERE id=?").get(d))}logs(e,t={}){let r=Math.min(1000,Math.max(1,t.limit??200));return this.controlPlane.database.query("SELECT * FROM operation_logs WHERE operation_id=? AND sequence>? ORDER BY sequence ASC LIMIT ?").all(e,t.after??0,r).map(Tn)}requestCancellation(e,t){let r=this.controlPlane.getOperation(e);if(!r||ho.includes(r.state))throw Error("Only queued or running operations can be cancelled");let n=this.controlPlane.requestCancellation(e);if(this.controlPlane.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:t,correlationId:r.correlationId,type:"operation.cancellation_requested",level:"warning",payload:{state:r.state}}),this.appendLog(e,r.state==="queued"?"Cancellation accepted before execution.":"Cancellation requested; waiting for the current provider step.",{stream:"system"}),n.state==="queued")return this.finish(e,"cancelled",{cancelledBeforeStart:!0});return n}retry(e,t,r={}){let n=this.controlPlane.getOperation(e),i=this.getJob(e);if(!n||!i||!["failed","cancelled","timed_out"].includes(n.state))throw Error("Only failed, cancelled, or timed-out queue jobs can be retried");if(n.attempt>=i.maxAttempts)throw Error(`Operation reached its ${i.maxAttempts}-attempt limit`);if(!i.retryClasses.includes(t))throw Error(`Retry class ${t} is not allowed for this operation`);let o=this.controlPlane.transitionOperation(e,{to:"queued",expectedVersion:n.version,error:`Retry requested after ${t}`}),s=new Date(this.nowFn().getTime()+Math.max(0,r.delayMs??0)).toISOString();this.controlPlane.database.run("UPDATE operations SET cancel_requested_at=NULL, finished_at=NULL WHERE id=?",[e]),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=NULL, updated_at=? WHERE operation_id=?",[s,this.now(),e]),this.controlPlane.appendEvent({projectId:n.projectId,operationId:e,resourceId:n.resourceId,actorId:r.actorId,correlationId:n.correlationId,type:"operation.retry_requested",payload:{errorClass:t,availableAt:s,nextAttempt:n.attempt+1}}),this.appendLog(e,`Retry queued for error class ${t}.`,{stream:"system"});let a=this.controlPlane.getOperation(o.id);return this.notifyAvailable(),a}release(e){this.controlPlane.database.run("DELETE FROM operation_locks WHERE operation_id=?",[e])}finish(e,t,r={},n){let i=this.controlPlane.getOperation(e);if(!i)throw Error(`Operation ${e} was not found`);let o=this.controlPlane.transitionOperation(e,{to:t,expectedVersion:i.version,output:r,error:n});return this.release(e),o}complete(e,t={}){let r=this.controlPlane.getOperation(e);if(!r||r.state!=="running"||r.leaseOwner!==this.workerId)throw Error("Only the lease owner can complete a running operation");return this.appendLog(e,"Operation completed successfully.",{stream:"system"}),this.finish(e,"succeeded",t)}fail(e,t,r={}){let n=this.controlPlane.getOperation(e);if(!n||n.state!=="running"||n.leaseOwner!==this.workerId)throw Error("Only the lease owner can fail a running operation");return this.appendLog(e,t,{stream:"stderr"}),this.finish(e,"failed",r,t)}async runOne(e){let t=this.claimNext(Object.keys(e));if(!t)return{handled:!1};let{operation:r,job:n}=t,i=e[r.kind];if(!i)return{handled:!1};let o=new AbortController,s=!1,a=setTimeout(()=>{s=!0,o.abort(new tt(n.timeoutSeconds))},n.timeoutSeconds*1000),d=setInterval(()=>{try{this.heartbeat(r.id)}catch{}},Math.max(250,Math.floor(this.leaseMs/3))),c=setInterval(()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)o.abort(new Re)},100),p={operation:r,signal:o.signal,log:(l,u)=>this.appendLog(r.id,l,u),checkpoint:(l,u)=>{this.heartbeat(r.id,l),this.appendLog(r.id,u??l,{stream:"step",step:l})},heartbeat:()=>this.heartbeat(r.id),cancellationRequested:()=>!!this.controlPlane.getOperation(r.id)?.cancelRequestedAt,throwIfCancellationRequested:()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)throw new Re}};try{let l=await Promise.race([i(p),new Promise((E,T)=>o.signal.addEventListener("abort",()=>T(o.signal.reason),{once:!0}))]);if(this.controlPlane.getOperation(r.id).cancelRequestedAt){let E=n.cancellationMode==="provider_non_cancellable";return this.appendLog(r.id,E?"Provider step completed after cancellation was requested; reconciliation is required.":"Operation cancelled cooperatively.",{stream:"system"}),{handled:!0,operation:this.finish(r.id,"cancelled",{providerCompleted:E,reconciliationRequired:E}),terminalState:"cancelled"}}return{handled:!0,operation:this.complete(r.id,l??{}),terminalState:"succeeded"}}catch(l){if(s||l instanceof tt)return this.appendLog(r.id,`Timed out after ${n.timeoutSeconds}s.`,{stream:"system"}),{handled:!0,operation:this.finish(r.id,"timed_out",{reconciliationRequired:n.cancellationMode==="provider_non_cancellable"},l instanceof Error?l.message:String(l)),terminalState:"timed_out"};if(l instanceof Re||this.controlPlane.getOperation(r.id)?.cancelRequestedAt)return{handled:!0,operation:this.finish(r.id,"cancelled",{cooperativelyCancelled:!0}),terminalState:"cancelled"};if(l instanceof J&&n.retryClasses.includes(l.errorClass)&&r.attempt<n.maxAttempts){let E=this.controlPlane.getOperation(r.id);this.controlPlane.transitionOperation(r.id,{to:"queued",expectedVersion:E.version,error:l.message});let T=Math.min(60000,1000*2**Math.max(0,r.attempt-1)),_=new Date(this.nowFn().getTime()+T).toISOString();return this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=?, updated_at=? WHERE operation_id=?",[_,`retry_backoff:${l.errorClass}`,this.now(),r.id]),this.release(r.id),this.appendLog(r.id,`Retryable ${l.errorClass} failure; next attempt is delayed.`,{stream:"system"}),{handled:!0,operation:this.controlPlane.getOperation(r.id),requeued:!0}}let u=l instanceof Error?l.message:String(l);return this.appendLog(r.id,u,{stream:"stderr"}),{handled:!0,operation:this.finish(r.id,"failed",{},u),terminalState:"failed"}}finally{clearTimeout(a),clearInterval(d),clearInterval(c)}}recoverExpired(){let e=this.controlPlane.database.query("SELECT o.id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND (o.lease_expires_at IS NULL OR o.lease_expires_at<=?)").all(this.now()),t={requeued:0,failed:0,cancelled:0};for(let r of e){let n=this.controlPlane.getOperation(String(r.id)),i=this.getJob(n.id);if(this.release(n.id),n.cancelRequestedAt){this.finish(n.id,"cancelled",{recoveredAfterWorkerLoss:!0}),t.cancelled++;continue}if(i.resumePolicy==="requeue"&&n.attempt<i.maxAttempts)this.controlPlane.transitionOperation(n.id,{to:"queued",expectedVersion:n.version,error:"Worker lease expired; safely requeued from the last checkpoint."}),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason='worker_restart', updated_at=? WHERE operation_id=?",[this.now(),this.now(),n.id]),this.appendLog(n.id,"Worker lease expired; operation requeued from its persisted checkpoint.",{stream:"system"}),t.requeued++;else this.finish(n.id,"failed",{recoverable:!0,lastCheckpoint:i.currentStep??null},"Worker lease expired; retry explicitly after reconciling provider state."),t.failed++}return t}clearCompleted(e={}){let t=this.now(),r=[t],n=e.projectId?"AND o.project_id=?":"";if(e.projectId)r.push(e.projectId);let i=e.before?"AND o.finished_at<=?":"";if(e.before)r.push(new Date(e.before).toISOString());let o=this.controlPlane.database.query(`SELECT o.id, o.project_id, o.correlation_id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state IN ('succeeded','failed','cancelled','timed_out') AND j.retention_until<=? ${n} ${i}`).all(...r);for(let s of o)this.controlPlane.appendEvent({projectId:Z(s.project_id),actorId:e.actorId,correlationId:String(s.correlation_id),type:"queue.history.cleared",level:"warning",payload:{operationId:String(s.id),retentionCutoff:t}}),this.controlPlane.database.run("DELETE FROM operations WHERE id=?",[String(s.id)]);return o.length}}function gn(e,t,r){if(!Number.isFinite(e))return t;return Math.min(r,Math.max(1,Math.floor(e)))}class yo{queue;handlers;parallelism;pollIntervalMs;onResult;onError;waits=new Map;nextWaitId=0;lanes=[];running=!1;unsubscribeAvailability;constructor(e,t,r={}){this.queue=e;this.handlers=t;this.parallelism=gn(r.parallelism,4,100),this.pollIntervalMs=gn(r.pollIntervalMs,5000,60000),this.onResult=r.onResult,this.onError=r.onError}get active(){return this.running}start(){if(this.running)return this;return this.running=!0,this.unsubscribeAvailability=this.queue.onAvailable(()=>this.wake()),this.lanes=Array.from({length:this.parallelism},(e,t)=>this.runLane(t)),this}stop(){this.running=!1,this.unsubscribeAvailability?.(),this.unsubscribeAvailability=void 0,this.wake()}wake(){for(let{resolve:e,timer:t}of this.waits.values()){if(t)clearTimeout(t);e()}this.waits.clear()}async settled(){await Promise.allSettled(this.lanes)}async drain(){let e=[];while(!0){let t=await Promise.all(Array.from({length:this.parallelism},()=>this.queue.runOne(this.handlers)));if(e.push(...t.filter((r)=>r.handled)),!t.some((r)=>r.handled))return e}}wait(e){return new Promise((t)=>{let r=++this.nextWaitId,n=e?setTimeout(()=>{this.waits.delete(r),t()},this.pollIntervalMs):void 0;n?.unref?.(),this.waits.set(r,{resolve:t,timer:n})})}async runLane(e){while(this.running){try{let t=await this.queue.runOne(this.handlers);if(!this.running)break;if(t.handled){this.onResult?.(t),this.wake();continue}}catch(t){this.onError?.(t)}await this.wait(e===0)}}}import{createHash as Lo}from"node:crypto";var fn=/^[a-z0-9](?:[a-z0-9_.-]{0,62})$/,vo=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Io=/(?:secret|token|password|passwd|private.?key|api.?key|credential)/i,So=new Set(["image","build","command","entrypoint","environment","ports","volumes","networks","depends_on","healthcheck","restart","deploy","labels"]),_n=new Map([["privileged","Privileged containers are blocked."],["network_mode","Host/custom network modes are blocked."],["pid","Host PID namespaces are blocked."],["ipc","Host IPC namespaces are blocked."],["devices","Device access is blocked."],["cap_add","Additional Linux capabilities require an external policy exception."],["security_opt","Custom security options require an external policy exception."]]);function C(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Gt(e){return Array.isArray(e)?e:e==null?[]:[e]}function bo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,63)||"compose-app"}function Ce(e){if(Array.isArray(e))return e.map(String);if(typeof e==="string"&&e.trim())return["sh","-c",e];return}function Yt(e,t){let r=String(e??""),n=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(r);if(!n)return t;let i=Number(n[1]);return Math.max(0,Math.round(i*(n[2]==="ms"?0.001:n[2]==="m"?60:n[2]==="h"?3600:1)))}function hn(e){let t=/^(\d+(?:\.\d+)?)\s*(b|k|kb|kib|m|mb|mib|g|gb|gib)?$/i.exec(String(e??""));if(!t)return;let r=Number(t[1]),n=String(t[2]??"b").toLowerCase(),i=r*(n.startsWith("g")?1073741824:n.startsWith("m")?1048576:n.startsWith("k")?1024:1);return Math.max(1,Math.round(i/1024/1024))}function Ro(e){if(e==null)return"";return/^\$\{([A-Za-z_][A-Za-z0-9_]*)(?::[-?][^}]*)?\}$/.exec(String(e))?.[1]}function yn(e,t,r){let n={},i=Array.isArray(e)?e.map((o)=>{let[s,...a]=String(o).split("=");return[s,a.length?a.join("="):null]}):Object.entries(C(e));for(let[o,s]of i){let a=String(o);if(!vo.test(a)){r.push({severity:"error",path:`${t}.${a}`,code:"environment.name",message:"Environment variable names must use portable shell identifiers."});continue}let d=Ro(s);if(d!==void 0){n[a]={secretRef:d||a};continue}if(Io.test(a)){r.push({severity:"error",path:`${t}.${a}`,code:"secret.literal",message:"Literal secret-like environment values are not stored.",alternative:`Use \${${a}} and supply ${a} through the secret store.`}),n[a]={secretRef:a};continue}n[a]=String(s??"")}return n}function Co(e,t,r){let n=[];for(let[i,o]of Gt(e).entries()){let s,a,d="tcp";if(typeof o==="number")s=o;else if(typeof o==="string"){let[c,p]=o.split("/");d=p==="udp"?"udp":"tcp";let l=c.split(":");s=Number(l.at(-1)),a=l.length>1?Number(l.at(-2)):void 0}else{let c=C(o);s=Number(c.target),a=c.published==null?void 0:Number(c.published),d=c.protocol==="udp"?"udp":"tcp"}if(!Number.isInteger(s)||s<1||s>65535||a!=null&&(!Number.isInteger(a)||a<1||a>65535))r.push({severity:"error",path:`${t}[${i}]`,code:"port.invalid",message:"Ports must be integers from 1 through 65535."});else n.push({target:s,...a?{published:a}:{},protocol:d})}return n}function Ao(e,t,r,n){let i=[];for(let[o,s]of Gt(e).entries()){let a="",d="",c=!1,p="volume";if(typeof s==="string"){let l=s.split(":");a=l[0]??"",d=l[1]??"",c=l.slice(2).includes("ro"),p=a.startsWith("/")||a.startsWith(".")?"bind":"volume"}else{let l=C(s);a=String(l.source??""),d=String(l.target??""),c=l.read_only===!0,p=String(l.type??"volume")}if(p!=="volume"||a.startsWith("/")||a.startsWith(".")){n.push({severity:"error",path:`${r}[${o}]`,code:"volume.host_mount",message:"Host and bind mounts are blocked; use a named volume.",alternative:"Declare the volume at the top level and mount it by name."});continue}if(!fn.test(a)||!d.startsWith("/")){n.push({severity:"error",path:`${r}[${o}]`,code:"volume.invalid",message:"A named source and absolute container target are required."});continue}if(!t.has(a))n.push({severity:"warning",path:`${r}[${o}]`,code:"volume.implicit",message:`Named volume ${a} is implicit and will be declared on export.`});t.add(a),i.push({source:a,target:d,readOnly:c})}return i}function Oo(e){return Array.isArray(e)?e.map((t)=>({service:String(t),condition:"service_started"})):Object.entries(C(e)).map(([t,r])=>({service:t,condition:["service_started","service_healthy","service_completed_successfully"].includes(String(C(r).condition))?String(C(r).condition):"service_started"}))}function Nn(e){let t=C(e);if(!Object.keys(t).length||t.disable===!0)return;let r=Ce(t.test);return r?{test:r,intervalSeconds:Yt(t.interval,30),timeoutSeconds:Yt(t.timeout,5),retries:Math.max(1,Number(t.retries)||3),...t.start_period?{startPeriodSeconds:Yt(t.start_period,0)}:{}}:void 0}function Uo(e,t,r){if(!e)return;let n=typeof e==="string"?{context:e}:C(e),i=String(n.context??"."),o=String(n.dockerfile??"Dockerfile");if(i.startsWith("/")||i.split("/").includes("..")||o.startsWith("/")||o.split("/").includes(".."))r.push({severity:"error",path:t,code:"build.traversal",message:"Build context and Dockerfile must stay inside the repository."});return{context:i,dockerfile:o,...n.target?{target:String(n.target)}:{},args:yn(n.args,`${t}.args`,r)}}function Do(e,t,r){let n=Array.isArray(e)?Object.fromEntries(e.map((o)=>String(o).split("=",2))):C(e),i=String(n["ts-cloud.domains"]??n["ts-cloud.domain"]??"").split(",").map((o)=>o.trim()).filter(Boolean);for(let o of i)if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(o))r.push({severity:"error",path:t,code:"domain.invalid",message:`Invalid service domain ${o}.`});return i.filter((o)=>/\./.test(o))}function wo(e,t){let r=[],n=new Set,i=new Set,o=(s)=>{if(i.has(s))return;if(n.has(s)){t.push({severity:"error",path:`services.${s}.depends_on`,code:"dependency.cycle",message:"Service dependencies contain a cycle."});return}n.add(s);for(let a of e[s]?.dependsOn??[])if(!e[a.service])t.push({severity:"error",path:`services.${s}.depends_on.${a.service}`,code:"dependency.missing",message:`Dependency ${a.service} does not exist.`});else o(a.service);n.delete(s),i.add(s),r.push(s)};return Object.keys(e).sort().forEach(o),r}function ie(e,t){if(Buffer.byteLength(e)>524288)throw Error("Compose source exceeds the 512 KiB limit");let r;try{r=C(Bun.YAML.parse(e))}catch(u){throw Error(`Compose YAML could not be parsed: ${u instanceof Error?u.message:String(u)}`)}let n=[],i=C(r.services),o=Object.keys(i);if(!o.length)n.push({severity:"error",path:"services",code:"services.required",message:"At least one service is required."});if(o.length>64)n.push({severity:"error",path:"services",code:"services.limit",message:"A Compose application may contain at most 64 services."});let s=new Set(Object.keys(C(r.volumes))),a=new Set(Object.keys(C(r.networks))),d={};for(let u of o.sort()){let m=`services.${u}`,E=C(i[u]);if(!fn.test(u)){n.push({severity:"error",path:m,code:"service.name",message:"Service names must be portable lowercase identifiers."});continue}for(let[R,On]of _n)if(E[R]!=null&&E[R]!==!1&&(!Array.isArray(E[R])||E[R].length))n.push({severity:"error",path:`${m}.${R}`,code:`unsafe.${R}`,message:On});for(let R of Object.keys(E))if(!So.has(R)&&!_n.has(R))n.push({severity:"warning",path:`${m}.${R}`,code:"field.unsupported",message:`Compose field ${R} is not in the supported subset and will not be deployed.`});let T=E.image?String(E.image):void 0,_=Uo(E.build,`${m}.build`,n);if(!T&&!_)n.push({severity:"error",path:m,code:"service.source",message:"Each service requires image or build."});if(T&&!T.includes("@sha256:")&&(!T.includes(":")||T.endsWith(":latest")))n.push({severity:"warning",path:`${m}.image`,code:"image.floating",message:`Image ${T} is not pinned to a digest or explicit tag.`});let h=Gt(E.networks).map((R)=>typeof R==="string"?R:String(C(R).name??"")).filter(Boolean);h.forEach((R)=>a.add(R));let N=C(E.deploy),f=C(N.resources),b=C(f.limits),O=["no","always","on-failure","unless-stopped"].includes(String(E.restart))?String(E.restart):"unless-stopped";d[u]={name:u,...T?{image:T}:{},..._?{build:_}:{},...Ce(E.command)?{command:Ce(E.command)}:{},...Ce(E.entrypoint)?{entrypoint:Ce(E.entrypoint)}:{},environment:yn(E.environment,`${m}.environment`,n),ports:Co(E.ports,`${m}.ports`,n),volumes:Ao(E.volumes,s,`${m}.volumes`,n),networks:h,dependsOn:Oo(E.depends_on),...Nn(E.healthcheck)?{healthCheck:Nn(E.healthcheck)}:{},restart:O,...Number(b.cpus)>0?{cpu:Number(b.cpus)}:{},...hn(b.memory)?{memoryMb:hn(b.memory)}:{},replicas:Math.max(1,Math.min(100,Number(N.replicas)||1)),domains:Do(E.labels,`${m}.labels`,n)}}let c=wo(d,n),p={apiVersion:"ts-cloud.dev/v1",kind:"ComposeApplication",metadata:{name:t.name.trim(),slug:bo(t.slug??t.name),projectId:t.projectId,environmentId:t.environmentId},spec:{services:d,networks:[...a].sort(),volumes:[...s].sort(),dependencyOrder:c}},l=Wt(p);return{valid:!n.some((u)=>u.severity==="error"),manifest:p,diagnostics:n,redactedSource:l,sourceHash:Lo("sha256").update(e).digest("hex")}}function Wt(e){let t=Object.fromEntries(Object.entries(e.spec.services).map(([r,n])=>[r,{...n.image?{image:n.image}:{},...n.build?{build:{context:n.build.context,dockerfile:n.build.dockerfile,...n.build.target?{target:n.build.target}:{},...Object.keys(n.build.args).length?{args:Object.fromEntries(Object.entries(n.build.args).map(([i,o])=>[i,typeof o==="string"?o:`\${${o.secretRef}:?required secret ${o.secretRef}}`]))}:{}}}:{},...n.command?{command:n.command}:{},...n.entrypoint?{entrypoint:n.entrypoint}:{},...Object.keys(n.environment).length?{environment:Object.fromEntries(Object.entries(n.environment).map(([i,o])=>[i,typeof o==="string"?o:`\${${o.secretRef}:?required secret ${o.secretRef}}`]))}:{},...n.ports.length?{ports:n.ports.map((i)=>`${i.published?`${i.published}:`:""}${i.target}${i.protocol==="udp"?"/udp":""}`)}:{},...n.volumes.length?{volumes:n.volumes.map((i)=>`${i.source}:${i.target}${i.readOnly?":ro":""}`)}:{},...n.networks.length?{networks:n.networks}:{},...n.dependsOn.length?{depends_on:Object.fromEntries(n.dependsOn.map((i)=>[i.service,{condition:i.condition}]))}:{},...n.healthCheck?{healthcheck:{test:n.healthCheck.test,interval:`${n.healthCheck.intervalSeconds}s`,timeout:`${n.healthCheck.timeoutSeconds}s`,retries:n.healthCheck.retries,...n.healthCheck.startPeriodSeconds!=null?{start_period:`${n.healthCheck.startPeriodSeconds}s`}:{}}}:{},restart:n.restart,...n.cpu||n.memoryMb||n.replicas!==1?{deploy:{replicas:n.replicas,resources:{limits:{...n.cpu?{cpus:String(n.cpu)}:{},...n.memoryMb?{memory:`${n.memoryMb}M`}:{}}}}}:{},...n.domains.length?{labels:{"ts-cloud.domains":n.domains.join(",")}}:{}}]));return Bun.YAML.stringify({services:t,...e.spec.networks.length?{networks:Object.fromEntries(e.spec.networks.map((r)=>[r,{}]))}:{},...e.spec.volumes.length?{volumes:Object.fromEntries(e.spec.volumes.map((r)=>[r,{}]))}:{}})}function Jt(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 a of[...new Set([...Object.keys(o),...Object.keys(s)])].sort())n(i?`${i}.${a}`:a,o[a],s[a]);return}r.push({path:i,...o!==void 0?{before:o}:{},...s!==void 0?{after:s}:{}})};return n("",e,t),r}import{createHash as Ln}from"node:crypto";var ko="2026-07-21T00:00:00.000Z",vn=[{id:"bun-postgres-redis",name:"Bun + Postgres + Redis",description:"Web and worker services with durable Postgres and Redis dependencies.",category:"application",version:"1.0.0",sourceVersion:"oven/bun:1.2.21,postgres:17.5,redis:8.0.3",architecture:"web → Postgres + Redis; worker → Postgres + Redis",minimumResources:{cpu:2,memoryMb:3072},exposedServices:["web"],maintenanceNotes:"Back up the Postgres volume before major upgrades.",inputs:[{name:"domain",label:"Web domain",required:!0,secret:!1}],source:`services:
|
|
1553
|
+
TS_CLOUD_THROTTLE_EOF`);return fe("applying the throttled firewall ruleset",E),{kind:"nftables_throttle",factor:e.factor,previousThresholds:r.thresholds??{}}}async restoreRequests(e){let t=this.options.renderDdos,r=this.options.ddos;if(!t||!r)return;let s=e.previousThresholds??{},n=t({...r,thresholds:s}),i=await this.options.exec(this.options.host,`bash -s <<'TS_CLOUD_THROTTLE_EOF'
|
|
1554
|
+
${n}
|
|
1555
|
+
TS_CLOUD_THROTTLE_EOF`);fe("restoring the firewall ruleset",i)}}function Cd(e){let t=async(s,n)=>{let i={},E,a=0;for(let[d,T]of e.entries()){let N=T[s];if(!N)continue;a++;try{i[String(d)]=await N.call(T,n)}catch(o){i[String(d)]={error:o instanceof Error?o.message:String(o)},E??=o}}if(a===0)throw Error(`No transport implements ${s}.`);if(E)throw E;return{kind:"composite",legs:i}},r=async(s,n)=>{let i=n.legs??{},E;for(let[a,d]of e.entries()){let T=d[s];if(!T)continue;let N=i[String(a)];if(!N||typeof N!=="object"||Array.isArray(N)||"error"in N)continue;try{await T.call(d,N)}catch(o){E??=o}}if(E)throw E};return{throttleRequests:(s)=>t("throttleRequests",s),restoreRequests:(s)=>r("restoreRequests",s),suspendFunctions:(s)=>t("suspendFunctions",s),resumeFunctions:(s)=>r("resumeFunctions",s),serveStatic:(s)=>t("serveStatic",s),restoreDynamic:(s)=>r("restoreDynamic",s),suspendProject:(s)=>t("suspendProject",s),resumeProject:(s)=>r("resumeProject",s)}}import{createHash as dE}from"node:crypto";class Se extends Error{constructor(){super("Operation cancellation was requested")}}class et extends Error{timeoutSeconds;constructor(e){super(`Operation exceeded its ${e}s timeout`);this.timeoutSeconds=e}}class J extends Error{errorClass;constructor(e,t){super(e);this.errorClass=t}}var tt={project:2,environment:1,provider:2,builds:1},Li=30,os=16384,mi=["succeeded","failed","cancelled","timed_out"],Gt=new Map,cs=new WeakMap;function Ns(e){if(e.path===":memory:"){let s=cs.get(e);if(s)return s;let n=new Set;return cs.set(e,n),n}let t=Gt.get(e.path);if(t)return t;let r=new Set;return Gt.set(e.path,r),r}function Z(e){return typeof e==="string"&&e?e:void 0}function ui(e){try{let t=JSON.parse(String(e));return Array.isArray(t)?t.map(String):[]}catch{return[]}}function Ci(e){return{operationId:String(e.operation_id),lockKey:Z(e.lock_key),providerKey:Z(e.provider_key),buildSlot:Number(e.build_slot)===1,maxAttempts:Number(e.max_attempts),availableAt:String(e.available_at),timeoutSeconds:Number(e.timeout_seconds),heartbeatAt:Z(e.heartbeat_at),currentStep:Z(e.current_step),blockedReason:Z(e.blocked_reason),retryClasses:ui(e.retry_classes),resumePolicy:String(e.resume_policy),cancellationMode:String(e.cancellation_mode),retentionUntil:String(e.retention_until),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function _s(e){return{sequence:Number(e.sequence),id:String(e.id),operationId:String(e.operation_id),stream:String(e.stream),step:Z(e.step),message:String(e.message),redacted:Number(e.redacted)===1,truncated:Number(e.truncated)===1,createdAt:String(e.created_at)}}function H(e,t,r){return Number.isFinite(e)?Math.min(r,Math.max(1,Math.floor(e))):t}class ${controlPlane;nowFn;idFn;workerId;leaseMs;limits;constructor(e,t={}){this.controlPlane=e;this.workerId=t.workerId??`worker:${process.pid}:${crypto.randomUUID()}`,this.leaseMs=H(t.leaseMs,60000,3600000),this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID());let r=e.getSetting("queue.concurrency");this.limits={project:H(t.limits?.project??r?.project,tt.project,100),environment:H(t.limits?.environment??r?.environment,tt.environment,100),provider:H(t.limits?.provider??r?.provider,tt.provider,100),builds:H(t.limits?.builds??r?.builds,tt.builds,100)}}now(){return this.nowFn().toISOString()}leaseExpiry(){return new Date(this.nowFn().getTime()+this.leaseMs).toISOString()}enqueue(e){let t=this.controlPlane.createOperation(e);if(this.getJob(t.id))return this.view(t.id);let s=this.now(),n=H(e.maxAttempts,1,20),i=H(e.timeoutSeconds,1800,86400),E=H(e.retentionDays,Li,3650),a=e.availableAt?new Date(e.availableAt).toISOString():s,d=new Date(this.nowFn().getTime()+E*24*60*60*1000).toISOString();this.controlPlane.database.run(`INSERT OR IGNORE INTO operation_jobs (operation_id, lock_key, provider_key, build_slot, max_attempts, available_at, timeout_seconds, retry_classes, resume_policy, cancellation_mode, retention_until, created_at, updated_at)
|
|
1556
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.id,e.lockKey??e.resourceId??null,e.providerKey??null,e.buildSlot?1:0,n,a,i,JSON.stringify([...new Set(e.retryClasses??[])]),e.resumePolicy??"fail",e.cancellationMode??"cooperative",d,s,s]),this.appendLog(t.id,"Queued for durable execution.",{stream:"system"});let T=this.view(t.id);return this.notifyAvailable(),T}onAvailable(e){let t=Ns(this.controlPlane);return t.add(e),()=>{if(t.delete(e),t.size===0&&this.controlPlane.path!==":memory:")Gt.delete(this.controlPlane.path)}}notifyAvailable(){for(let e of Ns(this.controlPlane))e()}getJob(e){let t=this.controlPlane.database.query("SELECT * FROM operation_jobs WHERE operation_id=?").get(e);return t?Ci(t):void 0}view(e){let t=this.controlPlane.getOperation(e),r=this.getJob(e);if(!t||!r)return;let s;if(t.state==="queued")s={ahead:Number(this.controlPlane.database.query("SELECT COUNT(*) AS count FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='queued' AND j.available_at<=? AND (o.priority>? OR (o.priority=? AND o.created_at<?))").get(this.now(),t.priority,t.priority,t.createdAt)?.count??0),precision:"bounded"};return{operation:t,job:r,approximatePosition:s}}list(e={}){return this.controlPlane.listOperations({projectId:e.projectId,state:e.state,limit:e.limit??200}).map((t)=>this.view(t.id)).filter((t)=>!!t)}configureConcurrency(e,t={}){let r={project:H(e.project,this.limits.project,100),environment:H(e.environment,this.limits.environment,100),provider:H(e.provider,this.limits.provider,100),builds:H(e.builds,this.limits.builds,100)};return Object.assign(this.limits,r),this.controlPlane.setSetting("queue.concurrency",r),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.actorId,type:"queue.concurrency.updated",level:"warning",payload:r}),r}runningCount(e,t){return Number(this.controlPlane.database.query(e).get(...t)?.count??0)}blockReason(e,t){if(t.lockKey){if(this.controlPlane.database.query("SELECT * FROM operation_locks WHERE lock_key=? AND operation_id!=? AND lease_expires_at>?").get(t.lockKey,e.id,this.now()))return`resource_lock:${t.lockKey}`}if(e.projectId&&this.runningCount("SELECT COUNT(*) AS count FROM operations WHERE state='running' AND project_id=?",[e.projectId])>=this.limits.project)return"project_concurrency";if(e.environmentId&&this.runningCount("SELECT COUNT(*) AS count FROM operations WHERE state='running' AND environment_id=?",[e.environmentId])>=this.limits.environment)return"environment_concurrency";if(t.providerKey&&this.runningCount("SELECT COUNT(*) AS count FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND j.provider_key=?",[t.providerKey])>=this.limits.provider)return"provider_concurrency";if(t.buildSlot&&this.runningCount("SELECT COUNT(*) AS count FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND j.build_slot=1",[])>=this.limits.builds)return"build_concurrency";return}claim(e){return this.controlPlane.transaction(()=>{let t=this.now();this.controlPlane.database.run("DELETE FROM operation_locks WHERE lease_expires_at<=?",[t]);let r=this.controlPlane.getOperation(e),s=r?this.getJob(r.id):void 0;if(!r||!s||r.state!=="queued"||s.availableAt>t)return;if(r.cancelRequestedAt){this.controlPlane.transitionOperation(r.id,{to:"cancelled",expectedVersion:r.version,output:{cancelledBeforeStart:!0}}),this.appendLog(r.id,"Cancelled before execution began.",{stream:"system"});return}let n=this.blockReason(r,s);if(n){this.controlPlane.database.run("UPDATE operation_jobs SET blocked_reason=?, updated_at=? WHERE operation_id=?",[n,t,r.id]);return}let i=this.controlPlane.claimOperation(r.id,this.workerId,this.leaseMs);if(!i)return;let E=i.leaseExpiresAt??this.leaseExpiry();if(s.lockKey)this.controlPlane.database.run("INSERT INTO operation_locks (lock_key, operation_id, lease_owner, lease_expires_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",[s.lockKey,r.id,this.workerId,E,t,t]);return this.controlPlane.database.run("UPDATE operation_jobs SET heartbeat_at=?, blocked_reason=NULL, updated_at=? WHERE operation_id=?",[t,t,r.id]),this.appendLog(r.id,`Claimed by ${this.workerId}; attempt ${i.attempt}.`,{stream:"system"}),this.view(r.id)})}claimNext(e){let t=this.now(),r=e?.length?`AND o.kind IN (${e.map(()=>"?").join(",")})`:"",s=this.controlPlane.database.query(`SELECT o.id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='queued' AND j.available_at<=? ${r} ORDER BY o.priority DESC, o.created_at ASC, o.rowid ASC LIMIT 100`).all(t,...e??[]);for(let n of s){let i=this.claim(String(n.id));if(i)return i}return}heartbeat(e,t){let r=this.controlPlane.getOperation(e);if(!r||r.state!=="running"||r.leaseOwner!==this.workerId)throw Error("Operation lease is not owned by this worker");let s=this.now(),n=this.leaseExpiry(),i=this.getJob(e);if(this.controlPlane.database.run("UPDATE operations SET lease_expires_at=?, updated_at=?, version=version+1 WHERE id=? AND state='running' AND lease_owner=? AND version=?",[n,s,e,this.workerId,r.version]).changes!==1)throw Error("Operation lease changed before heartbeat");if(this.controlPlane.database.run("UPDATE operation_jobs SET heartbeat_at=?, current_step=COALESCE(?, current_step), updated_at=? WHERE operation_id=?",[s,t??null,s,e]),i?.lockKey)this.controlPlane.database.run("UPDATE operation_locks SET lease_expires_at=?, updated_at=? WHERE lock_key=? AND operation_id=? AND lease_owner=?",[n,s,i.lockKey,e,this.workerId]);if(t&&t!==i?.currentStep)this.controlPlane.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:r.actorId,correlationId:r.correlationId,type:"operation.step",payload:{step:t}})}appendLog(e,t,r={}){if(!this.getJob(e))throw Error(`Queue job ${e} was not found`);let s=t,n=!1;for(let N of r.secrets??[])if(N&&s.includes(N))s=s.split(N).join("[REDACTED]"),n=!0;let i=h({message:s});if(i.message!==s)n=!0;s=i.message??"[output unavailable]";let E=Buffer.from(s),a=E.byteLength>os;if(a)s=`${E.subarray(0,os-32).toString("utf8")}
|
|
1557
|
+
[output truncated]`;let d=this.idFn(),T=this.now();return this.controlPlane.database.run("INSERT INTO operation_logs (id, operation_id, stream, step, message, redacted, truncated, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[d,e,r.stream??"stdout",r.step??null,s,n?1:0,a?1:0,T]),_s(this.controlPlane.database.query("SELECT * FROM operation_logs WHERE id=?").get(d))}logs(e,t={}){let r=Math.min(1000,Math.max(1,t.limit??200));return this.controlPlane.database.query("SELECT * FROM operation_logs WHERE operation_id=? AND sequence>? ORDER BY sequence ASC LIMIT ?").all(e,t.after??0,r).map(_s)}requestCancellation(e,t){let r=this.controlPlane.getOperation(e);if(!r||mi.includes(r.state))throw Error("Only queued or running operations can be cancelled");let s=this.controlPlane.requestCancellation(e);if(this.controlPlane.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:t,correlationId:r.correlationId,type:"operation.cancellation_requested",level:"warning",payload:{state:r.state}}),this.appendLog(e,r.state==="queued"?"Cancellation accepted before execution.":"Cancellation requested; waiting for the current provider step.",{stream:"system"}),s.state==="queued")return this.finish(e,"cancelled",{cancelledBeforeStart:!0});return s}retry(e,t,r={}){let s=this.controlPlane.getOperation(e),n=this.getJob(e);if(!s||!n||!["failed","cancelled","timed_out"].includes(s.state))throw Error("Only failed, cancelled, or timed-out queue jobs can be retried");if(s.attempt>=n.maxAttempts)throw Error(`Operation reached its ${n.maxAttempts}-attempt limit`);if(!n.retryClasses.includes(t))throw Error(`Retry class ${t} is not allowed for this operation`);let i=this.controlPlane.transitionOperation(e,{to:"queued",expectedVersion:s.version,error:`Retry requested after ${t}`}),E=new Date(this.nowFn().getTime()+Math.max(0,r.delayMs??0)).toISOString();this.controlPlane.database.run("UPDATE operations SET cancel_requested_at=NULL, finished_at=NULL WHERE id=?",[e]),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=NULL, updated_at=? WHERE operation_id=?",[E,this.now(),e]),this.controlPlane.appendEvent({projectId:s.projectId,operationId:e,resourceId:s.resourceId,actorId:r.actorId,correlationId:s.correlationId,type:"operation.retry_requested",payload:{errorClass:t,availableAt:E,nextAttempt:s.attempt+1}}),this.appendLog(e,`Retry queued for error class ${t}.`,{stream:"system"});let a=this.controlPlane.getOperation(i.id);return this.notifyAvailable(),a}release(e){this.controlPlane.database.run("DELETE FROM operation_locks WHERE operation_id=?",[e])}finish(e,t,r={},s){let n=this.controlPlane.getOperation(e);if(!n)throw Error(`Operation ${e} was not found`);let i=this.controlPlane.transitionOperation(e,{to:t,expectedVersion:n.version,output:r,error:s});return this.release(e),i}complete(e,t={}){let r=this.controlPlane.getOperation(e);if(!r||r.state!=="running"||r.leaseOwner!==this.workerId)throw Error("Only the lease owner can complete a running operation");return this.appendLog(e,"Operation completed successfully.",{stream:"system"}),this.finish(e,"succeeded",t)}fail(e,t,r={}){let s=this.controlPlane.getOperation(e);if(!s||s.state!=="running"||s.leaseOwner!==this.workerId)throw Error("Only the lease owner can fail a running operation");return this.appendLog(e,t,{stream:"stderr"}),this.finish(e,"failed",r,t)}async runOne(e){let t=this.claimNext(Object.keys(e));if(!t)return{handled:!1};let{operation:r,job:s}=t,n=e[r.kind];if(!n)return{handled:!1};let i=new AbortController,E=!1,a=setTimeout(()=>{E=!0,i.abort(new et(s.timeoutSeconds))},s.timeoutSeconds*1000),d=setInterval(()=>{try{this.heartbeat(r.id)}catch{}},Math.max(250,Math.floor(this.leaseMs/3))),T=setInterval(()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)i.abort(new Se)},100),N={operation:r,signal:i.signal,log:(o,c)=>this.appendLog(r.id,o,c),checkpoint:(o,c)=>{this.heartbeat(r.id,o),this.appendLog(r.id,c??o,{stream:"step",step:o})},heartbeat:()=>this.heartbeat(r.id),cancellationRequested:()=>!!this.controlPlane.getOperation(r.id)?.cancelRequestedAt,throwIfCancellationRequested:()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)throw new Se}};try{let o=await Promise.race([n(N),new Promise((_,L)=>i.signal.addEventListener("abort",()=>L(i.signal.reason),{once:!0}))]);if(this.controlPlane.getOperation(r.id).cancelRequestedAt){let _=s.cancellationMode==="provider_non_cancellable";return this.appendLog(r.id,_?"Provider step completed after cancellation was requested; reconciliation is required.":"Operation cancelled cooperatively.",{stream:"system"}),{handled:!0,operation:this.finish(r.id,"cancelled",{providerCompleted:_,reconciliationRequired:_}),terminalState:"cancelled"}}return{handled:!0,operation:this.complete(r.id,o??{}),terminalState:"succeeded"}}catch(o){if(E||o instanceof et)return this.appendLog(r.id,`Timed out after ${s.timeoutSeconds}s.`,{stream:"system"}),{handled:!0,operation:this.finish(r.id,"timed_out",{reconciliationRequired:s.cancellationMode==="provider_non_cancellable"},o instanceof Error?o.message:String(o)),terminalState:"timed_out"};if(o instanceof Se||this.controlPlane.getOperation(r.id)?.cancelRequestedAt)return{handled:!0,operation:this.finish(r.id,"cancelled",{cooperativelyCancelled:!0}),terminalState:"cancelled"};if(o instanceof J&&s.retryClasses.includes(o.errorClass)&&r.attempt<s.maxAttempts){let _=this.controlPlane.getOperation(r.id);this.controlPlane.transitionOperation(r.id,{to:"queued",expectedVersion:_.version,error:o.message});let L=Math.min(60000,1000*2**Math.max(0,r.attempt-1)),u=new Date(this.nowFn().getTime()+L).toISOString();return this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=?, updated_at=? WHERE operation_id=?",[u,`retry_backoff:${o.errorClass}`,this.now(),r.id]),this.release(r.id),this.appendLog(r.id,`Retryable ${o.errorClass} failure; next attempt is delayed.`,{stream:"system"}),{handled:!0,operation:this.controlPlane.getOperation(r.id),requeued:!0}}let c=o instanceof Error?o.message:String(o);return this.appendLog(r.id,c,{stream:"stderr"}),{handled:!0,operation:this.finish(r.id,"failed",{},c),terminalState:"failed"}}finally{clearTimeout(a),clearInterval(d),clearInterval(T)}}recoverExpired(){let e=this.controlPlane.database.query("SELECT o.id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND (o.lease_expires_at IS NULL OR o.lease_expires_at<=?)").all(this.now()),t={requeued:0,failed:0,cancelled:0};for(let r of e){let s=this.controlPlane.getOperation(String(r.id)),n=this.getJob(s.id);if(this.release(s.id),s.cancelRequestedAt){this.finish(s.id,"cancelled",{recoveredAfterWorkerLoss:!0}),t.cancelled++;continue}if(n.resumePolicy==="requeue"&&s.attempt<n.maxAttempts)this.controlPlane.transitionOperation(s.id,{to:"queued",expectedVersion:s.version,error:"Worker lease expired; safely requeued from the last checkpoint."}),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason='worker_restart', updated_at=? WHERE operation_id=?",[this.now(),this.now(),s.id]),this.appendLog(s.id,"Worker lease expired; operation requeued from its persisted checkpoint.",{stream:"system"}),t.requeued++;else this.finish(s.id,"failed",{recoverable:!0,lastCheckpoint:n.currentStep??null},"Worker lease expired; retry explicitly after reconciling provider state."),t.failed++}return t}clearCompleted(e={}){let t=this.now(),r=[t],s=e.projectId?"AND o.project_id=?":"";if(e.projectId)r.push(e.projectId);let n=e.before?"AND o.finished_at<=?":"";if(e.before)r.push(new Date(e.before).toISOString());let i=this.controlPlane.database.query(`SELECT o.id, o.project_id, o.correlation_id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state IN ('succeeded','failed','cancelled','timed_out') AND j.retention_until<=? ${s} ${n}`).all(...r);for(let E of i)this.controlPlane.appendEvent({projectId:Z(E.project_id),actorId:e.actorId,correlationId:String(E.correlation_id),type:"queue.history.cleared",level:"warning",payload:{operationId:String(E.id),retentionCutoff:t}}),this.controlPlane.database.run("DELETE FROM operations WHERE id=?",[String(E.id)]);return i.length}}function ls(e,t,r){if(!Number.isFinite(e))return t;return Math.min(r,Math.max(1,Math.floor(e)))}class gi{queue;handlers;parallelism;pollIntervalMs;onResult;onError;waits=new Map;nextWaitId=0;lanes=[];running=!1;unsubscribeAvailability;constructor(e,t,r={}){this.queue=e;this.handlers=t;this.parallelism=ls(r.parallelism,4,100),this.pollIntervalMs=ls(r.pollIntervalMs,5000,60000),this.onResult=r.onResult,this.onError=r.onError}get active(){return this.running}start(){if(this.running)return this;return this.running=!0,this.unsubscribeAvailability=this.queue.onAvailable(()=>this.wake()),this.lanes=Array.from({length:this.parallelism},(e,t)=>this.runLane(t)),this}stop(){this.running=!1,this.unsubscribeAvailability?.(),this.unsubscribeAvailability=void 0,this.wake()}wake(){for(let{resolve:e,timer:t}of this.waits.values()){if(t)clearTimeout(t);e()}this.waits.clear()}async settled(){await Promise.allSettled(this.lanes)}async drain(){let e=[];while(!0){let t=await Promise.all(Array.from({length:this.parallelism},()=>this.queue.runOne(this.handlers)));if(e.push(...t.filter((r)=>r.handled)),!t.some((r)=>r.handled))return e}}wait(e){return new Promise((t)=>{let r=++this.nextWaitId,s=e?setTimeout(()=>{this.waits.delete(r),t()},this.pollIntervalMs):void 0;s?.unref?.(),this.waits.set(r,{resolve:t,timer:s})})}async runLane(e){while(this.running){try{let t=await this.queue.runOne(this.handlers);if(!this.running)break;if(t.handled){this.onResult?.(t),this.wake();continue}}catch(t){this.onError?.(t)}await this.wait(e===0)}}}import{createHash as Ri}from"node:crypto";var Cs=/^[a-z0-9](?:[a-z0-9_.-]{0,62})$/,Oi=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Ai=/(?:secret|token|password|passwd|private.?key|api.?key|credential)/i,Ui=new Set(["image","build","command","entrypoint","environment","ports","volumes","networks","depends_on","healthcheck","restart","deploy","labels"]),Ls=new Map([["privileged","Privileged containers are blocked."],["network_mode","Host/custom network modes are blocked."],["pid","Host PID namespaces are blocked."],["ipc","Host IPC namespaces are blocked."],["devices","Device access is blocked."],["cap_add","Additional Linux capabilities require an external policy exception."],["security_opt","Custom security options require an external policy exception."]]);function I(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Vt(e){return Array.isArray(e)?e:e==null?[]:[e]}function hi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,63)||"compose-app"}function Xe(e){if(Array.isArray(e))return e.map(String);if(typeof e==="string"&&e.trim())return["sh","-c",e];return}function Qt(e,t){let r=String(e??""),s=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(r);if(!s)return t;let n=Number(s[1]);return Math.max(0,Math.round(n*(s[2]==="ms"?0.001:s[2]==="m"?60:s[2]==="h"?3600:1)))}function ms(e){let t=/^(\d+(?:\.\d+)?)\s*(b|k|kb|kib|m|mb|mib|g|gb|gib)?$/i.exec(String(e??""));if(!t)return;let r=Number(t[1]),s=String(t[2]??"b").toLowerCase(),n=r*(s.startsWith("g")?1073741824:s.startsWith("m")?1048576:s.startsWith("k")?1024:1);return Math.max(1,Math.round(n/1024/1024))}function fi(e){if(e==null)return"";return/^\$\{([A-Za-z_][A-Za-z0-9_]*)(?::[-?][^}]*)?\}$/.exec(String(e))?.[1]}function gs(e,t,r){let s={},n=Array.isArray(e)?e.map((i)=>{let[E,...a]=String(i).split("=");return[E,a.length?a.join("="):null]}):Object.entries(I(e));for(let[i,E]of n){let a=String(i);if(!Oi.test(a)){r.push({severity:"error",path:`${t}.${a}`,code:"environment.name",message:"Environment variable names must use portable shell identifiers."});continue}let d=fi(E);if(d!==void 0){s[a]={secretRef:d||a};continue}if(Ai.test(a)){r.push({severity:"error",path:`${t}.${a}`,code:"secret.literal",message:"Literal secret-like environment values are not stored.",alternative:`Use \${${a}} and supply ${a} through the secret store.`}),s[a]={secretRef:a};continue}s[a]=String(E??"")}return s}function Si(e,t,r){let s=[];for(let[n,i]of Vt(e).entries()){let E,a,d="tcp";if(typeof i==="number")E=i;else if(typeof i==="string"){let[T,N]=i.split("/");d=N==="udp"?"udp":"tcp";let o=T.split(":");E=Number(o.at(-1)),a=o.length>1?Number(o.at(-2)):void 0}else{let T=I(i);E=Number(T.target),a=T.published==null?void 0:Number(T.published),d=T.protocol==="udp"?"udp":"tcp"}if(!Number.isInteger(E)||E<1||E>65535||a!=null&&(!Number.isInteger(a)||a<1||a>65535))r.push({severity:"error",path:`${t}[${n}]`,code:"port.invalid",message:"Ports must be integers from 1 through 65535."});else s.push({target:E,...a?{published:a}:{},protocol:d})}return s}function Xi(e,t,r,s){let n=[];for(let[i,E]of Vt(e).entries()){let a="",d="",T=!1,N="volume";if(typeof E==="string"){let o=E.split(":");a=o[0]??"",d=o[1]??"",T=o.slice(2).includes("ro"),N=a.startsWith("/")||a.startsWith(".")?"bind":"volume"}else{let o=I(E);a=String(o.source??""),d=String(o.target??""),T=o.read_only===!0,N=String(o.type??"volume")}if(N!=="volume"||a.startsWith("/")||a.startsWith(".")){s.push({severity:"error",path:`${r}[${i}]`,code:"volume.host_mount",message:"Host and bind mounts are blocked; use a named volume.",alternative:"Declare the volume at the top level and mount it by name."});continue}if(!Cs.test(a)||!d.startsWith("/")){s.push({severity:"error",path:`${r}[${i}]`,code:"volume.invalid",message:"A named source and absolute container target are required."});continue}if(!t.has(a))s.push({severity:"warning",path:`${r}[${i}]`,code:"volume.implicit",message:`Named volume ${a} is implicit and will be declared on export.`});t.add(a),n.push({source:a,target:d,readOnly:T})}return n}function Ii(e){return Array.isArray(e)?e.map((t)=>({service:String(t),condition:"service_started"})):Object.entries(I(e)).map(([t,r])=>({service:t,condition:["service_started","service_healthy","service_completed_successfully"].includes(String(I(r).condition))?String(I(r).condition):"service_started"}))}function us(e){let t=I(e);if(!Object.keys(t).length||t.disable===!0)return;let r=Xe(t.test);return r?{test:r,intervalSeconds:Qt(t.interval,30),timeoutSeconds:Qt(t.timeout,5),retries:Math.max(1,Number(t.retries)||3),...t.start_period?{startPeriodSeconds:Qt(t.start_period,0)}:{}}:void 0}function vi(e,t,r){if(!e)return;let s=typeof e==="string"?{context:e}:I(e),n=String(s.context??"."),i=String(s.dockerfile??"Dockerfile");if(n.startsWith("/")||n.split("/").includes("..")||i.startsWith("/")||i.split("/").includes(".."))r.push({severity:"error",path:t,code:"build.traversal",message:"Build context and Dockerfile must stay inside the repository."});return{context:n,dockerfile:i,...s.target?{target:String(s.target)}:{},args:gs(s.args,`${t}.args`,r)}}function yi(e,t,r){let s=Array.isArray(e)?Object.fromEntries(e.map((i)=>String(i).split("=",2))):I(e),n=String(s["ts-cloud.domains"]??s["ts-cloud.domain"]??"").split(",").map((i)=>i.trim()).filter(Boolean);for(let i of n)if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(i))r.push({severity:"error",path:t,code:"domain.invalid",message:`Invalid service domain ${i}.`});return n.filter((i)=>/\./.test(i))}function pi(e,t){let r=[],s=new Set,n=new Set,i=(E)=>{if(n.has(E))return;if(s.has(E)){t.push({severity:"error",path:`services.${E}.depends_on`,code:"dependency.cycle",message:"Service dependencies contain a cycle."});return}s.add(E);for(let a of e[E]?.dependsOn??[])if(!e[a.service])t.push({severity:"error",path:`services.${E}.depends_on.${a.service}`,code:"dependency.missing",message:`Dependency ${a.service} does not exist.`});else i(a.service);s.delete(E),n.add(E),r.push(E)};return Object.keys(e).sort().forEach(i),r}function se(e,t){if(Buffer.byteLength(e)>524288)throw Error("Compose source exceeds the 512 KiB limit");let r;try{r=I(Bun.YAML.parse(e))}catch(c){throw Error(`Compose YAML could not be parsed: ${c instanceof Error?c.message:String(c)}`)}let s=[],n=I(r.services),i=Object.keys(n);if(!i.length)s.push({severity:"error",path:"services",code:"services.required",message:"At least one service is required."});if(i.length>64)s.push({severity:"error",path:"services",code:"services.limit",message:"A Compose application may contain at most 64 services."});let E=new Set(Object.keys(I(r.volumes))),a=new Set(Object.keys(I(r.networks))),d={};for(let c of i.sort()){let l=`services.${c}`,_=I(n[c]);if(!Cs.test(c)){s.push({severity:"error",path:l,code:"service.name",message:"Service names must be portable lowercase identifiers."});continue}for(let[X,Is]of Ls)if(_[X]!=null&&_[X]!==!1&&(!Array.isArray(_[X])||_[X].length))s.push({severity:"error",path:`${l}.${X}`,code:`unsafe.${X}`,message:Is});for(let X of Object.keys(_))if(!Ui.has(X)&&!Ls.has(X))s.push({severity:"warning",path:`${l}.${X}`,code:"field.unsupported",message:`Compose field ${X} is not in the supported subset and will not be deployed.`});let L=_.image?String(_.image):void 0,u=vi(_.build,`${l}.build`,s);if(!L&&!u)s.push({severity:"error",path:l,code:"service.source",message:"Each service requires image or build."});if(L&&!L.includes("@sha256:")&&(!L.includes(":")||L.endsWith(":latest")))s.push({severity:"warning",path:`${l}.image`,code:"image.floating",message:`Image ${L} is not pinned to a digest or explicit tag.`});let C=Vt(_.networks).map((X)=>typeof X==="string"?X:String(I(X).name??"")).filter(Boolean);C.forEach((X)=>a.add(X));let g=I(_.deploy),R=I(g.resources),S=I(R.limits),y=["no","always","on-failure","unless-stopped"].includes(String(_.restart))?String(_.restart):"unless-stopped";d[c]={name:c,...L?{image:L}:{},...u?{build:u}:{},...Xe(_.command)?{command:Xe(_.command)}:{},...Xe(_.entrypoint)?{entrypoint:Xe(_.entrypoint)}:{},environment:gs(_.environment,`${l}.environment`,s),ports:Si(_.ports,`${l}.ports`,s),volumes:Xi(_.volumes,E,`${l}.volumes`,s),networks:C,dependsOn:Ii(_.depends_on),...us(_.healthcheck)?{healthCheck:us(_.healthcheck)}:{},restart:y,...Number(S.cpus)>0?{cpu:Number(S.cpus)}:{},...ms(S.memory)?{memoryMb:ms(S.memory)}:{},replicas:Math.max(1,Math.min(100,Number(g.replicas)||1)),domains:yi(_.labels,`${l}.labels`,s)}}let T=pi(d,s),N={apiVersion:"ts-cloud.dev/v1",kind:"ComposeApplication",metadata:{name:t.name.trim(),slug:hi(t.slug??t.name),projectId:t.projectId,environmentId:t.environmentId},spec:{services:d,networks:[...a].sort(),volumes:[...E].sort(),dependencyOrder:T}},o=Wt(N);return{valid:!s.some((c)=>c.severity==="error"),manifest:N,diagnostics:s,redactedSource:o,sourceHash:Ri("sha256").update(e).digest("hex")}}function Wt(e){let t=Object.fromEntries(Object.entries(e.spec.services).map(([r,s])=>[r,{...s.image?{image:s.image}:{},...s.build?{build:{context:s.build.context,dockerfile:s.build.dockerfile,...s.build.target?{target:s.build.target}:{},...Object.keys(s.build.args).length?{args:Object.fromEntries(Object.entries(s.build.args).map(([n,i])=>[n,typeof i==="string"?i:`\${${i.secretRef}:?required secret ${i.secretRef}}`]))}:{}}}:{},...s.command?{command:s.command}:{},...s.entrypoint?{entrypoint:s.entrypoint}:{},...Object.keys(s.environment).length?{environment:Object.fromEntries(Object.entries(s.environment).map(([n,i])=>[n,typeof i==="string"?i:`\${${i.secretRef}:?required secret ${i.secretRef}}`]))}:{},...s.ports.length?{ports:s.ports.map((n)=>`${n.published?`${n.published}:`:""}${n.target}${n.protocol==="udp"?"/udp":""}`)}:{},...s.volumes.length?{volumes:s.volumes.map((n)=>`${n.source}:${n.target}${n.readOnly?":ro":""}`)}:{},...s.networks.length?{networks:s.networks}:{},...s.dependsOn.length?{depends_on:Object.fromEntries(s.dependsOn.map((n)=>[n.service,{condition:n.condition}]))}:{},...s.healthCheck?{healthcheck:{test:s.healthCheck.test,interval:`${s.healthCheck.intervalSeconds}s`,timeout:`${s.healthCheck.timeoutSeconds}s`,retries:s.healthCheck.retries,...s.healthCheck.startPeriodSeconds!=null?{start_period:`${s.healthCheck.startPeriodSeconds}s`}:{}}}:{},restart:s.restart,...s.cpu||s.memoryMb||s.replicas!==1?{deploy:{replicas:s.replicas,resources:{limits:{...s.cpu?{cpus:String(s.cpu)}:{},...s.memoryMb?{memory:`${s.memoryMb}M`}:{}}}}}:{},...s.domains.length?{labels:{"ts-cloud.domains":s.domains.join(",")}}:{}}]));return Bun.YAML.stringify({services:t,...e.spec.networks.length?{networks:Object.fromEntries(e.spec.networks.map((r)=>[r,{}]))}:{},...e.spec.volumes.length?{volumes:Object.fromEntries(e.spec.volumes.map((r)=>[r,{}]))}:{}})}function Jt(e,t){let r=[],s=(n,i,E)=>{if(JSON.stringify(i)===JSON.stringify(E))return;if(i&&E&&typeof i==="object"&&typeof E==="object"&&!Array.isArray(i)&&!Array.isArray(E)){for(let a of[...new Set([...Object.keys(i),...Object.keys(E)])].sort())s(n?`${n}.${a}`:a,i[a],E[a]);return}r.push({path:n,...i!==void 0?{before:i}:{},...E!==void 0?{after:E}:{}})};return s("",e,t),r}import{createHash as Rs}from"node:crypto";var Di="2026-07-21T00:00:00.000Z",Os=[{id:"bun-postgres-redis",name:"Bun + Postgres + Redis",description:"Web and worker services with durable Postgres and Redis dependencies.",category:"application",version:"1.0.0",sourceVersion:"oven/bun:1.2.21,postgres:17.5,redis:8.0.3",architecture:"web → Postgres + Redis; worker → Postgres + Redis",minimumResources:{cpu:2,memoryMb:3072},exposedServices:["web"],maintenanceNotes:"Back up the Postgres volume before major upgrades.",inputs:[{name:"domain",label:"Web domain",required:!0,secret:!1}],source:`services:
|
|
1558
1558
|
web:
|
|
1559
1559
|
image: oven/bun:1.2.21
|
|
1560
1560
|
command: [bun, run, start]
|
|
@@ -1610,8 +1610,8 @@ volumes:
|
|
|
1610
1610
|
volumes:
|
|
1611
1611
|
wordpress-data: {}
|
|
1612
1612
|
database-data: {}
|
|
1613
|
-
`}];function Xo(){return vn.map(({source:e,...t})=>({...t,source:`builtin:${t.id}`,lastVerifiedAt:ko,builtin:!0,checksum:Ln("sha256").update(e).digest("hex"),exposedServices:[...t.exposedServices],inputs:t.inputs.map((r)=>({...r}))}))}function Po(e,t){return Xo().find((r)=>r.id===e&&(!t||r.version===t))}function Zt(e,t,r,n){let i=vn.find((s)=>s.id===e&&(!n||s.version===n));if(!i)throw Error(`Compose template ${e}${n?`@${n}`:""} was not found`);let o=i.source;for(let s of i.inputs){let a=t[s.name]??("default"in s?s.default:void 0);if(s.required&&!a)throw Error(`Template input ${s.name} is required`);if(a&&!/^[A-Za-z0-9._:/@+-]{1,255}$/.test(a))throw Error(`Template input ${s.name} contains unsupported characters`);o=o.replaceAll(`{{${s.name}}}`,a??"")}return ie(o,r)}function Ud(e,t){if(Buffer.byteLength(e)>1048576)throw Error("Compose catalog exceeds the 1 MiB limit");let r;try{r=JSON.parse(e)}catch{throw Error("Compose catalog must be valid JSON")}if(r.apiVersion!=="ts-cloud.dev/compose-catalog/v1"||!Array.isArray(r.templates))throw Error("Compose catalog must use ts-cloud.dev/compose-catalog/v1 and contain templates");let n=String(r.source??"").trim();if(!/^https:\/\//.test(n)&&!n.startsWith("file:"))throw Error("Compose catalog source must be HTTPS or an explicit file: source");let i=[],o=[];for(let[s,a]of r.templates.slice(0,100).entries()){let d=a&&typeof a==="object"&&!Array.isArray(a)?a:{},c=`templates[${s}]`,p=String(d.compose??""),l=Ln("sha256").update(p).digest("hex");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(String(d.id??""))||!/^\d+\.\d+\.\d+$/.test(String(d.version??""))){i.push({severity:"error",path:c,code:"template.identity",message:"Template id and semantic version are required."});continue}if(String(d.checksum??"")!==l){i.push({severity:"error",path:`${c}.checksum`,code:"template.checksum",message:"Template checksum does not match its Compose source."});continue}let u=ie(p,{name:String(d.name??d.id),projectId:t.projectId,environmentId:t.environmentId});i.push(...u.diagnostics.map((E)=>({...E,path:`${c}.compose.${E.path}`})));let m={id:String(d.id),name:String(d.name??d.id),description:String(d.description??""),category:String(d.category??"custom"),version:String(d.version),source:n,sourceVersion:String(d.sourceVersion??d.version),architecture:String(d.architecture??Object.keys(u.manifest.spec.services).join(" + ")),minimumResources:{cpu:Math.max(0.1,Number(d.minimumResources?.cpu)||1),memoryMb:Math.max(128,Number(d.minimumResources?.memoryMb)||512)},exposedServices:Array.isArray(d.exposedServices)?d.exposedServices.map(String):[],maintenanceNotes:String(d.maintenanceNotes??""),lastVerifiedAt:String(d.lastVerifiedAt??""),inputs:[],checksum:l,builtin:!1};o.push({template:m,parsed:u})}return{valid:!i.some((s)=>s.severity==="error"),source:n,templates:o,diagnostics:i}}function Dd(e,t,r,n,i,o){let s=Po(r,o);if(!s)throw Error(`Compose template ${r}@${o} was not found`);let a=Zt(r,n,i,o);return{template:s,parsed:a,templateChanges:Jt(t,a.manifest),userChanges:Jt(t,e)}}var nt=/^[a-z0-9][a-z0-9_.-]{0,62}$/;function A(e){return`'${e.replaceAll("'","'\\''")}'`}function it(e){return`${e.metadata.slug}-${e.metadata.environmentId.slice(0,8)}`.replace(/[^a-z0-9_-]/g,"-").slice(0,63)}function Xd(e,t,r={}){let n=it(e),i=`/opt/ts-cloud/compose/${n}`,o=`${i}/compose.yaml`,s=`docker compose --project-name ${A(n)} --file ${A(o)}`;if(r.service&&!nt.test(r.service))throw Error("Unsafe Compose service name");if(t==="deploy"||t==="redeploy"){let a=Buffer.from(Wt(e)).toString("base64");return`install -d -m 0750 ${A(i)} && printf %s ${A(a)} | base64 --decode > ${A(o)} && chmod 0640 ${A(o)} && ${s} config --quiet && ${s} up --detach --remove-orphans --wait${t==="redeploy"?" --force-recreate":""}`}if(t==="start")return`${s} start${r.service?` ${A(r.service)}`:""}`;if(t==="stop")return`${s} stop${r.service?` ${A(r.service)}`:""}`;if(t==="status")return`${s} ps --format json`;return`${s} down --remove-orphans${r.removeVolumes?" --volumes":""}`}function Pd(e,t,r){if(!nt.test(t)||!Number.isInteger(r)||r<0||r>100)throw Error("Scale requires a safe service name and 0-100 replicas");let n=it(e);return`docker compose --project-name ${A(n)} --file ${A(`/opt/ts-cloud/compose/${n}/compose.yaml`)} up --detach --wait --scale ${A(`${t}=${r}`)}`}function xd(e,t,r=200){if(!nt.test(t))throw Error("Unsafe Compose service name");let n=it(e);return`docker compose --project-name ${A(n)} --file ${A(`/opt/ts-cloud/compose/${n}/compose.yaml`)} logs --no-color --timestamps --tail ${Math.max(1,Math.min(2000,Math.floor(r)))} ${A(t)}`}function jd(e,t,r=["sh"]){if(!nt.test(t)||!r.length||r.some((i)=>i.includes("\x00")||i.length>1024))throw Error("Unsafe Compose shell request");let n=it(e);return`docker compose --project-name ${A(n)} --file ${A(`/opt/ts-cloud/compose/${n}/compose.yaml`)} exec ${A(t)} ${r.map(A).join(" ")}`}import{mkdir as tr,readdir as Ko,rm as $o,stat as Qo}from"node:fs/promises";import{basename as Yo,resolve as In,sep as Go}from"node:path";var er=/^[a-z0-9][a-z0-9_.-]{1,62}$/,xo=/^0?[0-7]{3}$/,jo=["/","/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run","/var/lib/docker","/var/lib/containers"],Fo=["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],Mo=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function zo(e){return Object.fromEntries(Fo.map((t)=>[t,{supported:!1,reason:e}]))}function ot(e,t={}){let r=zo("This storage driver does not support the operation.");for(let n of e)r[n]={supported:!0};return{...r,...t}}function qo(e){if(!e.startsWith("/")||e.includes("\x00")||e.split("/").includes(".."))throw Error("Mount target must be an absolute normalized path without traversal.");let t=e.replace(/\/+$/,"")||"/";if(jo.some((r)=>t===r||t.startsWith(`${r}/`)))throw Error(`Mount target ${e} is a protected host or runtime path.`)}function Ho(e){if(qo(e.targetPath),e.uid!=null&&(!Number.isInteger(e.uid)||e.uid<0))throw Error("Mount UID must be a non-negative integer.");if(e.gid!=null&&(!Number.isInteger(e.gid)||e.gid<0))throw Error("Mount GID must be a non-negative integer.");if(e.mode&&!xo.test(e.mode))throw Error("Mount mode must be a three or four digit octal value.");if(e.propagation&&!["private","rprivate","shared","rshared","slave","rslave"].includes(e.propagation))throw Error("Unsupported mount propagation mode.")}class Bo{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new H(e.controlPlane)}driver(e,t){let r=this.drivers.find((n)=>n.provider===e&&n.type===t);if(!r)throw Error(`No ${e} ${t} volume driver is configured.`);return r}capability(e,t){let r=e.capabilities[t];if(!r?.supported)throw Error(r?.reason??`${t} is unsupported for this volume.`)}queueMutation(e,t,r,n,i){return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:i??e.resourceId,actorId:n,kind:t,idempotencyKey:`${t}:${e.id}:v${e.version}:${JSON.stringify(r)}`,correlationId:`volume:${e.id}`,input:{volumeId:e.id,...r},lockKey:i?`resource:${i}`:`volume:${e.id}`,providerKey:e.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}create(e){if(!er.test(e.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");if(e.capacityBytes!=null&&(!Number.isSafeInteger(e.capacityBytes)||e.capacityBytes<=0))throw Error("Volume capacity must be a positive byte count.");let t=this.store.controlPlane.getProject(e.projectId),r=e.environmentId?this.store.controlPlane.listEnvironments(e.projectId).find((c)=>c.id===e.environmentId):void 0,n=e.resourceId?this.store.controlPlane.getResource(e.resourceId):void 0;if(!t||t.organizationId!==e.organizationId)throw Error("Volume project does not belong to the organization.");if(e.environmentId&&!r)throw Error("Volume environment does not belong to the project.");if(n&&(n.projectId!==e.projectId||n.environmentId!==e.environmentId||n.kind!=="volume"))throw Error("Volume resource does not belong to the selected scope.");let i=n??this.store.controlPlane.createResource({projectId:e.projectId,environmentId:e.environmentId,kind:"volume",slug:e.name,name:e.name,provider:e.provider,desiredState:{type:e.type,capacityBytes:e.capacityBytes??null,filesystem:e.filesystem??null,encrypted:!!e.encrypted}}),o=this.driver(e.provider,e.type),s=o.capabilities(),a=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,resourceId:i.id,name:e.name,provider:e.provider,type:e.type,status:"pending",capacityBytes:e.capacityBytes,filesystem:e.filesystem,encrypted:!!e.encrypted,capabilities:s,desiredState:e.desiredState??{},observedState:{}}),d=this.queueMutation(a,"volume.create",{},e.actorId);return this.store.audit({organizationId:a.organizationId,projectId:a.projectId,environmentId:a.environmentId,actorId:e.actorId,type:"volume.create.queued",volumeId:a.id,payload:{name:a.name,type:a.type}}),{volume:a,operation:d}}attach(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"attach"),Ho(t);let n=this.store.controlPlane.getResource(t.resourceId);if(!n||n.projectId!==r.projectId||n.environmentId!==r.environmentId)throw Error("Cross-project or cross-environment volume attachments are forbidden.");let i=this.store.upsertAttachment({volumeId:e,resourceId:t.resourceId,targetPath:t.targetPath,readOnly:!!t.readOnly,uid:t.uid,gid:t.gid,mode:t.mode,propagation:t.propagation??"private",driverOptions:t.driverOptions??{},desiredState:"attached",observedState:"pending"}),o=this.queueMutation(r,"volume.attach",{attachmentId:i.id},t.actorId,t.resourceId);return this.store.updateAttachment(i.id,{operationId:o.id}),this.store.update(r.id,r.version,{status:"attaching"}),this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.attach.queued",volumeId:e,payload:{resourceId:t.resourceId,targetPath:t.targetPath}}),{volume:this.store.get(r.id),attachment:this.store.attachment(i.id),operation:o}}detach(e,t,r={}){let n=this.store.get(e),i=this.store.attachment(t);if(!n||!i||i.volumeId!==e)throw Error("Volume attachment was not found.");if(this.capability(n,"detach"),i.observedState==="attached"&&(!r.drained||!r.unmounted))throw Error("Detach requires completed workload drain and filesystem unmount checkpoints.");if(r.force&&r.confirmation!==`detach ${n.name}`)throw Error(`Force detach requires confirmation: detach ${n.name}`);let o=this.store.updateAttachment(t,{desiredState:"detached"}),s=this.queueMutation(n,"volume.detach",{attachmentId:t,force:!!r.force},r.actorId,i.resourceId);return this.store.updateAttachment(t,{operationId:s.id}),this.store.update(n.id,n.version,{status:"detaching"}),{volume:this.store.get(e),attachment:o,operation:s}}resize(e,t,r={}){let n=this.store.get(e);if(!n)throw Error("Volume was not found.");if(this.capability(n,"resize"),!Number.isSafeInteger(t)||t<=0)throw Error("Volume capacity must be a positive byte count.");if(n.capacityBytes!=null&&t<n.capacityBytes)throw Error("Volume shrinking is not supported because it can corrupt data.");let i=n.capabilities.resize;if(i.minimumBytes&&t<i.minimumBytes)throw Error(`Minimum supported capacity is ${i.minimumBytes} bytes.`);if(i.maximumBytes&&t>i.maximumBytes)throw Error(`Maximum supported capacity is ${i.maximumBytes} bytes.`);if(i.online===!1&&!r.drained)throw Error("This resize requires a completed workload drain checkpoint.");let o=this.store.update(e,n.version,{status:"resizing",desiredState:{...n.desiredState,capacityBytes:t}}),s=this.queueMutation(o,"volume.resize",{capacityBytes:t},r.actorId);return{volume:o,operation:s}}snapshot(e,t={}){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"snapshot");let n=this.store.createSnapshot({volumeId:e,name:t.name??`${r.name}-${this.now().toISOString().replace(/[:.]/g,"-")}`,status:"pending",encrypted:r.encrypted,metadata:{}}),i=this.store.update(e,r.version,{status:"snapshotting"}),o=this.queueMutation(i,"volume.snapshot",{snapshotId:n.id},t.actorId);return{volume:i,snapshot:n,operation:o}}restore(e,t){let r=this.store.snapshot(e),n=r?this.store.get(r.volumeId):void 0;if(!r||!n||r.status!=="available")throw Error("An available volume snapshot is required for restore.");if(this.capability(n,"restore"),!er.test(t.name))throw Error("Restored volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let i=this.store.controlPlane.createResource({projectId:n.projectId,environmentId:n.environmentId,kind:"volume",slug:t.name,name:t.name,provider:n.provider,desiredState:{restoreFromSnapshotId:r.id}}),o=this.store.create({organizationId:n.organizationId,projectId:n.projectId,environmentId:n.environmentId,resourceId:i.id,name:t.name,provider:n.provider,type:n.type,status:"pending",capacityBytes:r.sizeBytes??n.capacityBytes,filesystem:n.filesystem,encrypted:r.encrypted,capabilities:n.capabilities,desiredState:{restoreFromSnapshotId:r.id,sourceVolumeId:n.id},observedState:{}}),s=this.queueMutation(o,"volume.restore",{snapshotId:r.id,sourceVolumeId:n.id},t.actorId);return{volume:o,snapshot:r,operation:s}}delete(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"delete");let n=this.store.attachments(e).filter((a)=>a.desiredState==="attached"||a.observedState==="attached");if(n.length)throw Error(`Detach ${n.length} active consumer(s) before deleting this volume.`);if(!t.recentAuthAt||this.now().getTime()-new Date(t.recentAuthAt).getTime()>900000)throw Error("Volume deletion requires authentication verified within the last 15 minutes.");if(t.confirmation!==r.name)throw Error(`Type ${r.name} to confirm permanent volume deletion.`);if(!(r.lastBackupAt&&this.now().getTime()-new Date(r.lastBackupAt).getTime()<=86400000)&&(!t.backupOverride||t.backupOverrideConfirmation!==`delete without backup ${r.name}`))throw Error(`A verified backup from the last 24 hours is required, or confirm: delete without backup ${r.name}`);let o=this.store.update(e,r.version,{status:"deleting"}),s=this.queueMutation(o,"volume.delete",{backupOverride:!!t.backupOverride},t.actorId);return{volume:o,operation:s}}async discover(e){let t=new Set;for(let r of this.drivers)for(let n of await r.discover(e.projectId,e.environmentId)){let i=this.store.list({projectId:e.projectId,environmentId:e.environmentId}).find((s)=>s.provider===r.provider&&s.providerId===n.providerId);if(i){t.add(i.id),this.store.update(i.id,i.version,{capacityBytes:n.capacityBytes,usedBytes:n.usedBytes,filesystem:n.filesystem,encrypted:n.encrypted??i.encrypted,observedState:n.raw??{},status:i.status==="orphaned"?"available":i.status,orphanedAt:void 0});continue}let o=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,name:`orphan-${n.providerId}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),provider:r.provider,providerId:n.providerId,type:r.type,status:"orphaned",capacityBytes:n.capacityBytes,usedBytes:n.usedBytes,filesystem:n.filesystem,encrypted:!!n.encrypted,capabilities:r.capabilities(),desiredState:{},observedState:n.raw??{},orphanedAt:this.now().toISOString()});t.add(o.id)}return this.store.list({projectId:e.projectId,environmentId:e.environmentId})}adopt(e,t){let r=this.store.get(e);if(!r||r.status!=="orphaned")throw Error("Only discovered orphan volumes can be adopted.");if(!er.test(t.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let n=this.store.update(e,r.version,{name:t.name,status:"available",adoptedAt:this.now().toISOString(),orphanedAt:void 0});return this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.adopted",volumeId:e,payload:{providerId:r.providerId??null}}),n}}function Vo(e){let t=Mo(e.input);if(typeof t.volumeId!=="string")throw Error("Queued volume operation is missing its volume identity.");return{volumeId:t.volumeId,sourceVolumeId:typeof t.sourceVolumeId==="string"?t.sourceVolumeId:void 0,attachmentId:typeof t.attachmentId==="string"?t.attachmentId:void 0,snapshotId:typeof t.snapshotId==="string"?t.snapshotId:void 0,capacityBytes:typeof t.capacityBytes==="number"?t.capacityBytes:void 0,force:t.force===!0}}function zd(e,t){let r=(i)=>{let o=t.find((s)=>s.provider===i.provider&&s.type===i.type);if(!o)throw Error(`No ${i.provider} ${i.type} volume driver is configured.`);return o},n=async(i)=>{let o=Vo(i.operation),s=e.get(o.volumeId);if(!s)throw Error("Queued volume was not found.");let a=r(s);i.checkpoint("preflight","Validating persistent volume identity and capabilities."),i.throwIfCancellationRequested();let d;if(i.operation.kind==="volume.create")d=await a.create(s),e.update(s.id,s.version,{providerId:d.providerId,capacityBytes:d.capacityBytes??s.capacityBytes,usedBytes:d.usedBytes,filesystem:d.filesystem??s.filesystem,encrypted:d.encrypted??s.encrypted,observedState:d.raw??{},status:"available"});else if(i.operation.kind==="volume.attach"){let c=o.attachmentId?e.attachment(o.attachmentId):void 0;if(!c)throw Error("Queued volume attachment was not found.");await a.attach(s,c),e.updateAttachment(c.id,{observedState:"attached",lastError:void 0}),e.update(s.id,s.version,{status:"attached"})}else if(i.operation.kind==="volume.detach"){let c=o.attachmentId?e.attachment(o.attachmentId):void 0;if(!c)throw Error("Queued volume attachment was not found.");await a.detach(s,c,{force:o.force}),e.updateAttachment(c.id,{observedState:"detached",lastError:void 0});let p=e.attachments(s.id).some((l)=>l.id!==c.id&&l.observedState==="attached");e.update(s.id,s.version,{status:p?"attached":"available"})}else if(i.operation.kind==="volume.resize"){if(!o.capacityBytes)throw Error("Queued volume resize is missing its capacity.");d=await a.resize(s,o.capacityBytes),e.update(s.id,s.version,{capacityBytes:d.capacityBytes??o.capacityBytes,usedBytes:d.usedBytes??s.usedBytes,observedState:d.raw??s.observedState,status:e.attachments(s.id).some((c)=>c.observedState==="attached")?"attached":"available"})}else if(i.operation.kind==="volume.snapshot"){let c=o.snapshotId?e.snapshot(o.snapshotId):void 0;if(!c)throw Error("Queued volume snapshot was not found.");let p=await a.snapshot(s,c);e.updateSnapshot(c.id,{...p,status:"available"}),e.update(s.id,s.version,{status:e.attachments(s.id).some((l)=>l.observedState==="attached")?"attached":"available",lastBackupAt:new Date().toISOString()})}else if(i.operation.kind==="volume.restore"){let c=o.snapshotId?e.snapshot(o.snapshotId):void 0,p=o.sourceVolumeId?e.get(o.sourceVolumeId):void 0;if(!c||!p)throw Error("Queued volume restore source was not found.");d=await a.restore(p,c,s),e.update(s.id,s.version,{providerId:d.providerId,capacityBytes:d.capacityBytes??s.capacityBytes,usedBytes:d.usedBytes,filesystem:d.filesystem??s.filesystem,encrypted:d.encrypted??s.encrypted,observedState:d.raw??{},status:"available"})}else if(i.operation.kind==="volume.delete")await a.delete(s),e.update(s.id,s.version,{status:"deleted",deletedAt:new Date().toISOString()});return i.checkpoint("finalize","Persisted observed volume state."),{volumeId:s.id,status:e.get(s.id)?.status??"deleted"}};return Object.fromEntries(["volume.create","volume.attach","volume.detach","volume.resize","volume.snapshot","volume.restore","volume.delete"].map((i)=>[i,n]))}var Wo=async(e)=>{let t=Bun.spawn(["docker",...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}},oe=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;class rr{command;provider="docker";type="docker";constructor(e=Wo){this.command=e}capabilities(){return ot(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Docker named volumes do not expose a portable capacity resize operation."},snapshot:{supported:!1,reason:"Attach a volume backup policy to create verified recovery points."},restore:{supported:!1,reason:"Restore this volume from its verified backup recovery point."}})}async run(e,t=!1){let r=await this.command(e);if(r.code!==0&&!t)throw Error(`Docker volume command failed: ${r.stderr.trim()||r.code}`);return r.stdout}async inspect(e){let t=await this.run(["volume","inspect",e],!0);if(!t.trim())return;let r;try{r=JSON.parse(t)[0]}catch{return}return{providerId:String(r.Name??e),raw:{driver:String(r.Driver??"local"),mountpoint:String(r.Mountpoint??""),labels:r.Labels??{}}}}async discover(e,t){let r=await this.run(["volume","ls","--format","{{.Name}}"]),n=[];for(let i of r.split(`
|
|
1614
|
-
`).map((
|
|
1615
|
-
`).find((n)=>n.includes(`"Name":"${e.providerId}"`));if(!r)return{};try{let n=JSON.parse(r);return{usedBytes:typeof n.Size==="number"?n.Size:void 0}}catch{return{}}}}class Jo{provider="server";type="server_path";root;constructor(e){this.root=In(e)}capabilities(){return ot(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Server paths use the capacity of their containing filesystem."},snapshot:{supported:!1,reason:"Attach a filesystem backup policy for verified recovery points."},restore:{supported:!1,reason:"Restore a filesystem recovery point into a new managed path."}})}path(e){if(!oe.test(e))throw Error("Server path volume name is invalid.");let t=In(this.root,e);if(!t.startsWith(`${this.root}${Go}`)||Yo(t)!==e)throw Error("Server path escaped the managed volume root.");return t}async discover(e,t){return await tr(this.root,{recursive:!0,mode:488}),(await Ko(this.root,{withFileTypes:!0})).filter((n)=>n.isDirectory()&&oe.test(n.name)).map((n)=>({providerId:n.name,raw:{path:this.path(n.name)}}))}async create(e){let t=typeof e.desiredState.nativeName==="string"?e.desiredState.nativeName:e.name,r=this.path(t);return await tr(this.root,{recursive:!0,mode:488}),await tr(r,{recursive:!1,mode:488}),{providerId:t,filesystem:"host",raw:{path:r}}}async attach(e,t){}async detach(e,t){}async resize(){throw Error(this.capabilities().resize.reason)}async snapshot(){throw Error(this.capabilities().snapshot.reason)}async restore(e,t,r){throw Error(this.capabilities().restore.reason)}async delete(e){if(!e.providerId)throw Error("Server path provider identity is unavailable.");await $o(this.path(e.providerId),{recursive:!0,force:!1})}async usage(e){if(!e.providerId)return{};return{usedBytes:(await Qo(this.path(e.providerId))).size}}}class Zo{provider;transport;type="ebs";constructor(e,t){this.provider=e;this.transport=t}capabilities(){return ot(["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],{resize:{supported:!0,online:!0,minimumBytes:1073741824}})}discover(e,t){return this.transport.list(e,t)}create(e){return this.transport.create({name:e.name,projectId:e.projectId,environmentId:e.environmentId,capacityBytes:e.capacityBytes,encrypted:e.encrypted,filesystem:e.filesystem})}resource(e,t){let r=e.resourceId===t.resourceId?e.observedState.resourceProviderId:void 0,n=typeof r==="string"?r:t.driverOptions.resourceProviderId;if(typeof n!=="string"||!n)throw Error("Cloud attachment requires a reviewed resourceProviderId driver option.");return n}attach(e,t){return this.transport.attach(e.providerId,this.resource(e,t),t.targetPath,t.readOnly)}detach(e,t,r){return this.transport.detach(e.providerId,this.resource(e,t),r.force)}resize(e,t){return this.transport.resize(e.providerId,t)}snapshot(e,t){return this.transport.snapshot(e.providerId,t.name)}restore(e,t,r){if(!t.providerId)throw Error("Cloud snapshot provider identity is unavailable.");return this.transport.restore(e.providerId,t.providerId,r.name)}delete(e){return this.transport.delete(e.providerId)}usage(e){return this.transport.usage(e.providerId)}}var w=(e)=>e==null?void 0:String(e),Ae=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},ir=(e)=>Number(e)===1,se=(e)=>e().toISOString();function Sn(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:w(e.environment_id),resourceId:w(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:w(e.provider_id),type:String(e.type),status:String(e.status),capacityBytes:e.capacity_bytes==null?void 0:Number(e.capacity_bytes),usedBytes:e.used_bytes==null?void 0:Number(e.used_bytes),filesystem:w(e.filesystem),encrypted:ir(e.encrypted),capabilities:Ae(e.capabilities,{}),desiredState:Ae(e.desired_state,{}),observedState:Ae(e.observed_state,{}),backupPolicyId:w(e.backup_policy_id),lastBackupAt:w(e.last_backup_at),orphanedAt:w(e.orphaned_at),adoptedAt:w(e.adopted_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:w(e.deleted_at)}}function nr(e){return{id:String(e.id),volumeId:String(e.volume_id),resourceId:String(e.resource_id),targetPath:String(e.target_path),readOnly:ir(e.read_only),uid:e.uid==null?void 0:Number(e.uid),gid:e.gid==null?void 0:Number(e.gid),mode:w(e.mode),propagation:String(e.propagation),driverOptions:Ae(e.driver_options,{}),desiredState:String(e.desired_state),observedState:String(e.observed_state),operationId:w(e.operation_id),lastError:w(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function bn(e){return{id:String(e.id),volumeId:String(e.volume_id),recoveryPointId:w(e.recovery_point_id),providerId:w(e.provider_id),name:String(e.name),status:String(e.status),sizeBytes:e.size_bytes==null?void 0:Number(e.size_bytes),encrypted:ir(e.encrypted),checksum:w(e.checksum),metadata:Ae(e.metadata,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:w(e.deleted_at)}}class st{controlPlane;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.controlPlane=e;this.now=t;this.id=r}get(e){let t=this.controlPlane.database.query("SELECT * FROM persistent_volumes WHERE id=?").get(e);return t?Sn(t):void 0}list(e){let t=["project_id=?"],r=[e.projectId];if(e.environmentId)t.push("environment_id=?"),r.push(e.environmentId);if(!e.includeDeleted)t.push("deleted_at IS NULL");return this.controlPlane.database.query(`SELECT * FROM persistent_volumes WHERE ${t.join(" AND ")} ORDER BY name`).all(...r).map(Sn)}create(e){let t=se(this.now),r=e.id??this.id();return this.controlPlane.database.run("INSERT INTO persistent_volumes (id,organization_id,project_id,environment_id,resource_id,name,provider,provider_id,type,status,capacity_bytes,used_bytes,filesystem,encrypted,capabilities,desired_state,observed_state,backup_policy_id,last_backup_at,orphaned_at,adopted_at,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.provider,e.providerId??null,e.type,e.status,e.capacityBytes??null,e.usedBytes??null,e.filesystem??null,e.encrypted?1:0,JSON.stringify(e.capabilities),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),e.backupPolicyId??null,e.lastBackupAt??null,e.orphanedAt??null,e.adoptedAt??null,t,t,e.deletedAt??null]),this.get(r)}update(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error("Volume changed before this operation could be applied.");let i={...n,...r,updatedAt:se(this.now)};if(this.controlPlane.database.run("UPDATE persistent_volumes SET environment_id=?,resource_id=?,name=?,provider=?,provider_id=?,type=?,status=?,capacity_bytes=?,used_bytes=?,filesystem=?,encrypted=?,capabilities=?,desired_state=?,observed_state=?,backup_policy_id=?,last_backup_at=?,orphaned_at=?,adopted_at=?,deleted_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[i.environmentId??null,i.resourceId??null,i.name,i.provider,i.providerId??null,i.type,i.status,i.capacityBytes??null,i.usedBytes??null,i.filesystem??null,i.encrypted?1:0,JSON.stringify(i.capabilities),JSON.stringify(i.desiredState),JSON.stringify(i.observedState),i.backupPolicyId??null,i.lastBackupAt??null,i.orphanedAt??null,i.adoptedAt??null,i.deletedAt??null,i.updatedAt,e,t]).changes!==1)throw Error("Volume changed before this operation could be applied.");return this.get(e)}attachments(e){return this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? ORDER BY target_path").all(e).map(nr)}attachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE id=?").get(e);return t?nr(t):void 0}upsertAttachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? AND resource_id=? AND target_path=?").get(e.volumeId,e.resourceId,e.targetPath),r=se(this.now);if(t){let i=nr(t);return this.controlPlane.database.run("UPDATE volume_attachments SET read_only=?,uid=?,gid=?,mode=?,propagation=?,driver_options=?,desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,i.id]),this.attachment(i.id)}let n=e.id??this.id();return this.controlPlane.database.run("INSERT INTO volume_attachments (id,volume_id,resource_id,target_path,read_only,uid,gid,mode,propagation,driver_options,desired_state,observed_state,operation_id,last_error,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[n,e.volumeId,e.resourceId,e.targetPath,e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,r]),this.attachment(n)}updateAttachment(e,t){let r=this.attachment(e);if(!r)throw Error("Volume attachment was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE volume_attachments SET desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[n.desiredState,n.observedState,n.operationId??null,n.lastError??null,se(this.now),e]),this.attachment(e)}snapshots(e){return this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE volume_id=? AND deleted_at IS NULL ORDER BY created_at DESC").all(e).map(bn)}snapshot(e){let t=this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE id=?").get(e);return t?bn(t):void 0}createSnapshot(e){let t=e.id??this.id(),r=se(this.now);return this.controlPlane.database.run("INSERT INTO volume_snapshots (id,volume_id,recovery_point_id,provider_id,name,status,size_bytes,encrypted,checksum,metadata,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.volumeId,e.recoveryPointId??null,e.providerId??null,e.name,e.status,e.sizeBytes??null,e.encrypted?1:0,e.checksum??null,JSON.stringify(e.metadata),r,r,e.deletedAt??null]),this.snapshot(t)}updateSnapshot(e,t){let r=this.snapshot(e);if(!r)throw Error("Volume snapshot was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE volume_snapshots SET recovery_point_id=?,provider_id=?,name=?,status=?,size_bytes=?,encrypted=?,checksum=?,metadata=?,deleted_at=?,updated_at=? WHERE id=?",[n.recoveryPointId??null,n.providerId??null,n.name,n.status,n.sizeBytes??null,n.encrypted?1:0,n.checksum??null,JSON.stringify(n.metadata),n.deletedAt??null,se(this.now),e]),this.snapshot(e)}inventory(e,t){return this.list({projectId:e,environmentId:t}).map((r)=>{let n=this.attachments(r.id),i=this.snapshots(r.id),o=r.lastBackupAt?Date.now()-new Date(r.lastBackupAt).getTime():1/0;return{...r,attachments:n,snapshots:i,orphaned:r.status==="orphaned",usagePercent:r.capacityBytes&&r.usedBytes!=null?Math.round(r.usedBytes/r.capacityBytes*1000)/10:void 0,backupState:r.backupPolicyId?o<=86400000?"protected":"stale":"unprotected"}})}audit(e){this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:this.get(e.volumeId)?.resourceId,actorId:e.actorId,type:e.type,level:"warning",payload:{volumeId:e.volumeId,environmentId:e.environmentId??null,...e.payload}})}}function or(e,t){let r=e.getProject(t.projectId);if(!r?.organizationId)return;let n=new st(e),i=new rr,o=new Set(t.manifest.spec.volumes),s=new Set;for(let a of o){let d=`${t.slug}-${a}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),c=n.list({projectId:t.projectId,environmentId:t.environmentId,includeDeleted:!0}).find((m)=>m.name===d);if(c?.deletedAt)throw Error(`Compose volume ${d} was permanently deleted; rename it before redeploying.`);let p=c?.resourceId?e.getResource(c.resourceId):e.createResource({projectId:t.projectId,environmentId:t.environmentId,kind:"volume",slug:d,name:d,provider:"docker",providerId:d,desiredState:{composeApplicationId:t.id,composeVolume:a}}),l=c??n.create({organizationId:r.organizationId,projectId:t.projectId,environmentId:t.environmentId,resourceId:p?.id,name:d,provider:"docker",providerId:d,type:"docker",status:"available",encrypted:!1,capabilities:i.capabilities(),desiredState:{composeApplicationId:t.id,composeVolume:a,nativeName:d},observedState:{}});s.add(l.id);let u=new Map;for(let m of Object.values(t.manifest.spec.services))for(let E of m.volumes.filter((T)=>T.source===a)){let T=u.get(E.target)??[];T.push(m.name),u.set(E.target,T),n.upsertAttachment({volumeId:l.id,resourceId:t.resourceId,targetPath:E.target,readOnly:E.readOnly,propagation:"private",driverOptions:{composeServices:T},desiredState:"attached",observedState:"pending"})}}for(let a of n.list({projectId:t.projectId,environmentId:t.environmentId}).filter((d)=>d.desiredState.composeApplicationId===t.id&&!s.has(d.id)))for(let d of n.attachments(a.id))n.updateAttachment(d.id,{desiredState:"detached"})}function Rn(e,t,r){let n=new st(e);for(let i of n.list({projectId:t.projectId,environmentId:t.environmentId}).filter((o)=>o.desiredState.composeApplicationId===t.id)){for(let o of n.attachments(i.id))n.updateAttachment(o.id,{desiredState:"detached",observedState:"detached"});n.update(i.id,i.version,{status:r?"deleted":"available",deletedAt:r?new Date().toISOString():void 0})}}function ae(e){return typeof e==="string"&&e?e:void 0}function sr(e,t){try{return JSON.parse(String(e))}catch{return t}}function at(e){return{id:String(e.id),resourceId:String(e.resource_id),projectId:String(e.project_id),environmentId:String(e.environment_id),name:String(e.name),slug:String(e.slug),status:String(e.status),sourceKind:String(e.source_kind),sourceHash:String(e.source_hash),redactedSource:String(e.redacted_source),manifest:sr(e.manifest,{}),diagnostics:sr(e.diagnostics,[]),templateId:ae(e.template_id),templateVersion:ae(e.template_version),latestOperationId:ae(e.latest_operation_id),createdByActorId:ae(e.created_by_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:ae(e.deleted_at)}}function es(e){return{applicationId:String(e.application_id),serviceName:String(e.service_name),status:String(e.status),replicas:Number(e.replicas),healthyReplicas:Number(e.healthy_replicas),latestOperationId:ae(e.latest_operation_id),observedState:sr(e.observed_state,{}),updatedAt:String(e.updated_at)}}class ee{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}persist(e,t){if(!e.valid)throw Error(`Compose definition contains ${e.diagnostics.filter((E)=>E.severity==="error").length} blocking diagnostic(s)`);let{projectId:r,environmentId:n,name:i,slug:o}=e.manifest.metadata;if(!this.controlPlane.listEnvironments(r).find((E)=>E.id===n))throw Error("Compose project and environment scope was not found");let a=this.getBySlug(r,n,o),d=this.now().toISOString(),c=JSON.stringify(e.manifest),p=JSON.stringify(I(e.diagnostics));if(a){if(a.status==="deleted")throw Error("A deleted Compose application cannot be overwritten; choose another slug");let E=this.controlPlane.getResource(a.resourceId);if(!E)throw Error("Compose application resource was not found");this.controlPlane.updateResource(E.id,E.version,{name:i,provider:E.provider,providerId:E.providerId,desiredState:e.manifest,discoveredState:E.discoveredState,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),this.controlPlane.database.run("UPDATE compose_applications SET name=?, status='ready', source_kind=?, source_hash=?, redacted_source=?, manifest=?, diagnostics=?, template_id=?, template_version=?, version=version+1, updated_at=? WHERE id=?",[i,t.sourceKind,e.sourceHash,e.redactedSource,c,p,t.templateId??null,t.templateVersion??null,d,a.id]);let T=Object.keys(e.manifest.spec.services);if(T.length)this.controlPlane.database.run(`DELETE FROM compose_service_states WHERE application_id=? AND service_name NOT IN (${T.map(()=>"?").join(",")})`,[a.id,...T]);for(let h of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?) ON CONFLICT(application_id, service_name) DO UPDATE SET replicas=excluded.replicas, updated_at=excluded.updated_at",[a.id,h.name,h.replicas,d]);this.controlPlane.appendEvent({projectId:r,resourceId:a.resourceId,actorId:t.createdByActorId,type:"compose.application.updated",payload:{applicationId:a.id,sourceHash:e.sourceHash,diagnosticCount:e.diagnostics.length,templateId:t.templateId??null,templateVersion:t.templateVersion??null}});let _=this.get(a.id);return or(this.controlPlane,_),_}let l=this.controlPlane.createResource({projectId:r,environmentId:n,kind:"compose_application",slug:o,name:i,desiredState:e.manifest,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),u=this.id();this.controlPlane.database.run("INSERT INTO compose_applications (id, resource_id, project_id, environment_id, name, slug, status, source_kind, source_hash, redacted_source, manifest, diagnostics, template_id, template_version, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'ready', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[u,l.id,r,n,i,o,t.sourceKind,e.sourceHash,e.redactedSource,c,p,t.templateId??null,t.templateVersion??null,t.createdByActorId??null,d,d]);for(let E of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?)",[u,E.name,E.replicas,d]);this.controlPlane.appendEvent({projectId:r,resourceId:l.id,actorId:t.createdByActorId,type:"compose.application.created",payload:{applicationId:u,sourceHash:e.sourceHash,serviceNames:Object.keys(e.manifest.spec.services),templateId:t.templateId??null}});let m=this.get(u);return or(this.controlPlane,m),m}import(e,t){let r=ie(e,t);return{application:this.persist(r,{sourceKind:"compose",createdByActorId:t.createdByActorId}),parsed:r}}fromTemplate(e,t,r){let n=Zt(e,t,r,r.version);return{application:this.persist(n,{sourceKind:"template",templateId:e,templateVersion:r.version??"1.0.0",createdByActorId:r.createdByActorId}),parsed:n}}preview(e,t){return ie(e,t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE id=?").get(e);return t?at(t):void 0}getByResource(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE resource_id=?").get(e);return t?at(t):void 0}getBySlug(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE project_id=? AND environment_id=? AND slug=?").get(e,t,r);return n?at(n):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM compose_applications ORDER BY updated_at DESC").all().map(at).filter((t)=>(!e.projectId||t.projectId===e.projectId)&&(!e.environmentId||t.environmentId===e.environmentId)&&(e.includeDeleted||t.status!=="deleted"))}services(e){return this.controlPlane.database.query("SELECT * FROM compose_service_states WHERE application_id=? ORDER BY service_name").all(e).map(es)}transition(e,t,r={}){let n=this.get(e);if(!n)throw Error(`Compose application ${e} was not found`);let i=this.now().toISOString(),o=t==="deleted"?i:null;this.controlPlane.database.run("UPDATE compose_applications SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), version=version+1, updated_at=?, deleted_at=? WHERE id=?",[t,r.operationId??null,i,o,e]);for(let s of r.services??[])if(n.manifest.spec.services[s.name])this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, latest_operation_id, observed_state, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(application_id, service_name) DO UPDATE SET status=excluded.status, replicas=excluded.replicas, healthy_replicas=excluded.healthy_replicas, latest_operation_id=excluded.latest_operation_id, observed_state=excluded.observed_state, updated_at=excluded.updated_at",[e,s.name,s.status,s.replicas??n.manifest.spec.services[s.name].replicas,s.healthyReplicas??0,r.operationId??null,JSON.stringify(I(s.observedState??{})),i]);return this.controlPlane.appendEvent({projectId:n.projectId,resourceId:n.resourceId,operationId:r.operationId,type:`compose.application.${t}`,level:t==="failed"||t==="degraded"?"error":"info",payload:{applicationId:e,error:r.error??null}}),this.get(e)}}class ts{controlPlane;applications;queue;constructor(e){this.controlPlane=e;this.applications=new ee(e),this.queue=new H(e)}enqueue(e,t,r={}){if(e.status==="deleted")throw Error("Deleted Compose applications cannot be operated");if(r.service&&!e.manifest.spec.services[r.service])throw Error(`Compose service ${r.service} was not found`);if(t==="delete"){let i=r.removeVolumes?`${e.slug} delete volumes`:e.slug;if(r.confirmation!==i)throw Error(`Type ${i} to confirm ${r.removeVolumes?"persistent data removal":"stack deletion"}`)}if(t==="scale"&&(!r.service||!Number.isInteger(r.replicas)||r.replicas<0||r.replicas>100))throw Error("Scale requires a service and 0-100 replicas");let n=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r.actorId,kind:`compose.${t}`,idempotencyKey:`compose:${e.id}:${t}:${r.service??"stack"}:${r.replicas??""}:${e.version}`,correlationId:`compose:${e.id}`,input:{applicationId:e.id,service:r.service??null,replicas:r.replicas??null,removeVolumes:!!r.removeVolumes},lockKey:`compose:${e.id}`,providerKey:this.controlPlane.getResource(e.resourceId)?.provider??"default",buildSlot:t==="deploy"||t==="redeploy",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.applications.transition(e.id,t==="delete"?"deleting":t==="stop"?"stopped":t==="start"?"deploying":t==="scale"?e.status:"deploying",{operationId:n.id}),n}}import{createHash as rs}from"node:crypto";var ns=/^[a-f0-9]{40,64}$/i,is=/^[A-Z][A-Z0-9_]{1,127}$/;function z(e){return typeof e==="string"&&e?e:void 0}function de(e){try{return JSON.parse(String(e))}catch{return{}}}function os(e){let t=de(e);return Array.isArray(t)?t.map(String):[]}function ar(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),enabled:Number(e.enabled)===1,branchRule:z(e.branch_rule),domainPattern:String(e.domain_pattern),ttlHours:Number(e.ttl_hours),keepCount:Number(e.keep_count),publicAccess:Number(e.public_access)===1,authenticationRequired:Number(e.authentication_required)===1,allowForks:Number(e.allow_forks)===1,inheritedSecrets:os(e.inherited_secrets),resourceOverrides:de(e.resource_overrides),databaseStrategy:String(e.database_strategy),maxMonthlyCost:Number(e.max_monthly_cost),maxCpu:Number(e.max_cpu),maxMemoryMb:Number(e.max_memory_mb),cleanupOnClose:Number(e.cleanup_on_close)===1,version:Number(e.version),createdByActorId:z(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Oe(e){return{id:String(e.id),definitionId:String(e.definition_id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),identityKey:String(e.identity_key),sourceProvider:z(e.source_provider),repository:z(e.repository),branch:String(e.branch),pullRequestNumber:e.pull_request_number==null?void 0:Number(e.pull_request_number),fork:Number(e.fork)===1,commitSha:String(e.commit_sha),name:String(e.name),stackName:String(e.stack_name),url:z(e.url),status:String(e.status),expiresAt:String(e.expires_at),latestOperationId:z(e.latest_operation_id),createdByActorId:z(e.created_by_actor_id),costEstimate:e.cost_estimate==null?void 0:Number(e.cost_estimate),desiredState:de(e.desired_state),observedState:de(e.observed_state),teardownError:z(e.teardown_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),destroyedAt:z(e.destroyed_at)}}function Cn(e){return{id:String(e.id),previewId:String(e.preview_id),provider:String(e.provider),providerResourceId:String(e.provider_resource_id),kind:String(e.kind),tags:de(e.tags),observedState:de(e.observed_state),discoveredAt:String(e.discovered_at),deletedAt:z(e.deleted_at)}}function V(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,Math.floor(e))):t}function dt(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,e)):t}function dr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,28)||"preview"}class ce{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}createDefinition(e){let t=this.controlPlane.getResource(e.resourceId),r=this.controlPlane.listEnvironments(e.projectId).find((c)=>c.id===e.baseEnvironmentId);if(!t||t.projectId!==e.projectId||t.environmentId!==r?.id)throw Error("Preview resource and base environment must belong to the same project scope");if(t.kind!=="application")throw Error("Preview environments currently support application resources only");if(!/^https:\/\//.test(e.domainPattern)||!e.domainPattern.includes("{name}"))throw Error("Preview domainPattern must be HTTPS and include {name}");let n=this.getDefinitionForResource(e.resourceId),i=e.publicAccess??n?.publicAccess??!1,o=e.authenticationRequired??n?.authenticationRequired??!0;if(i&&!o)throw Error("Public preview environments require an authentication policy");let s=[...new Set(e.inheritedSecrets??[])];if(s.some((c)=>!is.test(c)))throw Error("Inherited preview secret names must use uppercase environment-variable identifiers");let a=this.now().toISOString();if(n)return this.controlPlane.database.run("UPDATE preview_definitions SET base_environment_id=?, enabled=1, branch_rule=?, domain_pattern=?, ttl_hours=?, keep_count=?, public_access=?, authentication_required=?, allow_forks=?, inherited_secrets=?, resource_overrides=?, database_strategy=?, max_monthly_cost=?, max_cpu=?, max_memory_mb=?, cleanup_on_close=?, version=version+1, updated_at=? WHERE id=?",[e.baseEnvironmentId,e.branchRule??null,e.domainPattern,V(e.ttlHours,n.ttlHours,1,720),V(e.keepCount,n.keepCount,1,100),i?1:0,o?1:0,e.allowForks??n.allowForks?1:0,JSON.stringify(e.inheritedSecrets===void 0?n.inheritedSecrets:s),JSON.stringify(I(e.resourceOverrides??n.resourceOverrides)),e.databaseStrategy??n.databaseStrategy,dt(e.maxMonthlyCost,n.maxMonthlyCost,0,1e4),dt(e.maxCpu,n.maxCpu,0.1,64),V(e.maxMemoryMb,n.maxMemoryMb,128,131072),e.cleanupOnClose??n.cleanupOnClose?1:0,a,n.id]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.updated",payload:{definitionId:n.id,baseEnvironmentId:e.baseEnvironmentId,version:n.version+1}}),this.getDefinition(n.id);let d=this.id();return this.controlPlane.database.run("INSERT INTO preview_definitions (id, project_id, resource_id, base_environment_id, enabled, branch_rule, domain_pattern, ttl_hours, keep_count, public_access, authentication_required, allow_forks, inherited_secrets, resource_overrides, database_strategy, max_monthly_cost, max_cpu, max_memory_mb, cleanup_on_close, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[d,e.projectId,e.resourceId,e.baseEnvironmentId,e.branchRule??null,e.domainPattern,V(e.ttlHours,24,1,720),V(e.keepCount,10,1,100),e.publicAccess?1:0,e.authenticationRequired===!1?0:1,e.allowForks?1:0,JSON.stringify(s),JSON.stringify(I(e.resourceOverrides??{})),e.databaseStrategy??"disabled",dt(e.maxMonthlyCost,25,0,1e4),dt(e.maxCpu,1,0.1,64),V(e.maxMemoryMb,1024,128,131072),e.cleanupOnClose===!1?0:1,e.createdByActorId??null,a,a]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.created",payload:{definitionId:d,baseEnvironmentId:e.baseEnvironmentId,ttlHours:V(e.ttlHours,24,1,720),inheritedSecretNames:s}}),this.getDefinition(d)}getDefinition(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE id=?").get(e);return t?ar(t):void 0}getDefinitionForResource(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE resource_id=?").get(e);return t?ar(t):void 0}listDefinitions(e){return this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE project_id=? ORDER BY updated_at DESC").all(e).map(ar)}listInstances(e={}){return this.controlPlane.database.query("SELECT * FROM preview_instances ORDER BY created_at DESC").all().map(Oe).filter((r)=>(!e.projectId||r.projectId===e.projectId)&&(!e.definitionId||r.definitionId===e.definitionId)&&(!e.status||r.status===e.status))}getInstance(e){let t=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE id=?").get(e);return t?Oe(t):void 0}findForPullRequest(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`pr:${t}:${r}`);return n?Oe(n):void 0}findForBranch(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`branch:${t}:${r}`);return n?Oe(n):void 0}upsert(e){let t=this.getDefinition(e.definitionId);if(!t?.enabled)throw Error("Preview environments are not enabled for this application");if(!ns.test(e.commitSha))throw Error("Preview deployment requires an immutable 40-64 character commit SHA");if(e.fork&&!t.allowForks)throw Error("Untrusted fork previews are disabled");let r=e.pullRequestNumber?`pr:${e.repository??"unknown"}:${e.pullRequestNumber}`:`branch:${e.repository??"local"}:${e.branch}`,n=rs("sha256").update(`${t.id}:${r}`).digest("hex").slice(0,8),o=`${(e.pullRequestNumber?`pr-${e.pullRequestNumber}`:dr(e.branch)).slice(0,28)}-${n}`,s=`preview-${o}`.slice(0,63),a=t.domainPattern.replaceAll("{name}",o).replaceAll("{project}",dr(t.projectId)).replaceAll("{branch}",dr(e.branch)).replaceAll("{pr}",String(e.pullRequestNumber??"branch")),d=e.now??this.now(),c=d.toISOString(),p=new Date(d.getTime()+t.ttlHours*60*60*1000).toISOString(),l=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(t.id,r);if(l){let E=Oe(l),T=E.commitSha!==e.commitSha||E.status==="destroyed";if(T)this.controlPlane.database.run("UPDATE preview_instances SET commit_sha=?, branch=?, fork=?, status='queued', expires_at=?, url=?, teardown_error=NULL, destroyed_at=NULL, version=version+1, updated_at=? WHERE id=?",[e.commitSha,e.branch,e.fork?1:0,p,a,c,E.id]);return{preview:this.getInstance(E.id),created:!1,changed:T,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}let u=this.id(),m=I({source:{provider:e.sourceProvider??null,repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:!!e.fork},policy:{databaseStrategy:t.databaseStrategy,resourceOverrides:t.resourceOverrides,maxMonthlyCost:t.maxMonthlyCost,maxCpu:t.maxCpu,maxMemoryMb:t.maxMemoryMb,publicAccess:t.publicAccess,authenticationRequired:t.authenticationRequired},inheritedSecretNames:e.fork?[]:t.inheritedSecrets});return this.controlPlane.database.run("INSERT INTO preview_instances (id, definition_id, project_id, resource_id, base_environment_id, identity_key, source_provider, repository, branch, pull_request_number, fork, commit_sha, name, stack_name, url, status, expires_at, created_by_actor_id, desired_state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?)",[u,t.id,t.projectId,t.resourceId,t.baseEnvironmentId,r,e.sourceProvider??null,e.repository??null,e.branch,e.pullRequestNumber??null,e.fork?1:0,e.commitSha,o,s,a,p,e.createdByActorId??null,JSON.stringify(m),c,c]),this.controlPlane.appendEvent({projectId:t.projectId,resourceId:t.resourceId,actorId:e.createdByActorId,type:"preview.created",payload:{previewId:u,identityKey:r,commitSha:e.commitSha,expiresAt:p,fork:!!e.fork}}),{preview:this.getInstance(u),created:!0,changed:!0,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}transition(e,t,r={}){let n=this.getInstance(e);if(!n)throw Error(`Preview ${e} was not found`);let i=this.now().toISOString(),o=t==="destroyed"?i:null;return this.controlPlane.database.run("UPDATE preview_instances SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), observed_state=?, teardown_error=?, cost_estimate=COALESCE(?, cost_estimate), destroyed_at=?, version=version+1, updated_at=? WHERE id=?",[t,r.operationId??null,JSON.stringify(I(r.observedState??n.observedState)),r.teardownError??null,r.costEstimate??null,o,i,e]),this.controlPlane.appendEvent({projectId:n.projectId,resourceId:n.resourceId,operationId:r.operationId,type:`preview.${t}`,level:t==="failed"||t==="cleanup_failed"?"error":"info",payload:{previewId:e,commitSha:n.commitSha,teardownError:r.teardownError??null}}),this.getInstance(e)}extend(e,t){let r=this.getInstance(e),n=r?this.getDefinition(r.definitionId):void 0;if(!r||!n)throw Error(`Preview ${e} was not found`);let i=this.now(),o=V(t,n.ttlHours,1,720),s=new Date(Math.max(i.getTime(),new Date(r.expiresAt).getTime())+o*3600000).toISOString();return this.controlPlane.database.run("UPDATE preview_instances SET expires_at=?, version=version+1, updated_at=? WHERE id=?",[s,i.toISOString(),e]),this.getInstance(e)}expired(e=this.now()){return this.listInstances().filter((t)=>["queued","deploying","active","updating","failed","cleanup_failed"].includes(t.status)&&new Date(t.expiresAt)<=e)}recordResource(e){let t=this.getInstance(e.previewId);if(!t)throw Error(`Preview ${e.previewId} was not found`);let r={"ts-cloud:preview":t.id,"ts-cloud:project":t.projectId,"ts-cloud:expires-at":t.expiresAt};for(let[s,a]of Object.entries(r))if(e.tags[s]!==a)throw Error(`Preview resource is missing immutable tag ${s}`);let n=this.id(),i=this.now().toISOString();this.controlPlane.database.run("INSERT INTO preview_resources (id, preview_id, provider, provider_resource_id, kind, tags, observed_state, discovered_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(preview_id, provider, provider_resource_id) DO UPDATE SET kind=excluded.kind, tags=excluded.tags, observed_state=excluded.observed_state, deleted_at=NULL",[n,t.id,e.provider,e.providerResourceId,e.kind,JSON.stringify(e.tags),JSON.stringify(I(e.observedState??{})),i]);let o=this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? AND provider=? AND provider_resource_id=?").get(t.id,e.provider,e.providerResourceId);return Cn(o)}listResources(e){return this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? ORDER BY kind, provider_resource_id").all(e).map(Cn)}markResourcesDeleted(e){if(!this.getInstance(e))throw Error(`Preview ${e} was not found`);return this.controlPlane.database.run("UPDATE preview_resources SET deleted_at=? WHERE preview_id=? AND deleted_at IS NULL",[this.now().toISOString(),e]).changes}}class ss{controlPlane;previews;queue;constructor(e){this.controlPlane=e;this.previews=new ce(e),this.queue=new H(e)}enqueueDeploy(e,t={}){let r=t.created?"preview.create":"preview.update",n=t.reason==="manual_rebuild"?`:${crypto.randomUUID()}`:"",i=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:t.actorId,kind:r,correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:${e.commitSha}${n}`,input:{previewId:e.id,reason:t.reason??(t.created?"create":"commit_update"),source:{repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:e.fork}},lockKey:`preview:${e.id}`,providerKey:"preview",buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:i.id}),i}enqueueDestroy(e,t,r){if(e.status==="destroyed")throw Error("Preview is already destroyed");let n=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:r,kind:"preview.destroy",correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:destroy:${t}`,input:{previewId:e.id,reason:t},lockKey:`preview:${e.id}`,providerKey:"preview",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:n.id}),n}cleanup(e={}){let t=e.now??new Date,r=new Map,n=this.previews.listInstances().filter((d)=>!["destroyed","destroying"].includes(d.status)),i=(d,c)=>{let p=r.get(d.id)??{preview:d,reasons:[]};if(!p.reasons.includes(c))p.reasons.push(c);r.set(d.id,p)};for(let d of n){if(new Date(d.expiresAt)<=t)i(d,"ttl_expired");if(e.maxAgeHours&&t.getTime()-new Date(d.createdAt).getTime()>=e.maxAgeHours*3600000)i(d,"max_age")}let o=new Map;for(let d of n)o.set(d.definitionId,[...o.get(d.definitionId)??[],d]);for(let[d,c]of o){let p=this.previews.getDefinition(d),l=e.keepCount??p?.keepCount;if(!l)continue;c.sort((u,m)=>m.createdAt.localeCompare(u.createdAt)).slice(l).forEach((u)=>i(u,"keep_count"))}let s=[...r.values()].sort((d,c)=>d.preview.createdAt.localeCompare(c.preview.createdAt)),a=e.dryRun?[]:s.map((d)=>this.enqueueDestroy(d.preview,d.reasons.sort().join("+"),e.actorId));if(s.length)this.controlPlane.appendEvent({actorId:e.actorId,type:e.dryRun?"preview.cleanup.planned":"preview.cleanup.queued",payload:{previewIds:s.map((d)=>d.preview.id),reasons:Object.fromEntries(s.map((d)=>[d.preview.id,d.reasons])),dryRun:!!e.dryRun}});return{candidates:s,operations:a,dryRun:!!e.dryRun}}reconcile(e){let t=[],r=[],n=[];for(let i of e){let o=i.tags["ts-cloud:preview"],s=i.tags["ts-cloud:project"],a=i.tags["ts-cloud:expires-at"];if(!o||!s||!a){n.push(i.providerResourceId);continue}let d=this.previews.getInstance(o);if(!d||d.projectId!==s||d.expiresAt!==a){r.push(i.providerResourceId);continue}if(this.previews.recordResource({...i,previewId:d.id}),i.estimatedMonthlyCost!==void 0)this.previews.transition(d.id,d.status,{costEstimate:i.estimatedMonthlyCost,observedState:{...d.observedState,lastReconciledAt:new Date().toISOString()}});t.push(i.providerResourceId)}if(r.length)this.controlPlane.appendEvent({type:"preview.reconciliation.leaks",level:"error",payload:{providerResourceIds:r}});return{matched:t,unknownPreviewResources:r,ignoredUntagged:n}}}var as=["deployment.create","deployment.rollback","application.create","deploy.source","deploy.preview","preview.create","preview.update","preview.destroy","compose.deploy","compose.redeploy","compose.start","compose.stop","compose.delete","compose.scale"];function ct(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function ds(e,t){if(!t.projectId||!t.environmentId)throw Error(`Queued ${t.kind} operation is missing its project or environment scope`);let r=e.listEnvironments(t.projectId).find((s)=>s.id===t.environmentId);if(!r)throw Error(`Environment ${t.environmentId} was not found for queued ${t.kind} operation`);let n=t.resourceId?e.getResource(t.resourceId):void 0;if(t.resourceId&&(!n||n.projectId!==t.projectId||n.environmentId!==t.environmentId))throw Error(`Resource ${t.resourceId} was not found in the queued deployment scope`);let i=ct(t.input);if(t.kind.startsWith("compose.")){let s=typeof i.applicationId==="string"?i.applicationId:void 0,a=s?new ee(e).get(s):t.resourceId?new ee(e).getByResource(t.resourceId):void 0;if(!a||a.projectId!==t.projectId||a.environmentId!==t.environmentId||a.resourceId!==t.resourceId)throw Error("Queued Compose application does not match the operation scope");let d=t.kind.slice(8),c=["compose:apply",a.id,"--action",d,"--env",r.slug];if(typeof i.service==="string"&&i.service)c.push("--service",i.service);if(typeof i.replicas==="number")c.push("--replicas",String(i.replicas));if(i.removeVolumes===!0)c.push("--remove-volumes");return{id:`queue:${t.id}`,label:`${d[0].toUpperCase()}${d.slice(1)} Compose application`,description:`${d} ${a.name}.`,command:c,mutates:!0,target:{environment:r.slug,resource:n?.slug,composeId:a.id}}}if(t.kind.startsWith("preview.")){let s=typeof i.previewId==="string"?i.previewId:void 0,a=s?new ce(e).getInstance(s):void 0;if(!a)throw Error(`Preview ${s??"(missing)"} was not found for queued ${t.kind}`);if(a.projectId!==t.projectId||a.resourceId!==t.resourceId)throw Error("Queued preview does not match the operation scope");if(t.kind==="preview.destroy")return{id:`queue:${t.id}`,label:"Destroy preview",description:`Destroy ${a.name}.`,command:["stack:delete",a.stackName,"--yes"],mutates:!0,target:{environment:r.slug,resource:n?.slug,previewId:a.id}};return{id:`queue:${t.id}`,label:t.kind==="preview.create"?"Create preview":"Update preview",description:`Deploy ${a.name} at ${a.commitSha}.`,command:["deploy","--stack",a.stackName,"--env",r.slug,"--yes","--skip-dns-verification",...n?["--site",n.slug]:[]],mutates:!0,target:{environment:r.slug,resource:n?.slug,previewId:a.id}}}if(t.kind==="deployment.rollback"){let s=["deploy:rollback"];if(n)s.push(n.slug);if(s.push("--env",r.slug),typeof i.revision==="string"&&i.revision)s.push("--to",i.revision);return{id:`queue:${t.id}`,label:"Rollback deployment",description:`Roll back ${n?.slug??r.slug}.`,command:s,mutates:!0,target:{environment:r.slug,resource:n?.slug}}}let o=["deploy","--env",r.slug,"--yes"];if(n)o.push("--site",n.slug);return{id:`queue:${t.id}`,label:t.kind==="deploy.preview"?"Deploy preview":"Deploy release",description:`Deploy ${n?.slug??r.slug}.`,command:o,mutates:!0,target:{environment:r.slug,resource:n?.slug}}}function cs(e){let t=e.stderr?.trim()||`Deployment process exited with code ${e.exitCode}`;if(/\b(?:429|rate.?limit|throttl)/i.test(t))return new J(t,"provider_throttled");if(/\b(?:502|503|504|temporar(?:y|ily)|unavailable|provider.?error)/i.test(t))return new J(t,"provider_unavailable");if(/\b(?:network|econn|enotfound|socket|timed?\s*out|fetch failed|dns)\b/i.test(t))return new J(t,"network");return Error(t)}function bc(e){let t=async(r)=>{r.checkpoint("prepare","Resolving the persisted deployment target.");let n=ds(e.store,r.operation),i=n.target.previewId?new ce(e.store):void 0,o=n.target.composeId?new ee(e.store):void 0;if(i&&n.target.previewId)i.transition(n.target.previewId,r.operation.kind==="preview.destroy"?"destroying":r.operation.kind==="preview.update"?"updating":"deploying",{operationId:r.operation.id});if(o&&n.target.composeId)o.transition(n.target.composeId,r.operation.kind==="compose.delete"?"deleting":r.operation.kind==="compose.stop"?"stopped":"deploying",{operationId:r.operation.id});r.log(`Target: ${n.target.resource??"all resources"} in ${n.target.environment}.`,{stream:"system"}),r.throwIfCancellationRequested(),r.checkpoint("execute",`Running cloud ${n.command.join(" ")}.`);let s=await e.execute(n,r);if(!s.ok){if(i&&n.target.previewId)i.transition(n.target.previewId,r.operation.kind==="preview.destroy"?"cleanup_failed":"failed",{operationId:r.operation.id,teardownError:r.operation.kind==="preview.destroy"?s.stderr?.trim()||`Process exited with ${s.exitCode}`:void 0});if(o&&n.target.composeId)o.transition(n.target.composeId,r.operation.kind==="compose.delete"?"degraded":"failed",{operationId:r.operation.id,error:s.stderr?.trim()||`Process exited with ${s.exitCode}`});throw cs(s)}if(r.throwIfCancellationRequested(),i&&n.target.previewId){let a=i.getInstance(n.target.previewId);if(r.operation.kind==="preview.destroy")i.markResourcesDeleted(a.id),i.transition(a.id,"destroyed",{operationId:r.operation.id,observedState:{reconciledResourceIds:i.listResources(a.id).map((d)=>d.providerResourceId),exactCommitSha:a.commitSha}});else{let d=e.store.getResource(a.resourceId)?.provider??"default";i.recordResource({previewId:a.id,provider:d,providerResourceId:a.stackName,kind:"stack",tags:{"ts-cloud:preview":a.id,"ts-cloud:project":a.projectId,"ts-cloud:expires-at":a.expiresAt},observedState:{command:s.command??null,exactCommitSha:a.commitSha}}),i.transition(a.id,"active",{operationId:r.operation.id,observedState:{url:a.url??null,stackName:a.stackName,exactCommitSha:a.commitSha,providerStatus:"deployed"}})}}if(o&&n.target.composeId){let a=o.get(n.target.composeId),d=typeof ct(r.operation.input).service==="string"?String(ct(r.operation.input).service):void 0,c=r.operation.kind==="compose.delete"?"deleted":r.operation.kind==="compose.stop"?"stopped":"running",p=o.transition(a.id,c,{operationId:r.operation.id,services:Object.values(a.manifest.spec.services).filter((l)=>!d||l.name===d).map((l)=>({name:l.name,status:c==="stopped"||c==="deleted"?"stopped":"running",replicas:c==="deleted"?0:l.replicas,healthyReplicas:c==="running"?l.replicas:0,observedState:{command:s.command??null,healthGatePassed:c==="running"}}))});if(c==="deleted")Rn(e.store,p,ct(r.operation.input).removeVolumes===!0)}return r.checkpoint("finalize","Deployment command completed; persisting the terminal result."),{command:s.command??`cloud ${n.command.join(" ")}`,exitCode:s.exitCode,environment:n.target.environment,resource:n.target.resource??null}};return Object.fromEntries(as.map((r)=>[r,t]))}class L extends Error{code;status;details;constructor(e,t,r,n){super(t);this.code=e;this.status=r;this.details=n}}function cr(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;if(e.resourceId&&e.resourceId!==t.resourceId)return!1;return!0}function us(e,t,r){return ls("sha256").update(`${e.toUpperCase()}
|
|
1613
|
+
`}];function bi(){return Os.map(({source:e,...t})=>({...t,source:`builtin:${t.id}`,lastVerifiedAt:Di,builtin:!0,checksum:Rs("sha256").update(e).digest("hex"),exposedServices:[...t.exposedServices],inputs:t.inputs.map((r)=>({...r}))}))}function ki(e,t){return bi().find((r)=>r.id===e&&(!t||r.version===t))}function Zt(e,t,r,s){let n=Os.find((E)=>E.id===e&&(!s||E.version===s));if(!n)throw Error(`Compose template ${e}${s?`@${s}`:""} was not found`);let i=n.source;for(let E of n.inputs){let a=t[E.name]??("default"in E?E.default:void 0);if(E.required&&!a)throw Error(`Template input ${E.name} is required`);if(a&&!/^[A-Za-z0-9._:/@+-]{1,255}$/.test(a))throw Error(`Template input ${E.name} contains unsupported characters`);i=i.replaceAll(`{{${E.name}}}`,a??"")}return se(i,r)}function vd(e,t){if(Buffer.byteLength(e)>1048576)throw Error("Compose catalog exceeds the 1 MiB limit");let r;try{r=JSON.parse(e)}catch{throw Error("Compose catalog must be valid JSON")}if(r.apiVersion!=="ts-cloud.dev/compose-catalog/v1"||!Array.isArray(r.templates))throw Error("Compose catalog must use ts-cloud.dev/compose-catalog/v1 and contain templates");let s=String(r.source??"").trim();if(!/^https:\/\//.test(s)&&!s.startsWith("file:"))throw Error("Compose catalog source must be HTTPS or an explicit file: source");let n=[],i=[];for(let[E,a]of r.templates.slice(0,100).entries()){let d=a&&typeof a==="object"&&!Array.isArray(a)?a:{},T=`templates[${E}]`,N=String(d.compose??""),o=Rs("sha256").update(N).digest("hex");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(String(d.id??""))||!/^\d+\.\d+\.\d+$/.test(String(d.version??""))){n.push({severity:"error",path:T,code:"template.identity",message:"Template id and semantic version are required."});continue}if(String(d.checksum??"")!==o){n.push({severity:"error",path:`${T}.checksum`,code:"template.checksum",message:"Template checksum does not match its Compose source."});continue}let c=se(N,{name:String(d.name??d.id),projectId:t.projectId,environmentId:t.environmentId});n.push(...c.diagnostics.map((_)=>({..._,path:`${T}.compose.${_.path}`})));let l={id:String(d.id),name:String(d.name??d.id),description:String(d.description??""),category:String(d.category??"custom"),version:String(d.version),source:s,sourceVersion:String(d.sourceVersion??d.version),architecture:String(d.architecture??Object.keys(c.manifest.spec.services).join(" + ")),minimumResources:{cpu:Math.max(0.1,Number(d.minimumResources?.cpu)||1),memoryMb:Math.max(128,Number(d.minimumResources?.memoryMb)||512)},exposedServices:Array.isArray(d.exposedServices)?d.exposedServices.map(String):[],maintenanceNotes:String(d.maintenanceNotes??""),lastVerifiedAt:String(d.lastVerifiedAt??""),inputs:[],checksum:o,builtin:!1};i.push({template:l,parsed:c})}return{valid:!n.some((E)=>E.severity==="error"),source:s,templates:i,diagnostics:n}}function yd(e,t,r,s,n,i){let E=ki(r,i);if(!E)throw Error(`Compose template ${r}@${i} was not found`);let a=Zt(r,s,n,i);return{template:E,parsed:a,templateChanges:Jt(t,a.manifest),userChanges:Jt(t,e)}}var rt=/^[a-z0-9][a-z0-9_.-]{0,62}$/;function v(e){return`'${e.replaceAll("'","'\\''")}'`}function st(e){return`${e.metadata.slug}-${e.metadata.environmentId.slice(0,8)}`.replace(/[^a-z0-9_-]/g,"-").slice(0,63)}function bd(e,t,r={}){let s=st(e),n=`/opt/ts-cloud/compose/${s}`,i=`${n}/compose.yaml`,E=`docker compose --project-name ${v(s)} --file ${v(i)}`;if(r.service&&!rt.test(r.service))throw Error("Unsafe Compose service name");if(t==="deploy"||t==="redeploy"){let a=Buffer.from(Wt(e)).toString("base64");return`install -d -m 0750 ${v(n)} && printf %s ${v(a)} | base64 --decode > ${v(i)} && chmod 0640 ${v(i)} && ${E} config --quiet && ${E} up --detach --remove-orphans --wait${t==="redeploy"?" --force-recreate":""}`}if(t==="start")return`${E} start${r.service?` ${v(r.service)}`:""}`;if(t==="stop")return`${E} stop${r.service?` ${v(r.service)}`:""}`;if(t==="status")return`${E} ps --format json`;return`${E} down --remove-orphans${r.removeVolumes?" --volumes":""}`}function kd(e,t,r){if(!rt.test(t)||!Number.isInteger(r)||r<0||r>100)throw Error("Scale requires a safe service name and 0-100 replicas");let s=st(e);return`docker compose --project-name ${v(s)} --file ${v(`/opt/ts-cloud/compose/${s}/compose.yaml`)} up --detach --wait --scale ${v(`${t}=${r}`)}`}function Fd(e,t,r=200){if(!rt.test(t))throw Error("Unsafe Compose service name");let s=st(e);return`docker compose --project-name ${v(s)} --file ${v(`/opt/ts-cloud/compose/${s}/compose.yaml`)} logs --no-color --timestamps --tail ${Math.max(1,Math.min(2000,Math.floor(r)))} ${v(t)}`}function Pd(e,t,r=["sh"]){if(!rt.test(t)||!r.length||r.some((n)=>n.includes("\x00")||n.length>1024))throw Error("Unsafe Compose shell request");let s=st(e);return`docker compose --project-name ${v(s)} --file ${v(`/opt/ts-cloud/compose/${s}/compose.yaml`)} exec ${v(t)} ${r.map(v).join(" ")}`}import{mkdir as er,readdir as qi,rm as Yi,stat as zi}from"node:fs/promises";import{basename as Gi,resolve as As,sep as Qi}from"node:path";var wt=/^[a-z0-9][a-z0-9_.-]{1,62}$/,Fi=/^0?[0-7]{3}$/,Pi=["/","/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run","/var/lib/docker","/var/lib/containers"],Hi=["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],Ki=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function xi(e){return Object.fromEntries(Hi.map((t)=>[t,{supported:!1,reason:e}]))}function nt(e,t={}){let r=xi("This storage driver does not support the operation.");for(let s of e)r[s]={supported:!0};return{...r,...t}}function Mi(e){if(!e.startsWith("/")||e.includes("\x00")||e.split("/").includes(".."))throw Error("Mount target must be an absolute normalized path without traversal.");let t=e.replace(/\/+$/,"")||"/";if(Pi.some((r)=>t===r||t.startsWith(`${r}/`)))throw Error(`Mount target ${e} is a protected host or runtime path.`)}function ji(e){if(Mi(e.targetPath),e.uid!=null&&(!Number.isInteger(e.uid)||e.uid<0))throw Error("Mount UID must be a non-negative integer.");if(e.gid!=null&&(!Number.isInteger(e.gid)||e.gid<0))throw Error("Mount GID must be a non-negative integer.");if(e.mode&&!Fi.test(e.mode))throw Error("Mount mode must be a three or four digit octal value.");if(e.propagation&&!["private","rprivate","shared","rshared","slave","rslave"].includes(e.propagation))throw Error("Unsupported mount propagation mode.")}class Bi{store;drivers;now;queue;constructor(e,t,r,s=()=>new Date){this.store=e;this.drivers=t;this.now=s;this.queue=r??new $(e.controlPlane)}driver(e,t){let r=this.drivers.find((s)=>s.provider===e&&s.type===t);if(!r)throw Error(`No ${e} ${t} volume driver is configured.`);return r}capability(e,t){let r=e.capabilities[t];if(!r?.supported)throw Error(r?.reason??`${t} is unsupported for this volume.`)}queueMutation(e,t,r,s,n){return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:n??e.resourceId,actorId:s,kind:t,idempotencyKey:`${t}:${e.id}:v${e.version}:${JSON.stringify(r)}`,correlationId:`volume:${e.id}`,input:{volumeId:e.id,...r},lockKey:n?`resource:${n}`:`volume:${e.id}`,providerKey:e.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}create(e){if(!wt.test(e.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");if(e.capacityBytes!=null&&(!Number.isSafeInteger(e.capacityBytes)||e.capacityBytes<=0))throw Error("Volume capacity must be a positive byte count.");let t=this.store.controlPlane.getProject(e.projectId),r=e.environmentId?this.store.controlPlane.listEnvironments(e.projectId).find((T)=>T.id===e.environmentId):void 0,s=e.resourceId?this.store.controlPlane.getResource(e.resourceId):void 0;if(!t||t.organizationId!==e.organizationId)throw Error("Volume project does not belong to the organization.");if(e.environmentId&&!r)throw Error("Volume environment does not belong to the project.");if(s&&(s.projectId!==e.projectId||s.environmentId!==e.environmentId||s.kind!=="volume"))throw Error("Volume resource does not belong to the selected scope.");let n=s??this.store.controlPlane.createResource({projectId:e.projectId,environmentId:e.environmentId,kind:"volume",slug:e.name,name:e.name,provider:e.provider,desiredState:{type:e.type,capacityBytes:e.capacityBytes??null,filesystem:e.filesystem??null,encrypted:!!e.encrypted}}),i=this.driver(e.provider,e.type),E=i.capabilities(),a=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,resourceId:n.id,name:e.name,provider:e.provider,type:e.type,status:"pending",capacityBytes:e.capacityBytes,filesystem:e.filesystem,encrypted:!!e.encrypted,capabilities:E,desiredState:e.desiredState??{},observedState:{}}),d=this.queueMutation(a,"volume.create",{},e.actorId);return this.store.audit({organizationId:a.organizationId,projectId:a.projectId,environmentId:a.environmentId,actorId:e.actorId,type:"volume.create.queued",volumeId:a.id,payload:{name:a.name,type:a.type}}),{volume:a,operation:d}}attach(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"attach"),ji(t);let s=this.store.controlPlane.getResource(t.resourceId);if(!s||s.projectId!==r.projectId||s.environmentId!==r.environmentId)throw Error("Cross-project or cross-environment volume attachments are forbidden.");let n=this.store.upsertAttachment({volumeId:e,resourceId:t.resourceId,targetPath:t.targetPath,readOnly:!!t.readOnly,uid:t.uid,gid:t.gid,mode:t.mode,propagation:t.propagation??"private",driverOptions:t.driverOptions??{},desiredState:"attached",observedState:"pending"}),i=this.queueMutation(r,"volume.attach",{attachmentId:n.id},t.actorId,t.resourceId);return this.store.updateAttachment(n.id,{operationId:i.id}),this.store.update(r.id,r.version,{status:"attaching"}),this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.attach.queued",volumeId:e,payload:{resourceId:t.resourceId,targetPath:t.targetPath}}),{volume:this.store.get(r.id),attachment:this.store.attachment(n.id),operation:i}}detach(e,t,r={}){let s=this.store.get(e),n=this.store.attachment(t);if(!s||!n||n.volumeId!==e)throw Error("Volume attachment was not found.");if(this.capability(s,"detach"),n.observedState==="attached"&&(!r.drained||!r.unmounted))throw Error("Detach requires completed workload drain and filesystem unmount checkpoints.");if(r.force&&r.confirmation!==`detach ${s.name}`)throw Error(`Force detach requires confirmation: detach ${s.name}`);let i=this.store.updateAttachment(t,{desiredState:"detached"}),E=this.queueMutation(s,"volume.detach",{attachmentId:t,force:!!r.force},r.actorId,n.resourceId);return this.store.updateAttachment(t,{operationId:E.id}),this.store.update(s.id,s.version,{status:"detaching"}),{volume:this.store.get(e),attachment:i,operation:E}}resize(e,t,r={}){let s=this.store.get(e);if(!s)throw Error("Volume was not found.");if(this.capability(s,"resize"),!Number.isSafeInteger(t)||t<=0)throw Error("Volume capacity must be a positive byte count.");if(s.capacityBytes!=null&&t<s.capacityBytes)throw Error("Volume shrinking is not supported because it can corrupt data.");let n=s.capabilities.resize;if(n.minimumBytes&&t<n.minimumBytes)throw Error(`Minimum supported capacity is ${n.minimumBytes} bytes.`);if(n.maximumBytes&&t>n.maximumBytes)throw Error(`Maximum supported capacity is ${n.maximumBytes} bytes.`);if(n.online===!1&&!r.drained)throw Error("This resize requires a completed workload drain checkpoint.");let i=this.store.update(e,s.version,{status:"resizing",desiredState:{...s.desiredState,capacityBytes:t}}),E=this.queueMutation(i,"volume.resize",{capacityBytes:t},r.actorId);return{volume:i,operation:E}}snapshot(e,t={}){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"snapshot");let s=this.store.createSnapshot({volumeId:e,name:t.name??`${r.name}-${this.now().toISOString().replace(/[:.]/g,"-")}`,status:"pending",encrypted:r.encrypted,metadata:{}}),n=this.store.update(e,r.version,{status:"snapshotting"}),i=this.queueMutation(n,"volume.snapshot",{snapshotId:s.id},t.actorId);return{volume:n,snapshot:s,operation:i}}restore(e,t){let r=this.store.snapshot(e),s=r?this.store.get(r.volumeId):void 0;if(!r||!s||r.status!=="available")throw Error("An available volume snapshot is required for restore.");if(this.capability(s,"restore"),!wt.test(t.name))throw Error("Restored volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let n=this.store.controlPlane.createResource({projectId:s.projectId,environmentId:s.environmentId,kind:"volume",slug:t.name,name:t.name,provider:s.provider,desiredState:{restoreFromSnapshotId:r.id}}),i=this.store.create({organizationId:s.organizationId,projectId:s.projectId,environmentId:s.environmentId,resourceId:n.id,name:t.name,provider:s.provider,type:s.type,status:"pending",capacityBytes:r.sizeBytes??s.capacityBytes,filesystem:s.filesystem,encrypted:r.encrypted,capabilities:s.capabilities,desiredState:{restoreFromSnapshotId:r.id,sourceVolumeId:s.id},observedState:{}}),E=this.queueMutation(i,"volume.restore",{snapshotId:r.id,sourceVolumeId:s.id},t.actorId);return{volume:i,snapshot:r,operation:E}}delete(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"delete");let s=this.store.attachments(e).filter((a)=>a.desiredState==="attached"||a.observedState==="attached");if(s.length)throw Error(`Detach ${s.length} active consumer(s) before deleting this volume.`);if(!t.recentAuthAt||this.now().getTime()-new Date(t.recentAuthAt).getTime()>900000)throw Error("Volume deletion requires authentication verified within the last 15 minutes.");if(t.confirmation!==r.name)throw Error(`Type ${r.name} to confirm permanent volume deletion.`);if(!(r.lastBackupAt&&this.now().getTime()-new Date(r.lastBackupAt).getTime()<=86400000)&&(!t.backupOverride||t.backupOverrideConfirmation!==`delete without backup ${r.name}`))throw Error(`A verified backup from the last 24 hours is required, or confirm: delete without backup ${r.name}`);let i=this.store.update(e,r.version,{status:"deleting"}),E=this.queueMutation(i,"volume.delete",{backupOverride:!!t.backupOverride},t.actorId);return{volume:i,operation:E}}async discover(e){let t=new Set;for(let r of this.drivers)for(let s of await r.discover(e.projectId,e.environmentId)){let n=this.store.list({projectId:e.projectId,environmentId:e.environmentId}).find((E)=>E.provider===r.provider&&E.providerId===s.providerId);if(n){t.add(n.id),this.store.update(n.id,n.version,{capacityBytes:s.capacityBytes,usedBytes:s.usedBytes,filesystem:s.filesystem,encrypted:s.encrypted??n.encrypted,observedState:s.raw??{},status:n.status==="orphaned"?"available":n.status,orphanedAt:void 0});continue}let i=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,name:`orphan-${s.providerId}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),provider:r.provider,providerId:s.providerId,type:r.type,status:"orphaned",capacityBytes:s.capacityBytes,usedBytes:s.usedBytes,filesystem:s.filesystem,encrypted:!!s.encrypted,capabilities:r.capabilities(),desiredState:{},observedState:s.raw??{},orphanedAt:this.now().toISOString()});t.add(i.id)}return this.store.list({projectId:e.projectId,environmentId:e.environmentId})}adopt(e,t){let r=this.store.get(e);if(!r||r.status!=="orphaned")throw Error("Only discovered orphan volumes can be adopted.");if(!wt.test(t.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let s=this.store.update(e,r.version,{name:t.name,status:"available",adoptedAt:this.now().toISOString(),orphanedAt:void 0});return this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.adopted",volumeId:e,payload:{providerId:r.providerId??null}}),s}}function $i(e){let t=Ki(e.input);if(typeof t.volumeId!=="string")throw Error("Queued volume operation is missing its volume identity.");return{volumeId:t.volumeId,sourceVolumeId:typeof t.sourceVolumeId==="string"?t.sourceVolumeId:void 0,attachmentId:typeof t.attachmentId==="string"?t.attachmentId:void 0,snapshotId:typeof t.snapshotId==="string"?t.snapshotId:void 0,capacityBytes:typeof t.capacityBytes==="number"?t.capacityBytes:void 0,force:t.force===!0}}function xd(e,t){let r=(n)=>{let i=t.find((E)=>E.provider===n.provider&&E.type===n.type);if(!i)throw Error(`No ${n.provider} ${n.type} volume driver is configured.`);return i},s=async(n)=>{let i=$i(n.operation),E=e.get(i.volumeId);if(!E)throw Error("Queued volume was not found.");let a=r(E);n.checkpoint("preflight","Validating persistent volume identity and capabilities."),n.throwIfCancellationRequested();let d;if(n.operation.kind==="volume.create")d=await a.create(E),e.update(E.id,E.version,{providerId:d.providerId,capacityBytes:d.capacityBytes??E.capacityBytes,usedBytes:d.usedBytes,filesystem:d.filesystem??E.filesystem,encrypted:d.encrypted??E.encrypted,observedState:d.raw??{},status:"available"});else if(n.operation.kind==="volume.attach"){let T=i.attachmentId?e.attachment(i.attachmentId):void 0;if(!T)throw Error("Queued volume attachment was not found.");await a.attach(E,T),e.updateAttachment(T.id,{observedState:"attached",lastError:void 0}),e.update(E.id,E.version,{status:"attached"})}else if(n.operation.kind==="volume.detach"){let T=i.attachmentId?e.attachment(i.attachmentId):void 0;if(!T)throw Error("Queued volume attachment was not found.");await a.detach(E,T,{force:i.force}),e.updateAttachment(T.id,{observedState:"detached",lastError:void 0});let N=e.attachments(E.id).some((o)=>o.id!==T.id&&o.observedState==="attached");e.update(E.id,E.version,{status:N?"attached":"available"})}else if(n.operation.kind==="volume.resize"){if(!i.capacityBytes)throw Error("Queued volume resize is missing its capacity.");d=await a.resize(E,i.capacityBytes),e.update(E.id,E.version,{capacityBytes:d.capacityBytes??i.capacityBytes,usedBytes:d.usedBytes??E.usedBytes,observedState:d.raw??E.observedState,status:e.attachments(E.id).some((T)=>T.observedState==="attached")?"attached":"available"})}else if(n.operation.kind==="volume.snapshot"){let T=i.snapshotId?e.snapshot(i.snapshotId):void 0;if(!T)throw Error("Queued volume snapshot was not found.");let N=await a.snapshot(E,T);e.updateSnapshot(T.id,{...N,status:"available"}),e.update(E.id,E.version,{status:e.attachments(E.id).some((o)=>o.observedState==="attached")?"attached":"available",lastBackupAt:new Date().toISOString()})}else if(n.operation.kind==="volume.restore"){let T=i.snapshotId?e.snapshot(i.snapshotId):void 0,N=i.sourceVolumeId?e.get(i.sourceVolumeId):void 0;if(!T||!N)throw Error("Queued volume restore source was not found.");d=await a.restore(N,T,E),e.update(E.id,E.version,{providerId:d.providerId,capacityBytes:d.capacityBytes??E.capacityBytes,usedBytes:d.usedBytes,filesystem:d.filesystem??E.filesystem,encrypted:d.encrypted??E.encrypted,observedState:d.raw??{},status:"available"})}else if(n.operation.kind==="volume.delete")await a.delete(E),e.update(E.id,E.version,{status:"deleted",deletedAt:new Date().toISOString()});return n.checkpoint("finalize","Persisted observed volume state."),{volumeId:E.id,status:e.get(E.id)?.status??"deleted"}};return Object.fromEntries(["volume.create","volume.attach","volume.detach","volume.resize","volume.snapshot","volume.restore","volume.delete"].map((n)=>[n,s]))}var Vi=async(e)=>{let t=Bun.spawn(["docker",...e],{stdout:"pipe",stderr:"pipe"}),[r,s,n]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);return{code:r,stdout:s,stderr:n}},ne=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;class tr{command;provider="docker";type="docker";constructor(e=Vi){this.command=e}capabilities(){return nt(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Docker named volumes do not expose a portable capacity resize operation."},snapshot:{supported:!1,reason:"Attach a volume backup policy to create verified recovery points."},restore:{supported:!1,reason:"Restore this volume from its verified backup recovery point."}})}async run(e,t=!1){let r=await this.command(e);if(r.code!==0&&!t)throw Error(`Docker volume command failed: ${r.stderr.trim()||r.code}`);return r.stdout}async inspect(e){let t=await this.run(["volume","inspect",e],!0);if(!t.trim())return;let r;try{r=JSON.parse(t)[0]}catch{return}return{providerId:String(r.Name??e),raw:{driver:String(r.Driver??"local"),mountpoint:String(r.Mountpoint??""),labels:r.Labels??{}}}}async discover(e,t){let r=await this.run(["volume","ls","--format","{{.Name}}"]),s=[];for(let n of r.split(`
|
|
1614
|
+
`).map((i)=>i.trim()).filter(ne.test.bind(ne))){let i=await this.inspect(n);if(i)s.push(i)}return s}async create(e){let t=typeof e.desiredState.nativeName==="string"?e.desiredState.nativeName:e.name;if(!ne.test(t))throw Error("Docker volume name is invalid.");return await this.run(["volume","create","--label",`ts-cloud.volume=${e.id}`,"--label",`ts-cloud.project=${e.projectId}`,t]),await this.inspect(t)??{providerId:t}}async attach(e,t){}async detach(e,t){}async resize(){throw Error(this.capabilities().resize.reason)}async snapshot(){throw Error(this.capabilities().snapshot.reason)}async restore(e,t,r){throw Error(this.capabilities().restore.reason)}async delete(e){if(!e.providerId||!ne.test(e.providerId))throw Error("Docker volume provider identity is missing or invalid.");await this.run(["volume","rm",e.providerId])}async usage(e){let t=await this.run(["system","df","-v","--format","{{json .}}"],!0),r=t.split(`
|
|
1615
|
+
`).find((s)=>s.includes(`"Name":"${e.providerId}"`));if(!r)return{};try{let s=JSON.parse(r);return{usedBytes:typeof s.Size==="number"?s.Size:void 0}}catch{return{}}}}class Wi{provider="server";type="server_path";root;constructor(e){this.root=As(e)}capabilities(){return nt(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Server paths use the capacity of their containing filesystem."},snapshot:{supported:!1,reason:"Attach a filesystem backup policy for verified recovery points."},restore:{supported:!1,reason:"Restore a filesystem recovery point into a new managed path."}})}path(e){if(!ne.test(e))throw Error("Server path volume name is invalid.");let t=As(this.root,e);if(!t.startsWith(`${this.root}${Qi}`)||Gi(t)!==e)throw Error("Server path escaped the managed volume root.");return t}async discover(e,t){return await er(this.root,{recursive:!0,mode:488}),(await qi(this.root,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&ne.test(s.name)).map((s)=>({providerId:s.name,raw:{path:this.path(s.name)}}))}async create(e){let t=typeof e.desiredState.nativeName==="string"?e.desiredState.nativeName:e.name,r=this.path(t);return await er(this.root,{recursive:!0,mode:488}),await er(r,{recursive:!1,mode:488}),{providerId:t,filesystem:"host",raw:{path:r}}}async attach(e,t){}async detach(e,t){}async resize(){throw Error(this.capabilities().resize.reason)}async snapshot(){throw Error(this.capabilities().snapshot.reason)}async restore(e,t,r){throw Error(this.capabilities().restore.reason)}async delete(e){if(!e.providerId)throw Error("Server path provider identity is unavailable.");await Yi(this.path(e.providerId),{recursive:!0,force:!1})}async usage(e){if(!e.providerId)return{};return{usedBytes:(await zi(this.path(e.providerId))).size}}}class Ji{provider;transport;type="ebs";constructor(e,t){this.provider=e;this.transport=t}capabilities(){return nt(["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],{resize:{supported:!0,online:!0,minimumBytes:1073741824}})}discover(e,t){return this.transport.list(e,t)}create(e){return this.transport.create({name:e.name,projectId:e.projectId,environmentId:e.environmentId,capacityBytes:e.capacityBytes,encrypted:e.encrypted,filesystem:e.filesystem})}resource(e,t){let r=e.resourceId===t.resourceId?e.observedState.resourceProviderId:void 0,s=typeof r==="string"?r:t.driverOptions.resourceProviderId;if(typeof s!=="string"||!s)throw Error("Cloud attachment requires a reviewed resourceProviderId driver option.");return s}attach(e,t){return this.transport.attach(e.providerId,this.resource(e,t),t.targetPath,t.readOnly)}detach(e,t,r){return this.transport.detach(e.providerId,this.resource(e,t),r.force)}resize(e,t){return this.transport.resize(e.providerId,t)}snapshot(e,t){return this.transport.snapshot(e.providerId,t.name)}restore(e,t,r){if(!t.providerId)throw Error("Cloud snapshot provider identity is unavailable.");return this.transport.restore(e.providerId,t.providerId,r.name)}delete(e){return this.transport.delete(e.providerId)}usage(e){return this.transport.usage(e.providerId)}}var b=(e)=>e==null?void 0:String(e),Ie=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},sr=(e)=>Number(e)===1,ie=(e)=>e().toISOString();function Us(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:b(e.environment_id),resourceId:b(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:b(e.provider_id),type:String(e.type),status:String(e.status),capacityBytes:e.capacity_bytes==null?void 0:Number(e.capacity_bytes),usedBytes:e.used_bytes==null?void 0:Number(e.used_bytes),filesystem:b(e.filesystem),encrypted:sr(e.encrypted),capabilities:Ie(e.capabilities,{}),desiredState:Ie(e.desired_state,{}),observedState:Ie(e.observed_state,{}),backupPolicyId:b(e.backup_policy_id),lastBackupAt:b(e.last_backup_at),orphanedAt:b(e.orphaned_at),adoptedAt:b(e.adopted_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:b(e.deleted_at)}}function rr(e){return{id:String(e.id),volumeId:String(e.volume_id),resourceId:String(e.resource_id),targetPath:String(e.target_path),readOnly:sr(e.read_only),uid:e.uid==null?void 0:Number(e.uid),gid:e.gid==null?void 0:Number(e.gid),mode:b(e.mode),propagation:String(e.propagation),driverOptions:Ie(e.driver_options,{}),desiredState:String(e.desired_state),observedState:String(e.observed_state),operationId:b(e.operation_id),lastError:b(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function hs(e){return{id:String(e.id),volumeId:String(e.volume_id),recoveryPointId:b(e.recovery_point_id),providerId:b(e.provider_id),name:String(e.name),status:String(e.status),sizeBytes:e.size_bytes==null?void 0:Number(e.size_bytes),encrypted:sr(e.encrypted),checksum:b(e.checksum),metadata:Ie(e.metadata,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:b(e.deleted_at)}}class it{controlPlane;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.controlPlane=e;this.now=t;this.id=r}get(e){let t=this.controlPlane.database.query("SELECT * FROM persistent_volumes WHERE id=?").get(e);return t?Us(t):void 0}list(e){let t=["project_id=?"],r=[e.projectId];if(e.environmentId)t.push("environment_id=?"),r.push(e.environmentId);if(!e.includeDeleted)t.push("deleted_at IS NULL");return this.controlPlane.database.query(`SELECT * FROM persistent_volumes WHERE ${t.join(" AND ")} ORDER BY name`).all(...r).map(Us)}create(e){let t=ie(this.now),r=e.id??this.id();return this.controlPlane.database.run("INSERT INTO persistent_volumes (id,organization_id,project_id,environment_id,resource_id,name,provider,provider_id,type,status,capacity_bytes,used_bytes,filesystem,encrypted,capabilities,desired_state,observed_state,backup_policy_id,last_backup_at,orphaned_at,adopted_at,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.provider,e.providerId??null,e.type,e.status,e.capacityBytes??null,e.usedBytes??null,e.filesystem??null,e.encrypted?1:0,JSON.stringify(e.capabilities),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),e.backupPolicyId??null,e.lastBackupAt??null,e.orphanedAt??null,e.adoptedAt??null,t,t,e.deletedAt??null]),this.get(r)}update(e,t,r){let s=this.get(e);if(!s||s.version!==t)throw Error("Volume changed before this operation could be applied.");let n={...s,...r,updatedAt:ie(this.now)};if(this.controlPlane.database.run("UPDATE persistent_volumes SET environment_id=?,resource_id=?,name=?,provider=?,provider_id=?,type=?,status=?,capacity_bytes=?,used_bytes=?,filesystem=?,encrypted=?,capabilities=?,desired_state=?,observed_state=?,backup_policy_id=?,last_backup_at=?,orphaned_at=?,adopted_at=?,deleted_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.environmentId??null,n.resourceId??null,n.name,n.provider,n.providerId??null,n.type,n.status,n.capacityBytes??null,n.usedBytes??null,n.filesystem??null,n.encrypted?1:0,JSON.stringify(n.capabilities),JSON.stringify(n.desiredState),JSON.stringify(n.observedState),n.backupPolicyId??null,n.lastBackupAt??null,n.orphanedAt??null,n.adoptedAt??null,n.deletedAt??null,n.updatedAt,e,t]).changes!==1)throw Error("Volume changed before this operation could be applied.");return this.get(e)}attachments(e){return this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? ORDER BY target_path").all(e).map(rr)}attachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE id=?").get(e);return t?rr(t):void 0}upsertAttachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? AND resource_id=? AND target_path=?").get(e.volumeId,e.resourceId,e.targetPath),r=ie(this.now);if(t){let n=rr(t);return this.controlPlane.database.run("UPDATE volume_attachments SET read_only=?,uid=?,gid=?,mode=?,propagation=?,driver_options=?,desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,n.id]),this.attachment(n.id)}let s=e.id??this.id();return this.controlPlane.database.run("INSERT INTO volume_attachments (id,volume_id,resource_id,target_path,read_only,uid,gid,mode,propagation,driver_options,desired_state,observed_state,operation_id,last_error,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[s,e.volumeId,e.resourceId,e.targetPath,e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,r]),this.attachment(s)}updateAttachment(e,t){let r=this.attachment(e);if(!r)throw Error("Volume attachment was not found.");let s={...r,...t};return this.controlPlane.database.run("UPDATE volume_attachments SET desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[s.desiredState,s.observedState,s.operationId??null,s.lastError??null,ie(this.now),e]),this.attachment(e)}snapshots(e){return this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE volume_id=? AND deleted_at IS NULL ORDER BY created_at DESC").all(e).map(hs)}snapshot(e){let t=this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE id=?").get(e);return t?hs(t):void 0}createSnapshot(e){let t=e.id??this.id(),r=ie(this.now);return this.controlPlane.database.run("INSERT INTO volume_snapshots (id,volume_id,recovery_point_id,provider_id,name,status,size_bytes,encrypted,checksum,metadata,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.volumeId,e.recoveryPointId??null,e.providerId??null,e.name,e.status,e.sizeBytes??null,e.encrypted?1:0,e.checksum??null,JSON.stringify(e.metadata),r,r,e.deletedAt??null]),this.snapshot(t)}updateSnapshot(e,t){let r=this.snapshot(e);if(!r)throw Error("Volume snapshot was not found.");let s={...r,...t};return this.controlPlane.database.run("UPDATE volume_snapshots SET recovery_point_id=?,provider_id=?,name=?,status=?,size_bytes=?,encrypted=?,checksum=?,metadata=?,deleted_at=?,updated_at=? WHERE id=?",[s.recoveryPointId??null,s.providerId??null,s.name,s.status,s.sizeBytes??null,s.encrypted?1:0,s.checksum??null,JSON.stringify(s.metadata),s.deletedAt??null,ie(this.now),e]),this.snapshot(e)}inventory(e,t){return this.list({projectId:e,environmentId:t}).map((r)=>{let s=this.attachments(r.id),n=this.snapshots(r.id),i=r.lastBackupAt?Date.now()-new Date(r.lastBackupAt).getTime():1/0;return{...r,attachments:s,snapshots:n,orphaned:r.status==="orphaned",usagePercent:r.capacityBytes&&r.usedBytes!=null?Math.round(r.usedBytes/r.capacityBytes*1000)/10:void 0,backupState:r.backupPolicyId?i<=86400000?"protected":"stale":"unprotected"}})}audit(e){this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:this.get(e.volumeId)?.resourceId,actorId:e.actorId,type:e.type,level:"warning",payload:{volumeId:e.volumeId,environmentId:e.environmentId??null,...e.payload}})}}function nr(e,t){let r=e.getProject(t.projectId);if(!r?.organizationId)return;let s=new it(e),n=new tr,i=new Set(t.manifest.spec.volumes),E=new Set;for(let a of i){let d=`${t.slug}-${a}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),T=s.list({projectId:t.projectId,environmentId:t.environmentId,includeDeleted:!0}).find((l)=>l.name===d);if(T?.deletedAt)throw Error(`Compose volume ${d} was permanently deleted; rename it before redeploying.`);let N=T?.resourceId?e.getResource(T.resourceId):e.createResource({projectId:t.projectId,environmentId:t.environmentId,kind:"volume",slug:d,name:d,provider:"docker",providerId:d,desiredState:{composeApplicationId:t.id,composeVolume:a}}),o=T??s.create({organizationId:r.organizationId,projectId:t.projectId,environmentId:t.environmentId,resourceId:N?.id,name:d,provider:"docker",providerId:d,type:"docker",status:"available",encrypted:!1,capabilities:n.capabilities(),desiredState:{composeApplicationId:t.id,composeVolume:a,nativeName:d},observedState:{}});E.add(o.id);let c=new Map;for(let l of Object.values(t.manifest.spec.services))for(let _ of l.volumes.filter((L)=>L.source===a)){let L=c.get(_.target)??[];L.push(l.name),c.set(_.target,L),s.upsertAttachment({volumeId:o.id,resourceId:t.resourceId,targetPath:_.target,readOnly:_.readOnly,propagation:"private",driverOptions:{composeServices:L},desiredState:"attached",observedState:"pending"})}}for(let a of s.list({projectId:t.projectId,environmentId:t.environmentId}).filter((d)=>d.desiredState.composeApplicationId===t.id&&!E.has(d.id)))for(let d of s.attachments(a.id))s.updateAttachment(d.id,{desiredState:"detached"})}function fs(e,t,r){let s=new it(e);for(let n of s.list({projectId:t.projectId,environmentId:t.environmentId}).filter((i)=>i.desiredState.composeApplicationId===t.id)){for(let i of s.attachments(n.id))s.updateAttachment(i.id,{desiredState:"detached",observedState:"detached"});s.update(n.id,n.version,{status:r?"deleted":"available",deletedAt:r?new Date().toISOString():void 0})}}function Ee(e){return typeof e==="string"&&e?e:void 0}function ir(e,t){try{return JSON.parse(String(e))}catch{return t}}function Et(e){return{id:String(e.id),resourceId:String(e.resource_id),projectId:String(e.project_id),environmentId:String(e.environment_id),name:String(e.name),slug:String(e.slug),status:String(e.status),sourceKind:String(e.source_kind),sourceHash:String(e.source_hash),redactedSource:String(e.redacted_source),manifest:ir(e.manifest,{}),diagnostics:ir(e.diagnostics,[]),templateId:Ee(e.template_id),templateVersion:Ee(e.template_version),latestOperationId:Ee(e.latest_operation_id),createdByActorId:Ee(e.created_by_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:Ee(e.deleted_at)}}function Zi(e){return{applicationId:String(e.application_id),serviceName:String(e.service_name),status:String(e.status),replicas:Number(e.replicas),healthyReplicas:Number(e.healthy_replicas),latestOperationId:Ee(e.latest_operation_id),observedState:ir(e.observed_state,{}),updatedAt:String(e.updated_at)}}class w{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}persist(e,t){if(!e.valid)throw Error(`Compose definition contains ${e.diagnostics.filter((_)=>_.severity==="error").length} blocking diagnostic(s)`);let{projectId:r,environmentId:s,name:n,slug:i}=e.manifest.metadata;if(!this.controlPlane.listEnvironments(r).find((_)=>_.id===s))throw Error("Compose project and environment scope was not found");let a=this.getBySlug(r,s,i),d=this.now().toISOString(),T=JSON.stringify(e.manifest),N=JSON.stringify(h(e.diagnostics));if(a){if(a.status==="deleted")throw Error("A deleted Compose application cannot be overwritten; choose another slug");let _=this.controlPlane.getResource(a.resourceId);if(!_)throw Error("Compose application resource was not found");this.controlPlane.updateResource(_.id,_.version,{name:n,provider:_.provider,providerId:_.providerId,desiredState:e.manifest,discoveredState:_.discoveredState,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),this.controlPlane.database.run("UPDATE compose_applications SET name=?, status='ready', source_kind=?, source_hash=?, redacted_source=?, manifest=?, diagnostics=?, template_id=?, template_version=?, version=version+1, updated_at=? WHERE id=?",[n,t.sourceKind,e.sourceHash,e.redactedSource,T,N,t.templateId??null,t.templateVersion??null,d,a.id]);let L=Object.keys(e.manifest.spec.services);if(L.length)this.controlPlane.database.run(`DELETE FROM compose_service_states WHERE application_id=? AND service_name NOT IN (${L.map(()=>"?").join(",")})`,[a.id,...L]);for(let C of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?) ON CONFLICT(application_id, service_name) DO UPDATE SET replicas=excluded.replicas, updated_at=excluded.updated_at",[a.id,C.name,C.replicas,d]);this.controlPlane.appendEvent({projectId:r,resourceId:a.resourceId,actorId:t.createdByActorId,type:"compose.application.updated",payload:{applicationId:a.id,sourceHash:e.sourceHash,diagnosticCount:e.diagnostics.length,templateId:t.templateId??null,templateVersion:t.templateVersion??null}});let u=this.get(a.id);return nr(this.controlPlane,u),u}let o=this.controlPlane.createResource({projectId:r,environmentId:s,kind:"compose_application",slug:i,name:n,desiredState:e.manifest,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),c=this.id();this.controlPlane.database.run("INSERT INTO compose_applications (id, resource_id, project_id, environment_id, name, slug, status, source_kind, source_hash, redacted_source, manifest, diagnostics, template_id, template_version, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'ready', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[c,o.id,r,s,n,i,t.sourceKind,e.sourceHash,e.redactedSource,T,N,t.templateId??null,t.templateVersion??null,t.createdByActorId??null,d,d]);for(let _ of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?)",[c,_.name,_.replicas,d]);this.controlPlane.appendEvent({projectId:r,resourceId:o.id,actorId:t.createdByActorId,type:"compose.application.created",payload:{applicationId:c,sourceHash:e.sourceHash,serviceNames:Object.keys(e.manifest.spec.services),templateId:t.templateId??null}});let l=this.get(c);return nr(this.controlPlane,l),l}import(e,t){let r=se(e,t);return{application:this.persist(r,{sourceKind:"compose",createdByActorId:t.createdByActorId}),parsed:r}}fromTemplate(e,t,r){let s=Zt(e,t,r,r.version);return{application:this.persist(s,{sourceKind:"template",templateId:e,templateVersion:r.version??"1.0.0",createdByActorId:r.createdByActorId}),parsed:s}}preview(e,t){return se(e,t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE id=?").get(e);return t?Et(t):void 0}getByResource(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE resource_id=?").get(e);return t?Et(t):void 0}getBySlug(e,t,r){let s=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE project_id=? AND environment_id=? AND slug=?").get(e,t,r);return s?Et(s):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM compose_applications ORDER BY updated_at DESC").all().map(Et).filter((t)=>(!e.projectId||t.projectId===e.projectId)&&(!e.environmentId||t.environmentId===e.environmentId)&&(e.includeDeleted||t.status!=="deleted"))}services(e){return this.controlPlane.database.query("SELECT * FROM compose_service_states WHERE application_id=? ORDER BY service_name").all(e).map(Zi)}transition(e,t,r={}){let s=this.get(e);if(!s)throw Error(`Compose application ${e} was not found`);let n=this.now().toISOString(),i=t==="deleted"?n:null;this.controlPlane.database.run("UPDATE compose_applications SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), version=version+1, updated_at=?, deleted_at=? WHERE id=?",[t,r.operationId??null,n,i,e]);for(let E of r.services??[])if(s.manifest.spec.services[E.name])this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, latest_operation_id, observed_state, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(application_id, service_name) DO UPDATE SET status=excluded.status, replicas=excluded.replicas, healthy_replicas=excluded.healthy_replicas, latest_operation_id=excluded.latest_operation_id, observed_state=excluded.observed_state, updated_at=excluded.updated_at",[e,E.name,E.status,E.replicas??s.manifest.spec.services[E.name].replicas,E.healthyReplicas??0,r.operationId??null,JSON.stringify(h(E.observedState??{})),n]);return this.controlPlane.appendEvent({projectId:s.projectId,resourceId:s.resourceId,operationId:r.operationId,type:`compose.application.${t}`,level:t==="failed"||t==="degraded"?"error":"info",payload:{applicationId:e,error:r.error??null}}),this.get(e)}}class wi{controlPlane;applications;queue;constructor(e){this.controlPlane=e;this.applications=new w(e),this.queue=new $(e)}enqueue(e,t,r={}){if(e.status==="deleted")throw Error("Deleted Compose applications cannot be operated");if(r.service&&!e.manifest.spec.services[r.service])throw Error(`Compose service ${r.service} was not found`);if(t==="delete"){let n=r.removeVolumes?`${e.slug} delete volumes`:e.slug;if(r.confirmation!==n)throw Error(`Type ${n} to confirm ${r.removeVolumes?"persistent data removal":"stack deletion"}`)}if(t==="scale"&&(!r.service||!Number.isInteger(r.replicas)||r.replicas<0||r.replicas>100))throw Error("Scale requires a service and 0-100 replicas");let s=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r.actorId,kind:`compose.${t}`,idempotencyKey:`compose:${e.id}:${t}:${r.service??"stack"}:${r.replicas??""}:${e.version}`,correlationId:`compose:${e.id}`,input:{applicationId:e.id,service:r.service??null,replicas:r.replicas??null,removeVolumes:!!r.removeVolumes},lockKey:`compose:${e.id}`,providerKey:this.controlPlane.getResource(e.resourceId)?.provider??"default",buildSlot:t==="deploy"||t==="redeploy",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.applications.transition(e.id,t==="delete"?"deleting":t==="stop"?"stopped":t==="start"?"deploying":t==="scale"?e.status:"deploying",{operationId:s.id}),s}}import{createHash as eE}from"node:crypto";var tE=/^[a-f0-9]{40,64}$/i,rE=/^[A-Z][A-Z0-9_]{1,127}$/;function j(e){return typeof e==="string"&&e?e:void 0}function ae(e){try{return JSON.parse(String(e))}catch{return{}}}function sE(e){let t=ae(e);return Array.isArray(t)?t.map(String):[]}function Er(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),enabled:Number(e.enabled)===1,branchRule:j(e.branch_rule),domainPattern:String(e.domain_pattern),ttlHours:Number(e.ttl_hours),keepCount:Number(e.keep_count),publicAccess:Number(e.public_access)===1,authenticationRequired:Number(e.authentication_required)===1,allowForks:Number(e.allow_forks)===1,inheritedSecrets:sE(e.inherited_secrets),resourceOverrides:ae(e.resource_overrides),databaseStrategy:String(e.database_strategy),maxMonthlyCost:Number(e.max_monthly_cost),maxCpu:Number(e.max_cpu),maxMemoryMb:Number(e.max_memory_mb),cleanupOnClose:Number(e.cleanup_on_close)===1,version:Number(e.version),createdByActorId:j(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ve(e){return{id:String(e.id),definitionId:String(e.definition_id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),identityKey:String(e.identity_key),sourceProvider:j(e.source_provider),repository:j(e.repository),branch:String(e.branch),pullRequestNumber:e.pull_request_number==null?void 0:Number(e.pull_request_number),fork:Number(e.fork)===1,commitSha:String(e.commit_sha),name:String(e.name),stackName:String(e.stack_name),url:j(e.url),status:String(e.status),expiresAt:String(e.expires_at),latestOperationId:j(e.latest_operation_id),createdByActorId:j(e.created_by_actor_id),costEstimate:e.cost_estimate==null?void 0:Number(e.cost_estimate),desiredState:ae(e.desired_state),observedState:ae(e.observed_state),teardownError:j(e.teardown_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),destroyedAt:j(e.destroyed_at)}}function Ss(e){return{id:String(e.id),previewId:String(e.preview_id),provider:String(e.provider),providerResourceId:String(e.provider_resource_id),kind:String(e.kind),tags:ae(e.tags),observedState:ae(e.observed_state),discoveredAt:String(e.discovered_at),deletedAt:j(e.deleted_at)}}function Y(e,t,r,s){return Number.isFinite(e)?Math.min(s,Math.max(r,Math.floor(e))):t}function at(e,t,r,s){return Number.isFinite(e)?Math.min(s,Math.max(r,e)):t}function ar(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,28)||"preview"}class de{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}createDefinition(e){let t=this.controlPlane.getResource(e.resourceId),r=this.controlPlane.listEnvironments(e.projectId).find((T)=>T.id===e.baseEnvironmentId);if(!t||t.projectId!==e.projectId||t.environmentId!==r?.id)throw Error("Preview resource and base environment must belong to the same project scope");if(t.kind!=="application")throw Error("Preview environments currently support application resources only");if(!/^https:\/\//.test(e.domainPattern)||!e.domainPattern.includes("{name}"))throw Error("Preview domainPattern must be HTTPS and include {name}");let s=this.getDefinitionForResource(e.resourceId),n=e.publicAccess??s?.publicAccess??!1,i=e.authenticationRequired??s?.authenticationRequired??!0;if(n&&!i)throw Error("Public preview environments require an authentication policy");let E=[...new Set(e.inheritedSecrets??[])];if(E.some((T)=>!rE.test(T)))throw Error("Inherited preview secret names must use uppercase environment-variable identifiers");let a=this.now().toISOString();if(s)return this.controlPlane.database.run("UPDATE preview_definitions SET base_environment_id=?, enabled=1, branch_rule=?, domain_pattern=?, ttl_hours=?, keep_count=?, public_access=?, authentication_required=?, allow_forks=?, inherited_secrets=?, resource_overrides=?, database_strategy=?, max_monthly_cost=?, max_cpu=?, max_memory_mb=?, cleanup_on_close=?, version=version+1, updated_at=? WHERE id=?",[e.baseEnvironmentId,e.branchRule??null,e.domainPattern,Y(e.ttlHours,s.ttlHours,1,720),Y(e.keepCount,s.keepCount,1,100),n?1:0,i?1:0,e.allowForks??s.allowForks?1:0,JSON.stringify(e.inheritedSecrets===void 0?s.inheritedSecrets:E),JSON.stringify(h(e.resourceOverrides??s.resourceOverrides)),e.databaseStrategy??s.databaseStrategy,at(e.maxMonthlyCost,s.maxMonthlyCost,0,1e4),at(e.maxCpu,s.maxCpu,0.1,64),Y(e.maxMemoryMb,s.maxMemoryMb,128,131072),e.cleanupOnClose??s.cleanupOnClose?1:0,a,s.id]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.updated",payload:{definitionId:s.id,baseEnvironmentId:e.baseEnvironmentId,version:s.version+1}}),this.getDefinition(s.id);let d=this.id();return this.controlPlane.database.run("INSERT INTO preview_definitions (id, project_id, resource_id, base_environment_id, enabled, branch_rule, domain_pattern, ttl_hours, keep_count, public_access, authentication_required, allow_forks, inherited_secrets, resource_overrides, database_strategy, max_monthly_cost, max_cpu, max_memory_mb, cleanup_on_close, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[d,e.projectId,e.resourceId,e.baseEnvironmentId,e.branchRule??null,e.domainPattern,Y(e.ttlHours,24,1,720),Y(e.keepCount,10,1,100),e.publicAccess?1:0,e.authenticationRequired===!1?0:1,e.allowForks?1:0,JSON.stringify(E),JSON.stringify(h(e.resourceOverrides??{})),e.databaseStrategy??"disabled",at(e.maxMonthlyCost,25,0,1e4),at(e.maxCpu,1,0.1,64),Y(e.maxMemoryMb,1024,128,131072),e.cleanupOnClose===!1?0:1,e.createdByActorId??null,a,a]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.created",payload:{definitionId:d,baseEnvironmentId:e.baseEnvironmentId,ttlHours:Y(e.ttlHours,24,1,720),inheritedSecretNames:E}}),this.getDefinition(d)}getDefinition(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE id=?").get(e);return t?Er(t):void 0}getDefinitionForResource(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE resource_id=?").get(e);return t?Er(t):void 0}listDefinitions(e){return this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE project_id=? ORDER BY updated_at DESC").all(e).map(Er)}listInstances(e={}){return this.controlPlane.database.query("SELECT * FROM preview_instances ORDER BY created_at DESC").all().map(ve).filter((r)=>(!e.projectId||r.projectId===e.projectId)&&(!e.definitionId||r.definitionId===e.definitionId)&&(!e.status||r.status===e.status))}getInstance(e){let t=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE id=?").get(e);return t?ve(t):void 0}findForPullRequest(e,t,r){let s=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`pr:${t}:${r}`);return s?ve(s):void 0}findForBranch(e,t,r){let s=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`branch:${t}:${r}`);return s?ve(s):void 0}upsert(e){let t=this.getDefinition(e.definitionId);if(!t?.enabled)throw Error("Preview environments are not enabled for this application");if(!tE.test(e.commitSha))throw Error("Preview deployment requires an immutable 40-64 character commit SHA");if(e.fork&&!t.allowForks)throw Error("Untrusted fork previews are disabled");let r=e.pullRequestNumber?`pr:${e.repository??"unknown"}:${e.pullRequestNumber}`:`branch:${e.repository??"local"}:${e.branch}`,s=eE("sha256").update(`${t.id}:${r}`).digest("hex").slice(0,8),i=`${(e.pullRequestNumber?`pr-${e.pullRequestNumber}`:ar(e.branch)).slice(0,28)}-${s}`,E=`preview-${i}`.slice(0,63),a=t.domainPattern.replaceAll("{name}",i).replaceAll("{project}",ar(t.projectId)).replaceAll("{branch}",ar(e.branch)).replaceAll("{pr}",String(e.pullRequestNumber??"branch")),d=e.now??this.now(),T=d.toISOString(),N=new Date(d.getTime()+t.ttlHours*60*60*1000).toISOString(),o=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(t.id,r);if(o){let _=ve(o),L=_.commitSha!==e.commitSha||_.status==="destroyed";if(L)this.controlPlane.database.run("UPDATE preview_instances SET commit_sha=?, branch=?, fork=?, status='queued', expires_at=?, url=?, teardown_error=NULL, destroyed_at=NULL, version=version+1, updated_at=? WHERE id=?",[e.commitSha,e.branch,e.fork?1:0,N,a,T,_.id]);return{preview:this.getInstance(_.id),created:!1,changed:L,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}let c=this.id(),l=h({source:{provider:e.sourceProvider??null,repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:!!e.fork},policy:{databaseStrategy:t.databaseStrategy,resourceOverrides:t.resourceOverrides,maxMonthlyCost:t.maxMonthlyCost,maxCpu:t.maxCpu,maxMemoryMb:t.maxMemoryMb,publicAccess:t.publicAccess,authenticationRequired:t.authenticationRequired},inheritedSecretNames:e.fork?[]:t.inheritedSecrets});return this.controlPlane.database.run("INSERT INTO preview_instances (id, definition_id, project_id, resource_id, base_environment_id, identity_key, source_provider, repository, branch, pull_request_number, fork, commit_sha, name, stack_name, url, status, expires_at, created_by_actor_id, desired_state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?)",[c,t.id,t.projectId,t.resourceId,t.baseEnvironmentId,r,e.sourceProvider??null,e.repository??null,e.branch,e.pullRequestNumber??null,e.fork?1:0,e.commitSha,i,E,a,N,e.createdByActorId??null,JSON.stringify(l),T,T]),this.controlPlane.appendEvent({projectId:t.projectId,resourceId:t.resourceId,actorId:e.createdByActorId,type:"preview.created",payload:{previewId:c,identityKey:r,commitSha:e.commitSha,expiresAt:N,fork:!!e.fork}}),{preview:this.getInstance(c),created:!0,changed:!0,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}transition(e,t,r={}){let s=this.getInstance(e);if(!s)throw Error(`Preview ${e} was not found`);let n=this.now().toISOString(),i=t==="destroyed"?n:null;return this.controlPlane.database.run("UPDATE preview_instances SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), observed_state=?, teardown_error=?, cost_estimate=COALESCE(?, cost_estimate), destroyed_at=?, version=version+1, updated_at=? WHERE id=?",[t,r.operationId??null,JSON.stringify(h(r.observedState??s.observedState)),r.teardownError??null,r.costEstimate??null,i,n,e]),this.controlPlane.appendEvent({projectId:s.projectId,resourceId:s.resourceId,operationId:r.operationId,type:`preview.${t}`,level:t==="failed"||t==="cleanup_failed"?"error":"info",payload:{previewId:e,commitSha:s.commitSha,teardownError:r.teardownError??null}}),this.getInstance(e)}extend(e,t){let r=this.getInstance(e),s=r?this.getDefinition(r.definitionId):void 0;if(!r||!s)throw Error(`Preview ${e} was not found`);let n=this.now(),i=Y(t,s.ttlHours,1,720),E=new Date(Math.max(n.getTime(),new Date(r.expiresAt).getTime())+i*3600000).toISOString();return this.controlPlane.database.run("UPDATE preview_instances SET expires_at=?, version=version+1, updated_at=? WHERE id=?",[E,n.toISOString(),e]),this.getInstance(e)}expired(e=this.now()){return this.listInstances().filter((t)=>["queued","deploying","active","updating","failed","cleanup_failed"].includes(t.status)&&new Date(t.expiresAt)<=e)}recordResource(e){let t=this.getInstance(e.previewId);if(!t)throw Error(`Preview ${e.previewId} was not found`);let r={"ts-cloud:preview":t.id,"ts-cloud:project":t.projectId,"ts-cloud:expires-at":t.expiresAt};for(let[E,a]of Object.entries(r))if(e.tags[E]!==a)throw Error(`Preview resource is missing immutable tag ${E}`);let s=this.id(),n=this.now().toISOString();this.controlPlane.database.run("INSERT INTO preview_resources (id, preview_id, provider, provider_resource_id, kind, tags, observed_state, discovered_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(preview_id, provider, provider_resource_id) DO UPDATE SET kind=excluded.kind, tags=excluded.tags, observed_state=excluded.observed_state, deleted_at=NULL",[s,t.id,e.provider,e.providerResourceId,e.kind,JSON.stringify(e.tags),JSON.stringify(h(e.observedState??{})),n]);let i=this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? AND provider=? AND provider_resource_id=?").get(t.id,e.provider,e.providerResourceId);return Ss(i)}listResources(e){return this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? ORDER BY kind, provider_resource_id").all(e).map(Ss)}markResourcesDeleted(e){if(!this.getInstance(e))throw Error(`Preview ${e} was not found`);return this.controlPlane.database.run("UPDATE preview_resources SET deleted_at=? WHERE preview_id=? AND deleted_at IS NULL",[this.now().toISOString(),e]).changes}}class nE{controlPlane;previews;queue;constructor(e){this.controlPlane=e;this.previews=new de(e),this.queue=new $(e)}enqueueDeploy(e,t={}){let r=t.created?"preview.create":"preview.update",s=t.reason==="manual_rebuild"?`:${crypto.randomUUID()}`:"",n=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:t.actorId,kind:r,correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:${e.commitSha}${s}`,input:{previewId:e.id,reason:t.reason??(t.created?"create":"commit_update"),source:{repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:e.fork}},lockKey:`preview:${e.id}`,providerKey:"preview",buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:n.id}),n}enqueueDestroy(e,t,r){if(e.status==="destroyed")throw Error("Preview is already destroyed");let s=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:r,kind:"preview.destroy",correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:destroy:${t}`,input:{previewId:e.id,reason:t},lockKey:`preview:${e.id}`,providerKey:"preview",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:s.id}),s}cleanup(e={}){let t=e.now??new Date,r=new Map,s=this.previews.listInstances().filter((d)=>!["destroyed","destroying"].includes(d.status)),n=(d,T)=>{let N=r.get(d.id)??{preview:d,reasons:[]};if(!N.reasons.includes(T))N.reasons.push(T);r.set(d.id,N)};for(let d of s){if(new Date(d.expiresAt)<=t)n(d,"ttl_expired");if(e.maxAgeHours&&t.getTime()-new Date(d.createdAt).getTime()>=e.maxAgeHours*3600000)n(d,"max_age")}let i=new Map;for(let d of s)i.set(d.definitionId,[...i.get(d.definitionId)??[],d]);for(let[d,T]of i){let N=this.previews.getDefinition(d),o=e.keepCount??N?.keepCount;if(!o)continue;T.sort((c,l)=>l.createdAt.localeCompare(c.createdAt)).slice(o).forEach((c)=>n(c,"keep_count"))}let E=[...r.values()].sort((d,T)=>d.preview.createdAt.localeCompare(T.preview.createdAt)),a=e.dryRun?[]:E.map((d)=>this.enqueueDestroy(d.preview,d.reasons.sort().join("+"),e.actorId));if(E.length)this.controlPlane.appendEvent({actorId:e.actorId,type:e.dryRun?"preview.cleanup.planned":"preview.cleanup.queued",payload:{previewIds:E.map((d)=>d.preview.id),reasons:Object.fromEntries(E.map((d)=>[d.preview.id,d.reasons])),dryRun:!!e.dryRun}});return{candidates:E,operations:a,dryRun:!!e.dryRun}}reconcile(e){let t=[],r=[],s=[];for(let n of e){let i=n.tags["ts-cloud:preview"],E=n.tags["ts-cloud:project"],a=n.tags["ts-cloud:expires-at"];if(!i||!E||!a){s.push(n.providerResourceId);continue}let d=this.previews.getInstance(i);if(!d||d.projectId!==E||d.expiresAt!==a){r.push(n.providerResourceId);continue}if(this.previews.recordResource({...n,previewId:d.id}),n.estimatedMonthlyCost!==void 0)this.previews.transition(d.id,d.status,{costEstimate:n.estimatedMonthlyCost,observedState:{...d.observedState,lastReconciledAt:new Date().toISOString()}});t.push(n.providerResourceId)}if(r.length)this.controlPlane.appendEvent({type:"preview.reconciliation.leaks",level:"error",payload:{providerResourceIds:r}});return{matched:t,unknownPreviewResources:r,ignoredUntagged:s}}}var iE=["deployment.create","deployment.rollback","application.create","deploy.source","deploy.preview","preview.create","preview.update","preview.destroy","compose.deploy","compose.redeploy","compose.start","compose.stop","compose.delete","compose.scale"];function dt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function EE(e,t){if(!t.projectId||!t.environmentId)throw Error(`Queued ${t.kind} operation is missing its project or environment scope`);let r=e.listEnvironments(t.projectId).find((E)=>E.id===t.environmentId);if(!r)throw Error(`Environment ${t.environmentId} was not found for queued ${t.kind} operation`);let s=t.resourceId?e.getResource(t.resourceId):void 0;if(t.resourceId&&(!s||s.projectId!==t.projectId||s.environmentId!==t.environmentId))throw Error(`Resource ${t.resourceId} was not found in the queued deployment scope`);let n=dt(t.input);if(t.kind.startsWith("compose.")){let E=typeof n.applicationId==="string"?n.applicationId:void 0,a=E?new w(e).get(E):t.resourceId?new w(e).getByResource(t.resourceId):void 0;if(!a||a.projectId!==t.projectId||a.environmentId!==t.environmentId||a.resourceId!==t.resourceId)throw Error("Queued Compose application does not match the operation scope");let d=t.kind.slice(8),T=["compose:apply",a.id,"--action",d,"--env",r.slug];if(typeof n.service==="string"&&n.service)T.push("--service",n.service);if(typeof n.replicas==="number")T.push("--replicas",String(n.replicas));if(n.removeVolumes===!0)T.push("--remove-volumes");return{id:`queue:${t.id}`,label:`${d[0].toUpperCase()}${d.slice(1)} Compose application`,description:`${d} ${a.name}.`,command:T,mutates:!0,target:{environment:r.slug,resource:s?.slug,composeId:a.id}}}if(t.kind.startsWith("preview.")){let E=typeof n.previewId==="string"?n.previewId:void 0,a=E?new de(e).getInstance(E):void 0;if(!a)throw Error(`Preview ${E??"(missing)"} was not found for queued ${t.kind}`);if(a.projectId!==t.projectId||a.resourceId!==t.resourceId)throw Error("Queued preview does not match the operation scope");if(t.kind==="preview.destroy")return{id:`queue:${t.id}`,label:"Destroy preview",description:`Destroy ${a.name}.`,command:["stack:delete",a.stackName,"--yes"],mutates:!0,target:{environment:r.slug,resource:s?.slug,previewId:a.id}};return{id:`queue:${t.id}`,label:t.kind==="preview.create"?"Create preview":"Update preview",description:`Deploy ${a.name} at ${a.commitSha}.`,command:["deploy","--stack",a.stackName,"--env",r.slug,"--yes","--skip-dns-verification",...s?["--site",s.slug]:[]],mutates:!0,target:{environment:r.slug,resource:s?.slug,previewId:a.id}}}if(t.kind==="deployment.rollback"){let E=["deploy:rollback"];if(s)E.push(s.slug);if(E.push("--env",r.slug),typeof n.revision==="string"&&n.revision)E.push("--to",n.revision);return{id:`queue:${t.id}`,label:"Rollback deployment",description:`Roll back ${s?.slug??r.slug}.`,command:E,mutates:!0,target:{environment:r.slug,resource:s?.slug}}}let i=["deploy","--env",r.slug,"--yes"];if(s)i.push("--site",s.slug);return{id:`queue:${t.id}`,label:t.kind==="deploy.preview"?"Deploy preview":"Deploy release",description:`Deploy ${s?.slug??r.slug}.`,command:i,mutates:!0,target:{environment:r.slug,resource:s?.slug}}}function aE(e){let t=e.stderr?.trim()||`Deployment process exited with code ${e.exitCode}`;if(/\b(?:429|rate.?limit|throttl)/i.test(t))return new J(t,"provider_throttled");if(/\b(?:502|503|504|temporar(?:y|ily)|unavailable|provider.?error)/i.test(t))return new J(t,"provider_unavailable");if(/\b(?:network|econn|enotfound|socket|timed?\s*out|fetch failed|dns)\b/i.test(t))return new J(t,"network");return Error(t)}function hT(e){let t=async(r)=>{r.checkpoint("prepare","Resolving the persisted deployment target.");let s=EE(e.store,r.operation),n=s.target.previewId?new de(e.store):void 0,i=s.target.composeId?new w(e.store):void 0;if(n&&s.target.previewId)n.transition(s.target.previewId,r.operation.kind==="preview.destroy"?"destroying":r.operation.kind==="preview.update"?"updating":"deploying",{operationId:r.operation.id});if(i&&s.target.composeId)i.transition(s.target.composeId,r.operation.kind==="compose.delete"?"deleting":r.operation.kind==="compose.stop"?"stopped":"deploying",{operationId:r.operation.id});r.log(`Target: ${s.target.resource??"all resources"} in ${s.target.environment}.`,{stream:"system"}),r.throwIfCancellationRequested(),r.checkpoint("execute",`Running cloud ${s.command.join(" ")}.`);let E=await e.execute(s,r);if(!E.ok){if(n&&s.target.previewId)n.transition(s.target.previewId,r.operation.kind==="preview.destroy"?"cleanup_failed":"failed",{operationId:r.operation.id,teardownError:r.operation.kind==="preview.destroy"?E.stderr?.trim()||`Process exited with ${E.exitCode}`:void 0});if(i&&s.target.composeId)i.transition(s.target.composeId,r.operation.kind==="compose.delete"?"degraded":"failed",{operationId:r.operation.id,error:E.stderr?.trim()||`Process exited with ${E.exitCode}`});throw aE(E)}if(r.throwIfCancellationRequested(),n&&s.target.previewId){let a=n.getInstance(s.target.previewId);if(r.operation.kind==="preview.destroy")n.markResourcesDeleted(a.id),n.transition(a.id,"destroyed",{operationId:r.operation.id,observedState:{reconciledResourceIds:n.listResources(a.id).map((d)=>d.providerResourceId),exactCommitSha:a.commitSha}});else{let d=e.store.getResource(a.resourceId)?.provider??"default";n.recordResource({previewId:a.id,provider:d,providerResourceId:a.stackName,kind:"stack",tags:{"ts-cloud:preview":a.id,"ts-cloud:project":a.projectId,"ts-cloud:expires-at":a.expiresAt},observedState:{command:E.command??null,exactCommitSha:a.commitSha}}),n.transition(a.id,"active",{operationId:r.operation.id,observedState:{url:a.url??null,stackName:a.stackName,exactCommitSha:a.commitSha,providerStatus:"deployed"}})}}if(i&&s.target.composeId){let a=i.get(s.target.composeId),d=typeof dt(r.operation.input).service==="string"?String(dt(r.operation.input).service):void 0,T=r.operation.kind==="compose.delete"?"deleted":r.operation.kind==="compose.stop"?"stopped":"running",N=i.transition(a.id,T,{operationId:r.operation.id,services:Object.values(a.manifest.spec.services).filter((o)=>!d||o.name===d).map((o)=>({name:o.name,status:T==="stopped"||T==="deleted"?"stopped":"running",replicas:T==="deleted"?0:o.replicas,healthyReplicas:T==="running"?o.replicas:0,observedState:{command:E.command??null,healthGatePassed:T==="running"}}))});if(T==="deleted")fs(e.store,N,dt(r.operation.input).removeVolumes===!0)}return r.checkpoint("finalize","Deployment command completed; persisting the terminal result."),{command:E.command??`cloud ${s.command.join(" ")}`,exitCode:E.exitCode,environment:s.target.environment,resource:s.target.resource??null}};return Object.fromEntries(iE.map((r)=>[r,t]))}class A extends Error{code;status;details;constructor(e,t,r,s){super(t);this.code=e;this.status=r;this.details=s}}function dr(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;if(e.resourceId&&e.resourceId!==t.resourceId)return!1;return!0}function TE(e,t,r){return dE("sha256").update(`${e.toUpperCase()}
|
|
1616
1616
|
${t}
|
|
1617
|
-
${JSON.stringify(r)}`).digest("hex")}class ps{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new H(e),this.spendGate=new Ne(e)}target(e,t){let r=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,t),n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope);if(!r||!n||!cr(n,r))throw new L("forbidden","The token does not grant access to this resource.",403);return r}authorize(e,t,r){if(!e.token.capabilities.includes(t))throw new L("forbidden",`The token is missing the ${t} capability.`,403);let n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,r),i=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope),o=t==="project:read"&&!!n&&!!i&&cr(n,i);if(!n||!i||!cr(i,n)&&!o)throw new L("forbidden","The token does not grant access to this resource.",403);let s=o?i:n;if(!ke({membership:e.membership,grants:this.controlPlane.listGrants(e.membership.id),capability:t,target:s}).allowed)throw new L("forbidden","The service account does not have access to this resource.",403);return n}listProjects(e){return this.controlPlane.listProjects().filter((t)=>t.organizationId===e.serviceAccount.organizationId).filter((t)=>{try{return this.authorize(e,"project:read",{type:"project",id:t.id}),!0}catch{return!1}}).map((t)=>({id:t.id,slug:t.slug,name:t.name,description:t.description,version:t.version,createdAt:t.createdAt,updatedAt:t.updatedAt}))}listEnvironments(e,t){let r=this.controlPlane.getProject(t);if(!r||r.organizationId!==e.serviceAccount.organizationId)throw new L("not_found","Project was not found.",404);return this.controlPlane.listEnvironments(t).filter((n)=>{try{return this.authorize(e,"project:read",{type:"environment",id:n.id}),!0}catch{return!1}}).map((n)=>({id:n.id,projectId:n.projectId,slug:n.slug,name:n.name,kind:n.kind,region:n.region,version:n.version,createdAt:n.createdAt,updatedAt:n.updatedAt}))}listServices(e,t,r){let n=new Set(this.listEnvironments(e,t).map((i)=>String(i.id)));if(r&&!n.has(r))throw new L("not_found","Environment was not found.",404);return this.controlPlane.listResources(t,r).filter((i)=>!i.environmentId||n.has(i.environmentId)).filter((i)=>{try{return this.authorize(e,"project:read",{type:"resource",id:i.id}),!0}catch{return!1}}).map((i)=>({id:i.id,projectId:i.projectId,environmentId:i.environmentId,kind:i.kind,slug:i.slug,name:i.name,provider:i.provider,providerId:i.providerId,metadata:I(i.metadata),version:i.version,createdAt:i.createdAt,updatedAt:i.updatedAt}))}listOperations(e,t){return this.controlPlane.listOperations({projectId:t,limit:500}).filter((n)=>{let i=n.resourceId?{type:"resource",id:n.resourceId}:n.environmentId?{type:"environment",id:n.environmentId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.authorize(e,"deployments:read",i),!0}catch{return!1}}).map((n)=>this.operation(n))}listEvents(e,t,r){if(t)this.authorize(e,"audit:read",{type:"project",id:t});else this.authorize(e,"audit:read",e.token.scope);return this.controlPlane.listEvents({organizationId:e.serviceAccount.organizationId,projectId:t,afterSequence:r,limit:500}).filter((n)=>{let i=n.resourceId?{type:"resource",id:n.resourceId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.target(e,i),!0}catch{return!1}}).map((n)=>({id:n.id,sequence:n.sequence,projectId:n.projectId,operationId:n.operationId,resourceId:n.resourceId,correlationId:n.correlationId,type:n.type,level:n.level,payload:I(n.payload),createdAt:n.createdAt}))}createDeployment(e,t,r){if(!this.controlPlane.listEnvironments(t.projectId).find((p)=>p.id===t.environmentId))throw new L("not_found","Environment was not found in this project.",404);let i=t.serviceId?{type:"resource",id:t.serviceId}:{type:"environment",id:t.environmentId};this.authorize(e,"deployments:create",i);let o=this.spendGate.check("deploy",{organizationId:e.serviceAccount.organizationId,projectId:t.projectId,environmentId:t.environmentId});if(!o.allowed)throw new L("spend_cap_exceeded",o.reason??"A spend cap is blocking deployments.",402,{action:o.action,budgetId:o.budgetId});let s=us("POST","/api/v1/deployments",t),a=this.identities.getIdempotency(e.token.id,r);if(a){if(a.requestHash!==s)throw new L("idempotency_conflict","Idempotency-Key was already used for another request.",409);let p=a.operationId?this.controlPlane.getOperation(a.operationId):void 0;if(!p)throw new L("idempotency_unavailable","The original operation is no longer available.",409);return{operation:this.operation(p),replay:!0}}if(t.serviceId){let p=this.controlPlane.getResource(t.serviceId);if(!p||p.projectId!==t.projectId||p.environmentId!==t.environmentId)throw new L("not_found","Service was not found in this environment.",404)}let d=t.serviceId?this.controlPlane.getResource(t.serviceId):void 0,c=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,resourceId:t.serviceId,actorId:e.actor.id,kind:t.action==="rollback"?"deployment.rollback":"deployment.create",idempotencyKey:`api:${e.token.id}:${r}`,input:I({action:t.action??"deploy",revision:t.revision??null}),lockKey:t.serviceId?`resource:${t.serviceId}`:`environment:${t.environmentId}`,providerKey:d?.provider??"default",buildSlot:t.action!=="rollback",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.identities.saveIdempotency({tokenId:e.token.id,key:r,requestHash:s,operationId:c.id,responseStatus:202,responseBody:{operationId:c.id}}),{operation:this.operation(c),replay:!1}}operation(e){return{id:e.id,state:e.state,kind:e.kind,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:e.actorId,correlationId:e.correlationId,input:I(e.input),output:I(e.output),error:e.error,attempt:e.attempt,createdAt:e.createdAt,updatedAt:e.updatedAt,startedAt:e.startedAt,finishedAt:e.finishedAt}}}function lt(e){return e.serviceAccount.organizationId}function An(e){if(e==null)return;if(e==="daily"||e==="weekly"||e==="monthly")return e;throw new L("validation_error","period must be daily, weekly, or monthly.",422)}function le(e,t){if(e==null)return;let r=Number(e);if(!Number.isFinite(r)||r<0||!Number.isInteger(r))throw new L("validation_error",`${t} must be a non-negative integer.`,422);return r}function D(e,t,r,n,i){if(i)e.authorization.authorize(t,r,{type:"environment",id:i});else if(n)e.authorization.authorize(t,r,{type:"project",id:n});else e.authorization.authorize(t,r,{type:"organization"});return{organizationId:lt(t),projectId:n,environmentId:i}}async function qc(e,t,r){let{method:n,url:i}=r,o=e.now?.()??new Date,s=i.searchParams.get("projectId")??void 0,a=i.searchParams.get("environmentId")??void 0;if(n==="GET"&&i.pathname==="/api/v1/usage"){let u=D(e,t,"billing:read",s,a);return e.service.usageReport({...u,period:An(i.searchParams.get("period")),timezone:i.searchParams.get("timezone")??void 0,now:o})}if(n==="GET"&&i.pathname==="/api/v1/usage/rollups"){let u=D(e,t,"billing:read",s,a),m=i.searchParams.get("from"),E=i.searchParams.get("to");if(!m||!E)throw new L("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(m))||Number.isNaN(Date.parse(E)))throw new L("validation_error","from and to must be ISO-8601 timestamps.",422);let T=i.searchParams.getAll("meter");return{data:e.store.listRollups({...u,from:m,to:E,meters:T.length>0?T:void 0},le(i.searchParams.get("limit"),"limit")??1000)}}if(n==="GET"&&i.pathname==="/api/v1/usage/focus"){let u=D(e,t,"billing:read",s,a),m=i.searchParams.get("from"),E=i.searchParams.get("to");if(!m||!E)throw new L("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(m))||Number.isNaN(Date.parse(E)))throw new L("validation_error","from and to must be ISO-8601 timestamps.",422);if(new Date(E).getTime()-new Date(m).getTime()>31622400000)throw new L("validation_error","The range must not exceed one year.",422);let T=i.searchParams.get("granularity")==="hourly"?"hourly":"daily",_=e.store.listRollups({...u,from:m,to:E},1e4),h=Hr(_,{billingPeriodStart:m,billingPeriodEnd:E,currency:e.store.priceBook.currency,granularity:T});return{contentType:"application/x-ndjson",body:Pt(h),recordCount:h.length}}if(n==="GET"&&i.pathname==="/api/v1/spend/budgets"){let u=D(e,t,"billing:read",s,a);return{data:e.store.listBudgets({organizationId:u.organizationId,projectId:u.projectId})}}if(n==="POST"&&i.pathname==="/api/v1/spend/budgets"){let u=await r.body?.()??{},E={organizationId:D(e,t,"billing:manage",u.projectId,u.environmentId).organizationId,projectId:u.projectId,environmentId:u.environmentId,name:String(u.name??"").trim(),period:An(u.period??"monthly")??"monthly",timezone:u.timezone,currency:u.currency,softLimitCents:le(u.softLimitCents,"softLimitCents"),hardLimitCents:le(u.hardLimitCents,"hardLimitCents"),thresholds:u.thresholds,meters:u.meters,graceSeconds:le(u.graceSeconds,"graceSeconds"),hysteresisPercent:u.hysteresisPercent,dryRun:u.dryRun!==!1,enabled:u.enabled};try{return{data:e.store.createBudget(E)}}catch(T){throw new L("validation_error",T instanceof Error?T.message:String(T),422)}}let d=/^\/api\/v1\/spend\/budgets\/([^/]+)$/.exec(i.pathname);if(d&&(n==="PATCH"||n==="DELETE")){let u=e.store.getBudget(decodeURIComponent(d[1]));if(!u||u.organizationId!==lt(t))throw new L("not_found","Budget was not found.",404);if(D(e,t,"billing:manage",u.projectId,u.environmentId),n==="DELETE")return{data:{deleted:e.store.deleteBudget(u.id)}};let m=await r.body?.()??{};try{return{data:e.store.updateBudget(u.id,m,le(m.expectedVersion,"expectedVersion"))}}catch(E){let T=E instanceof Error?E.message:String(E);throw new L(T.includes("concurrently")?"conflict":"validation_error",T,T.includes("concurrently")?409:422)}}if(n==="GET"&&i.pathname==="/api/v1/spend/anomalies"){let u=D(e,t,"billing:read",s,a);return{data:e.store.listAnomalies({organizationId:u.organizationId,projectId:u.projectId,since:i.searchParams.get("since")??void 0,unacknowledgedOnly:i.searchParams.get("unacknowledged")==="true",limit:le(i.searchParams.get("limit"),"limit")})}}let c=/^\/api\/v1\/spend\/anomalies\/([^/]+)\/acknowledge$/.exec(i.pathname);if(c&&n==="POST"){let u=e.store.getAnomaly(decodeURIComponent(c[1]));if(!u||u.organizationId!==lt(t))throw new L("not_found","Anomaly was not found.",404);return D(e,t,"billing:manage",u.projectId,u.environmentId),{data:{acknowledged:e.store.acknowledgeAnomaly(u.id)}}}if(n==="GET"&&i.pathname==="/api/v1/spend/signals")return D(e,t,"billing:read",s,a),{data:he};if(i.pathname==="/api/v1/spend/anomaly-configs"){if(n==="GET"){let u=D(e,t,"billing:read",s,a);return{data:e.service.anomalyConfigs.list({organizationId:u.organizationId,projectId:u.projectId})}}if(n==="POST"){let u=await r.body?.()??{},m=D(e,t,"billing:manage",u.projectId,u.environmentId);try{return{data:e.service.anomalyConfigs.upsert({organizationId:m.organizationId,projectId:u.projectId,environmentId:u.environmentId,signal:String(u.signal??""),enabled:u.enabled,sensitivity:u.sensitivity,seasonLength:u.seasonLength==null?void 0:Number(u.seasonLength),minAbsoluteDelta:u.minAbsoluteDelta==null?void 0:Number(u.minAbsoluteDelta),detectDrops:u.detectDrops,severity:u.severity})}}catch(E){throw new L("validation_error",E instanceof Error?E.message:String(E),422)}}}let p=/^\/api\/v1\/spend\/anomaly-configs\/([^/]+)$/.exec(i.pathname);if(p&&n==="DELETE"){let u=e.service.anomalyConfigs.get(decodeURIComponent(p[1]));if(!u||u.organizationId!==lt(t))throw new L("not_found","Anomaly config was not found.",404);return D(e,t,"billing:manage",u.projectId,u.environmentId),{data:{deleted:e.service.anomalyConfigs.delete(u.id)}}}if(i.pathname==="/api/v1/spend/anomaly-silences"){if(n==="GET"){let u=D(e,t,"billing:read",s,a);return{data:e.service.anomalyConfigs.listSilences({organizationId:u.organizationId,projectId:u.projectId,includeExpired:i.searchParams.get("includeExpired")==="true"})}}if(n==="POST"){let u=await r.body?.()??{},m=D(e,t,"billing:manage",u.projectId);try{return{data:e.service.anomalyConfigs.silence({organizationId:m.organizationId,projectId:u.projectId,signal:u.signal,routePattern:u.routePattern,statusCode:u.statusCode==null?void 0:Number(u.statusCode),reason:String(u.reason??""),expiresAt:u.expiresAt})}}catch(E){throw new L("validation_error",E instanceof Error?E.message:String(E),422)}}}let l=/^\/api\/v1\/spend\/anomaly-silences\/([^/]+)$/.exec(i.pathname);if(l&&n==="DELETE")return D(e,t,"billing:manage",s),{data:{deleted:e.service.anomalyConfigs.removeSilence(decodeURIComponent(l[1]))}};if(n==="GET"&&i.pathname==="/api/v1/spend/enforcement"){let u=D(e,t,"billing:read",s,a);return{data:e.store.listEnforcements({organizationId:u.organizationId,activeOnly:i.searchParams.get("active")!=="false"})}}if(n==="GET"&&i.pathname==="/api/v1/spend/allowance"){let u=D(e,t,"billing:read",s,a),m=i.searchParams.get("operation")??"deploy";if(!["build","deploy","function_invoke","request"].includes(m))throw new L("validation_error","operation must be build, deploy, function_invoke, or request.",422);let T=e.store.listEnforcements({organizationId:u.organizationId,activeOnly:!0}).filter((f)=>(!f.projectId||f.projectId===u.projectId)&&(!f.environmentId||f.environmentId===u.environmentId)),_=jr(m,T),N=e.store.budgetsForScope(u.organizationId,u.projectId,u.environmentId).map((f)=>e.service.status(f,o));return{operation:m,allowed:_.allowed,blockedBy:_.blockedBy??null,reason:_.reason??null,budgets:N.map((f)=>({id:f.budget.id,name:f.budget.name,usedPercent:f.decision.usedPercent,projectedPercent:f.decision.projectedPercent,level:f.decision.level,timeToCap:f.timeToCap}))}}return}function Hc(){let e=[{name:"projectId",in:"query",schema:{type:"string"}},{name:"environmentId",in:"query",schema:{type:"string"}}];return{"/api/v1/usage":{get:{summary:"Current usage, cost, and every budget governing the scope.",parameters:[...e,{name:"period",in:"query",schema:{type:"string",enum:["daily","weekly","monthly"]}},{name:"timezone",in:"query",schema:{type:"string"}}],responses:{"200":{description:"Usage totals, per-meter breakdown, hourly series, and budget status."}}}},"/api/v1/usage/rollups":{get:{summary:"Itemized hourly usage rollups.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"meter",in:"query",schema:{type:"array",items:{type:"string"}}},{name:"limit",in:"query",schema:{type:"integer"}}],responses:{"200":{description:"Hourly rollups, newest first."}}}},"/api/v1/usage/focus":{get:{summary:"Usage and cost in FOCUS v1.3 format, newline-delimited JSON.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"granularity",in:"query",schema:{type:"string",enum:["daily","hourly"]}}],responses:{"200":{description:"FOCUS records, one JSON object per line."}}}},"/api/v1/spend/budgets":{get:{summary:"Budgets governing a scope.",parameters:e,responses:{"200":{description:"Budgets."}}},post:{summary:"Create a budget. Starts in dry run unless dryRun is explicitly false.",responses:{"201":{description:"The created budget."},"422":{description:"Validation error."}}}},"/api/v1/spend/budgets/{budgetId}":{patch:{summary:"Update a budget. Pass expectedVersion for optimistic concurrency.",responses:{"200":{description:"The updated budget."},"409":{description:"Version conflict."}}},delete:{summary:"Delete a budget.",responses:{"200":{description:"Deletion result."}}}},"/api/v1/spend/anomalies":{get:{summary:"Detected spend anomalies.",parameters:[...e,{name:"since",in:"query",schema:{type:"string",format:"date-time"}},{name:"unacknowledged",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Anomalies, newest first."}}}},"/api/v1/spend/anomalies/{anomalyId}/acknowledge":{post:{summary:"Acknowledge an anomaly.",responses:{"200":{description:"Acknowledgement result."}}}},"/api/v1/spend/signals":{get:{summary:"Signals anomaly detection can run on, with their gap and sample rules.",responses:{"200":{description:"Signal catalog."}}}},"/api/v1/spend/anomaly-configs":{get:{summary:"Anomaly detection configuration.",parameters:e,responses:{"200":{description:"Configs."}}},post:{summary:"Create or update the config for a signal.",responses:{"200":{description:"The config."}}}},"/api/v1/spend/anomaly-configs/{configId}":{delete:{summary:"Delete an anomaly config, returning the signal to its default.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/anomaly-silences":{get:{summary:"Active anomaly silences.",parameters:e,responses:{"200":{description:"Silences."}}},post:{summary:"Silence a signal, route, or status code. A reason is required.",responses:{"200":{description:"The silence."}}}},"/api/v1/spend/anomaly-silences/{silenceId}":{delete:{summary:"Remove a silence.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/enforcement":{get:{summary:"Enforcement actions in force.",parameters:[...e,{name:"active",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Enforcement records."}}}},"/api/v1/spend/allowance":{get:{summary:"Whether an operation is allowed under current spend enforcement.",parameters:[...e,{name:"operation",in:"query",schema:{type:"string",enum:["build","deploy","function_invoke","request"]}}],responses:{"200":{description:"Allowance verdict and the budgets behind it."}}}}}}export{q as ci,Tt as di,re as ei,we as fi,_t as gi,ke as hi,zn as ii,B as ji,ht as ki,Xe as li,Kn as mi,vr as ni,Lt as oi,I as pi,Sr as qi,ei as ri,ie as si,Wt as ti,Jt as ui,Xo as vi,Po as wi,Zt as xi,Ud as yi,Dd as zi,it as Ai,Xd as Bi,Pd as Ci,xd as Di,jd as Ei,Re as Fi,tt as Gi,J as Hi,H as Ii,yo as Ji,ce as Ki,ss as Li,as as Mi,ds as Ni,bc as Oi,st as Pi,zo as Qi,ot as Ri,qo as Si,Ho as Ti,Bo as Ui,zd as Vi,rr as Wi,Jo as Xi,Zo as Yi,or as Zi,Rn as _i,ee as $i,ts as aj,Es as bj,ut as cj,ms as dj,k as ej,gs as fj,lr as gj,Dn as hj,pt as ij,_s as jj,hs as kj,Ns as lj,ur as mj,Ue as nj,Et as oj,Er as pj,te as qj,Q as rj,ys as sj,ue as tj,Ls as uj,gr as vj,xn as wj,Fn as xj,mt as yj,_r as zj,hr as Aj,G as Bj,ni as Cj,ii as Dj,Ur as Ej,Ct as Fj,ge as Gj,ai as Hj,Qe as Ij,Dr as Jj,wr as Kj,Ye as Lj,li as Mj,Xr as Nj,Pr as Oj,xr as Pj,jr as Qj,At as Rj,pi as Sj,Ei as Tj,na as Uj,Ti as Vj,Fr as Wj,Ge as Xj,gi as Yj,hi as Zj,Ut as _j,he as $j,wt as ak,kt as bk,Xt as ck,Mr as dk,fi as ek,Hr as fk,Pt as gk,la as hk,xt as ik,ya as jk,Br as kk,Ne as lk,Vr as mk,Sa as nk,$r as ok,Ai as pk,wi as qk,fe as rk,qt as sk,Bi as tk,Qi as uk,Yi as vk,nn as wk,on as xk,Gi as yk,Fa as zk,Ma as Ak,Bt as Bk,ye as Ck,sn as Dk,cn as Ek,io as Fk,oo as Gk,Vt as Hk,Ja as Ik,cd as Jk,Ie as Kk,ao as Lk,Kt as Mk,ud as Nk,po as Ok,Eo as Pk,mo as Qk,_d as Rk,To as Sk,go as Tk,fd as Uk,L as Vk,us as Wk,ps as Xk,qc as Yk,Hc as Zk};
|
|
1617
|
+
${JSON.stringify(r)}`).digest("hex")}class oE{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new $(e),this.spendGate=new Ce(e)}target(e,t){let r=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,t),s=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope);if(!r||!s||!dr(s,r))throw new A("forbidden","The token does not grant access to this resource.",403);return r}authorize(e,t,r){if(!e.token.capabilities.includes(t))throw new A("forbidden",`The token is missing the ${t} capability.`,403);let s=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,r),n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope),i=t==="project:read"&&!!s&&!!n&&dr(s,n);if(!s||!n||!dr(n,s)&&!i)throw new A("forbidden","The token does not grant access to this resource.",403);let E=i?n:s;if(!be({membership:e.membership,grants:this.controlPlane.listGrants(e.membership.id),capability:t,target:E}).allowed)throw new A("forbidden","The service account does not have access to this resource.",403);return s}listProjects(e){return this.controlPlane.listProjects().filter((t)=>t.organizationId===e.serviceAccount.organizationId).filter((t)=>{try{return this.authorize(e,"project:read",{type:"project",id:t.id}),!0}catch{return!1}}).map((t)=>({id:t.id,slug:t.slug,name:t.name,description:t.description,version:t.version,createdAt:t.createdAt,updatedAt:t.updatedAt}))}listEnvironments(e,t){let r=this.controlPlane.getProject(t);if(!r||r.organizationId!==e.serviceAccount.organizationId)throw new A("not_found","Project was not found.",404);return this.controlPlane.listEnvironments(t).filter((s)=>{try{return this.authorize(e,"project:read",{type:"environment",id:s.id}),!0}catch{return!1}}).map((s)=>({id:s.id,projectId:s.projectId,slug:s.slug,name:s.name,kind:s.kind,region:s.region,version:s.version,createdAt:s.createdAt,updatedAt:s.updatedAt}))}listServices(e,t,r){let s=new Set(this.listEnvironments(e,t).map((n)=>String(n.id)));if(r&&!s.has(r))throw new A("not_found","Environment was not found.",404);return this.controlPlane.listResources(t,r).filter((n)=>!n.environmentId||s.has(n.environmentId)).filter((n)=>{try{return this.authorize(e,"project:read",{type:"resource",id:n.id}),!0}catch{return!1}}).map((n)=>({id:n.id,projectId:n.projectId,environmentId:n.environmentId,kind:n.kind,slug:n.slug,name:n.name,provider:n.provider,providerId:n.providerId,metadata:h(n.metadata),version:n.version,createdAt:n.createdAt,updatedAt:n.updatedAt}))}listOperations(e,t){return this.controlPlane.listOperations({projectId:t,limit:500}).filter((s)=>{let n=s.resourceId?{type:"resource",id:s.resourceId}:s.environmentId?{type:"environment",id:s.environmentId}:s.projectId?{type:"project",id:s.projectId}:{type:"organization"};try{return this.authorize(e,"deployments:read",n),!0}catch{return!1}}).map((s)=>this.operation(s))}listEvents(e,t,r){if(t)this.authorize(e,"audit:read",{type:"project",id:t});else this.authorize(e,"audit:read",e.token.scope);return this.controlPlane.listEvents({organizationId:e.serviceAccount.organizationId,projectId:t,afterSequence:r,limit:500}).filter((s)=>{let n=s.resourceId?{type:"resource",id:s.resourceId}:s.projectId?{type:"project",id:s.projectId}:{type:"organization"};try{return this.target(e,n),!0}catch{return!1}}).map((s)=>({id:s.id,sequence:s.sequence,projectId:s.projectId,operationId:s.operationId,resourceId:s.resourceId,correlationId:s.correlationId,type:s.type,level:s.level,payload:h(s.payload),createdAt:s.createdAt}))}createDeployment(e,t,r){if(!this.controlPlane.listEnvironments(t.projectId).find((N)=>N.id===t.environmentId))throw new A("not_found","Environment was not found in this project.",404);let n=t.serviceId?{type:"resource",id:t.serviceId}:{type:"environment",id:t.environmentId};this.authorize(e,"deployments:create",n);let i=this.spendGate.check("deploy",{organizationId:e.serviceAccount.organizationId,projectId:t.projectId,environmentId:t.environmentId});if(!i.allowed)throw new A("spend_cap_exceeded",i.reason??"A spend cap is blocking deployments.",402,{action:i.action,budgetId:i.budgetId});let E=TE("POST","/api/v1/deployments",t),a=this.identities.getIdempotency(e.token.id,r);if(a){if(a.requestHash!==E)throw new A("idempotency_conflict","Idempotency-Key was already used for another request.",409);let N=a.operationId?this.controlPlane.getOperation(a.operationId):void 0;if(!N)throw new A("idempotency_unavailable","The original operation is no longer available.",409);return{operation:this.operation(N),replay:!0}}if(t.serviceId){let N=this.controlPlane.getResource(t.serviceId);if(!N||N.projectId!==t.projectId||N.environmentId!==t.environmentId)throw new A("not_found","Service was not found in this environment.",404)}let d=t.serviceId?this.controlPlane.getResource(t.serviceId):void 0,T=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,resourceId:t.serviceId,actorId:e.actor.id,kind:t.action==="rollback"?"deployment.rollback":"deployment.create",idempotencyKey:`api:${e.token.id}:${r}`,input:h({action:t.action??"deploy",revision:t.revision??null}),lockKey:t.serviceId?`resource:${t.serviceId}`:`environment:${t.environmentId}`,providerKey:d?.provider??"default",buildSlot:t.action!=="rollback",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.identities.saveIdempotency({tokenId:e.token.id,key:r,requestHash:E,operationId:T.id,responseStatus:202,responseBody:{operationId:T.id}}),{operation:this.operation(T),replay:!1}}operation(e){return{id:e.id,state:e.state,kind:e.kind,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:e.actorId,correlationId:e.correlationId,input:h(e.input),output:h(e.output),error:e.error,attempt:e.attempt,createdAt:e.createdAt,updatedAt:e.updatedAt,startedAt:e.startedAt,finishedAt:e.finishedAt}}}function Tt(e){return e.serviceAccount.organizationId}function Xs(e){if(e==null)return;if(e==="daily"||e==="weekly"||e==="monthly")return e;throw new A("validation_error","period must be daily, weekly, or monthly.",422)}function Te(e,t){if(e==null)return;let r=Number(e);if(!Number.isFinite(r)||r<0||!Number.isInteger(r))throw new A("validation_error",`${t} must be a non-negative integer.`,422);return r}function D(e,t,r,s,n){if(n)e.authorization.authorize(t,r,{type:"environment",id:n});else if(s)e.authorization.authorize(t,r,{type:"project",id:s});else e.authorization.authorize(t,r,{type:"organization"});return{organizationId:Tt(t),projectId:s,environmentId:n}}async function MT(e,t,r){let{method:s,url:n}=r,i=e.now?.()??new Date,E=n.searchParams.get("projectId")??void 0,a=n.searchParams.get("environmentId")??void 0;if(s==="GET"&&n.pathname==="/api/v1/usage"){let c=D(e,t,"billing:read",E,a);return e.service.usageReport({...c,period:Xs(n.searchParams.get("period")),timezone:n.searchParams.get("timezone")??void 0,now:i})}if(s==="GET"&&n.pathname==="/api/v1/usage/rollups"){let c=D(e,t,"billing:read",E,a),l=n.searchParams.get("from"),_=n.searchParams.get("to");if(!l||!_)throw new A("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(l))||Number.isNaN(Date.parse(_)))throw new A("validation_error","from and to must be ISO-8601 timestamps.",422);let L=n.searchParams.getAll("meter");return{data:e.store.listRollups({...c,from:l,to:_,meters:L.length>0?L:void 0},Te(n.searchParams.get("limit"),"limit")??1000)}}if(s==="GET"&&n.pathname==="/api/v1/usage/focus"){let c=D(e,t,"billing:read",E,a),l=n.searchParams.get("from"),_=n.searchParams.get("to");if(!l||!_)throw new A("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(l))||Number.isNaN(Date.parse(_)))throw new A("validation_error","from and to must be ISO-8601 timestamps.",422);if(new Date(_).getTime()-new Date(l).getTime()>31622400000)throw new A("validation_error","The range must not exceed one year.",422);let L=n.searchParams.get("granularity")==="hourly"?"hourly":"daily",u=e.store.listRollups({...c,from:l,to:_},1e4),C=Br(u,{billingPeriodStart:l,billingPeriodEnd:_,currency:e.store.priceBook.currency,granularity:L});return{contentType:"application/x-ndjson",body:Ft(C),recordCount:C.length}}if(s==="GET"&&n.pathname==="/api/v1/spend/budgets"){let c=D(e,t,"billing:read",E,a);return{data:e.store.listBudgets({organizationId:c.organizationId,projectId:c.projectId})}}if(s==="POST"&&n.pathname==="/api/v1/spend/budgets"){let c=await r.body?.()??{},_={organizationId:D(e,t,"billing:manage",c.projectId,c.environmentId).organizationId,projectId:c.projectId,environmentId:c.environmentId,name:String(c.name??"").trim(),period:Xs(c.period??"monthly")??"monthly",timezone:c.timezone,currency:c.currency,softLimitCents:Te(c.softLimitCents,"softLimitCents"),hardLimitCents:Te(c.hardLimitCents,"hardLimitCents"),thresholds:c.thresholds,meters:c.meters,graceSeconds:Te(c.graceSeconds,"graceSeconds"),hysteresisPercent:c.hysteresisPercent,dryRun:c.dryRun!==!1,enabled:c.enabled};try{return{data:e.store.createBudget(_)}}catch(L){throw new A("validation_error",L instanceof Error?L.message:String(L),422)}}let d=/^\/api\/v1\/spend\/budgets\/([^/]+)$/.exec(n.pathname);if(d&&(s==="PATCH"||s==="DELETE")){let c=e.store.getBudget(decodeURIComponent(d[1]));if(!c||c.organizationId!==Tt(t))throw new A("not_found","Budget was not found.",404);if(D(e,t,"billing:manage",c.projectId,c.environmentId),s==="DELETE")return{data:{deleted:e.store.deleteBudget(c.id)}};let l=await r.body?.()??{};try{return{data:e.store.updateBudget(c.id,l,Te(l.expectedVersion,"expectedVersion"))}}catch(_){let L=_ instanceof Error?_.message:String(_);throw new A(L.includes("concurrently")?"conflict":"validation_error",L,L.includes("concurrently")?409:422)}}if(s==="GET"&&n.pathname==="/api/v1/spend/anomalies"){let c=D(e,t,"billing:read",E,a);return{data:e.store.listAnomalies({organizationId:c.organizationId,projectId:c.projectId,since:n.searchParams.get("since")??void 0,unacknowledgedOnly:n.searchParams.get("unacknowledged")==="true",limit:Te(n.searchParams.get("limit"),"limit")})}}let T=/^\/api\/v1\/spend\/anomalies\/([^/]+)\/acknowledge$/.exec(n.pathname);if(T&&s==="POST"){let c=e.store.getAnomaly(decodeURIComponent(T[1]));if(!c||c.organizationId!==Tt(t))throw new A("not_found","Anomaly was not found.",404);return D(e,t,"billing:manage",c.projectId,c.environmentId),{data:{acknowledged:e.store.acknowledgeAnomaly(c.id)}}}if(s==="GET"&&n.pathname==="/api/v1/spend/signals")return D(e,t,"billing:read",E,a),{data:ue};if(n.pathname==="/api/v1/spend/anomaly-configs"){if(s==="GET"){let c=D(e,t,"billing:read",E,a);return{data:e.service.anomalyConfigs.list({organizationId:c.organizationId,projectId:c.projectId})}}if(s==="POST"){let c=await r.body?.()??{},l=D(e,t,"billing:manage",c.projectId,c.environmentId);try{return{data:e.service.anomalyConfigs.upsert({organizationId:l.organizationId,projectId:c.projectId,environmentId:c.environmentId,signal:String(c.signal??""),enabled:c.enabled,sensitivity:c.sensitivity,seasonLength:c.seasonLength==null?void 0:Number(c.seasonLength),minAbsoluteDelta:c.minAbsoluteDelta==null?void 0:Number(c.minAbsoluteDelta),detectDrops:c.detectDrops,severity:c.severity})}}catch(_){throw new A("validation_error",_ instanceof Error?_.message:String(_),422)}}}let N=/^\/api\/v1\/spend\/anomaly-configs\/([^/]+)$/.exec(n.pathname);if(N&&s==="DELETE"){let c=e.service.anomalyConfigs.get(decodeURIComponent(N[1]));if(!c||c.organizationId!==Tt(t))throw new A("not_found","Anomaly config was not found.",404);return D(e,t,"billing:manage",c.projectId,c.environmentId),{data:{deleted:e.service.anomalyConfigs.delete(c.id)}}}if(n.pathname==="/api/v1/spend/anomaly-silences"){if(s==="GET"){let c=D(e,t,"billing:read",E,a);return{data:e.service.anomalyConfigs.listSilences({organizationId:c.organizationId,projectId:c.projectId,includeExpired:n.searchParams.get("includeExpired")==="true"})}}if(s==="POST"){let c=await r.body?.()??{},l=D(e,t,"billing:manage",c.projectId);try{return{data:e.service.anomalyConfigs.silence({organizationId:l.organizationId,projectId:c.projectId,signal:c.signal,routePattern:c.routePattern,statusCode:c.statusCode==null?void 0:Number(c.statusCode),reason:String(c.reason??""),expiresAt:c.expiresAt})}}catch(_){throw new A("validation_error",_ instanceof Error?_.message:String(_),422)}}}let o=/^\/api\/v1\/spend\/anomaly-silences\/([^/]+)$/.exec(n.pathname);if(o&&s==="DELETE")return D(e,t,"billing:manage",E),{data:{deleted:e.service.anomalyConfigs.removeSilence(decodeURIComponent(o[1]))}};if(s==="GET"&&n.pathname==="/api/v1/spend/enforcement"){let c=D(e,t,"billing:read",E,a);return{data:e.store.listEnforcements({organizationId:c.organizationId,activeOnly:n.searchParams.get("active")!=="false"})}}if(s==="GET"&&n.pathname==="/api/v1/spend/allowance"){let c=D(e,t,"billing:read",E,a),l=n.searchParams.get("operation")??"deploy";if(!["build","deploy","function_invoke","request"].includes(l))throw new A("validation_error","operation must be build, deploy, function_invoke, or request.",422);let L=e.store.listEnforcements({organizationId:c.organizationId,activeOnly:!0}).filter((R)=>(!R.projectId||R.projectId===c.projectId)&&(!R.environmentId||R.environmentId===c.environmentId)),u=Hr(l,L),g=e.store.budgetsForScope(c.organizationId,c.projectId,c.environmentId).map((R)=>e.service.status(R,i));return{operation:l,allowed:u.allowed,blockedBy:u.blockedBy??null,reason:u.reason??null,budgets:g.map((R)=>({id:R.budget.id,name:R.budget.name,usedPercent:R.decision.usedPercent,projectedPercent:R.decision.projectedPercent,level:R.decision.level,timeToCap:R.timeToCap}))}}return}function jT(){let e=[{name:"projectId",in:"query",schema:{type:"string"}},{name:"environmentId",in:"query",schema:{type:"string"}}];return{"/api/v1/usage":{get:{summary:"Current usage, cost, and every budget governing the scope.",parameters:[...e,{name:"period",in:"query",schema:{type:"string",enum:["daily","weekly","monthly"]}},{name:"timezone",in:"query",schema:{type:"string"}}],responses:{"200":{description:"Usage totals, per-meter breakdown, hourly series, and budget status."}}}},"/api/v1/usage/rollups":{get:{summary:"Itemized hourly usage rollups.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"meter",in:"query",schema:{type:"array",items:{type:"string"}}},{name:"limit",in:"query",schema:{type:"integer"}}],responses:{"200":{description:"Hourly rollups, newest first."}}}},"/api/v1/usage/focus":{get:{summary:"Usage and cost in FOCUS v1.3 format, newline-delimited JSON.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"granularity",in:"query",schema:{type:"string",enum:["daily","hourly"]}}],responses:{"200":{description:"FOCUS records, one JSON object per line."}}}},"/api/v1/spend/budgets":{get:{summary:"Budgets governing a scope.",parameters:e,responses:{"200":{description:"Budgets."}}},post:{summary:"Create a budget. Starts in dry run unless dryRun is explicitly false.",responses:{"201":{description:"The created budget."},"422":{description:"Validation error."}}}},"/api/v1/spend/budgets/{budgetId}":{patch:{summary:"Update a budget. Pass expectedVersion for optimistic concurrency.",responses:{"200":{description:"The updated budget."},"409":{description:"Version conflict."}}},delete:{summary:"Delete a budget.",responses:{"200":{description:"Deletion result."}}}},"/api/v1/spend/anomalies":{get:{summary:"Detected spend anomalies.",parameters:[...e,{name:"since",in:"query",schema:{type:"string",format:"date-time"}},{name:"unacknowledged",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Anomalies, newest first."}}}},"/api/v1/spend/anomalies/{anomalyId}/acknowledge":{post:{summary:"Acknowledge an anomaly.",responses:{"200":{description:"Acknowledgement result."}}}},"/api/v1/spend/signals":{get:{summary:"Signals anomaly detection can run on, with their gap and sample rules.",responses:{"200":{description:"Signal catalog."}}}},"/api/v1/spend/anomaly-configs":{get:{summary:"Anomaly detection configuration.",parameters:e,responses:{"200":{description:"Configs."}}},post:{summary:"Create or update the config for a signal.",responses:{"200":{description:"The config."}}}},"/api/v1/spend/anomaly-configs/{configId}":{delete:{summary:"Delete an anomaly config, returning the signal to its default.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/anomaly-silences":{get:{summary:"Active anomaly silences.",parameters:e,responses:{"200":{description:"Silences."}}},post:{summary:"Silence a signal, route, or status code. A reason is required.",responses:{"200":{description:"The silence."}}}},"/api/v1/spend/anomaly-silences/{silenceId}":{delete:{summary:"Remove a silence.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/enforcement":{get:{summary:"Enforcement actions in force.",parameters:[...e,{name:"active",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Enforcement records."}}}},"/api/v1/spend/allowance":{get:{summary:"Whether an operation is allowed under current spend enforcement.",parameters:[...e,{name:"operation",in:"query",schema:{type:"string",enum:["build","deploy","function_invoke","request"]}}],responses:{"200":{description:"Allowance verdict and the budgets behind it."}}}}}}export{B as ci,lt as di,te as ei,De as fi,mt as gi,be as hi,xs as ii,q as ji,ut as ki,ke as li,qs as mi,Ar as ni,Ot as oi,h as pi,hr as qi,Zs as ri,se as si,Wt as ti,Jt as ui,bi as vi,ki as wi,Zt as xi,vd as yi,yd as zi,st as Ai,bd as Bi,kd as Ci,Fd as Di,Pd as Ei,Se as Fi,et as Gi,J as Hi,$ as Ii,gi as Ji,de as Ki,nE as Li,iE as Mi,EE as Ni,hT as Oi,xi as Pi,nt as Qi,Mi as Ri,ji as Si,Bi as Ti,xd as Ui,tr as Vi,Wi,Ji as Xi,it as Yi,nr as Zi,fs as _i,w as $i,wi as aj,cE as bj,ot as cj,NE as dj,k as ej,lE as fj,Tr as gj,ys as hj,ct as ij,LE as jj,mE as kj,uE as lj,or as mj,ye as nj,Nt as oj,Nr as pj,ee as qj,G as rj,gE as sj,oe as tj,RE as uj,Lr as vj,Fs as wj,Hs as xj,_t as yj,mr as zj,ur as Aj,V as Bj,tn as Cj,rn as Dj,yr as Ej,Xt as Fj,Le as Gj,En as Hj,Ge as Ij,pr as Jj,Dr as Kj,Qe as Lj,Tn as Mj,kr as Nj,Fr as Oj,Pr as Pj,Hr as Qj,It as Rj,cn as Sj,Nn as Tj,ta as Uj,ln as Vj,Kr as Wj,Ve as Xj,Ln as Yj,un as Zj,yt as _j,ue as $j,Dt as ak,bt as bk,kt as ck,xr as dk,gn as ek,Br as fk,Ft as gk,da as hk,Pt as ik,ga as jk,$r as kk,Ce as lk,qr as mk,Ua as nk,zr as ok,In as pk,Dn as qk,ge as rk,jt as sk,$n as tk,Gn as uk,Qn as vk,rs as wk,ss as xk,Vn as yk,Ha as zk,Ka as Ak,$t as Bk,Re as Ck,ns as Dk,as as Ek,si as Fk,ni as Gk,qt as Hk,Wa as Ik,ad as Jk,Ue as Kk,Ei as Lk,Yt as Mk,Td as Nk,oi as Ok,ci as Pk,Ni as Qk,Ld as Rk,_i as Sk,li as Tk,Cd as Uk,A as Vk,TE as Wk,oE as Xk,MT as Yk,jT as Zk};
|