@stacksjs/ts-cloud 0.11.1 → 0.11.3
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-6vjrts39.js → chunk-0zwknfwp.js} +1 -1
- package/dist/bin/chunk-104xrc2w.js +1 -0
- package/dist/bin/{chunk-jce28gnz.js → chunk-3aph4c1w.js} +2 -2
- package/dist/bin/{chunk-4a97kbk1.js → chunk-4q6tad44.js} +2 -2
- package/dist/bin/{chunk-md2k3n21.js → chunk-4xhj37nj.js} +1 -1
- package/dist/bin/{chunk-ftse39wf.js → chunk-56wvjysz.js} +2 -2
- package/dist/bin/chunk-5nkqza92.js +1 -0
- package/dist/bin/chunk-64vczwwt.js +1 -0
- package/dist/bin/{chunk-y3rm37z1.js → chunk-6tfwm33r.js} +3 -3
- package/dist/bin/chunk-7g2ahkse.js +1 -0
- package/dist/bin/{chunk-9rsn48qg.js → chunk-81hmza39.js} +2 -2
- package/dist/bin/{chunk-gskbezam.js → chunk-82mj52xr.js} +2 -2
- package/dist/bin/{chunk-mwgxyc0z.js → chunk-8khgprf6.js} +1 -1
- package/dist/bin/{chunk-mbnwt3r5.js → chunk-9a88fp00.js} +2 -2
- package/dist/bin/{chunk-21gggxvf.js → chunk-a7w13qfm.js} +2 -2
- package/dist/bin/{chunk-wzepfqf4.js → chunk-b0e39tpv.js} +6 -6
- package/dist/bin/{chunk-r6x7beew.js → chunk-b4wt9jcg.js} +2 -2
- package/dist/bin/{chunk-4a85nk2q.js → chunk-btsyjhk7.js} +2 -2
- package/dist/bin/{chunk-nmkm1f68.js → chunk-c0bdafbx.js} +2 -2
- package/dist/bin/{chunk-67jsyn0g.js → chunk-cbsys5v8.js} +2 -2
- package/dist/bin/{chunk-kbtrr0c3.js → chunk-cd0ps58j.js} +1 -1
- package/dist/bin/{chunk-fpcghdr3.js → chunk-cq9mca3h.js} +3 -3
- package/dist/bin/{chunk-9mydnqr6.js → chunk-d7ke90zt.js} +2 -2
- package/dist/bin/chunk-djg4zyqk.js +1 -0
- package/dist/bin/chunk-dkaz333b.js +1 -0
- package/dist/bin/{chunk-ww770qpn.js → chunk-dz1ec589.js} +2 -2
- package/dist/bin/{chunk-xev7qr2h.js → chunk-e2bybahr.js} +2 -2
- package/dist/bin/{chunk-dbv8w56s.js → chunk-e5ab5twy.js} +2 -2
- package/dist/bin/chunk-edvvx3hg.js +1 -0
- package/dist/bin/{chunk-ks4ewy1s.js → chunk-ehc63fvs.js} +1 -1
- package/dist/bin/chunk-f06c5np9.js +1 -0
- package/dist/bin/{chunk-nkpf91d3.js → chunk-g0fm1xcs.js} +1 -1
- package/dist/bin/chunk-gq8794k6.js +1 -0
- package/dist/bin/{chunk-4vdv41nh.js → chunk-hq9x489e.js} +1 -1
- package/dist/bin/{chunk-0y89hs67.js → chunk-ja1vjdn1.js} +1 -1
- package/dist/bin/{chunk-zwwnt4x1.js → chunk-k3120rx6.js} +1 -1
- package/dist/bin/{chunk-q182t9ba.js → chunk-kg61p5hw.js} +3 -3
- package/dist/bin/chunk-m189194f.js +1 -0
- package/dist/bin/{chunk-hej39dwr.js → chunk-mcr0r4at.js} +2 -2
- package/dist/bin/chunk-mfrf9q4b.js +2 -0
- package/dist/bin/{chunk-4kbhbfq8.js → chunk-my3ewh3a.js} +2 -2
- package/dist/bin/chunk-nw3d4k52.js +1 -0
- package/dist/bin/chunk-p70bc9yr.js +1 -0
- package/dist/bin/{chunk-neampxq1.js → chunk-r6b3pq31.js} +2 -2
- package/dist/bin/{chunk-c1j9v7ee.js → chunk-s4yzes15.js} +2 -2
- package/dist/bin/{chunk-41yqpdv7.js → chunk-sj5csg49.js} +1 -1
- package/dist/bin/chunk-tvz9c388.js +1 -0
- package/dist/bin/{chunk-e1bfd1yv.js → chunk-w32xv8n4.js} +2 -2
- package/dist/bin/chunk-wkx799z2.js +1 -0
- package/dist/bin/{chunk-nyc2jxd8.js → chunk-xhwqpgwq.js} +1 -1
- package/dist/bin/{chunk-zejwh9cy.js → chunk-xk08030d.js} +2 -2
- package/dist/bin/chunk-y1h63vpm.js +1 -0
- package/dist/bin/chunk-zdt2rjk6.js +1 -0
- package/dist/bin/chunk-zh2d4704.js +1 -0
- package/dist/bin/{chunk-35xstvnq.js → chunk-znnawt0k.js} +1 -1
- package/dist/bin/{chunk-26cj89s6.js → chunk-zpe64t4r.js} +1 -1
- package/dist/bin/{chunk-a2t1e5yb.js → chunk-zsf6pccz.js} +1 -1
- package/dist/bin/cli.js +237 -237
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/cdn/cloudflare-settings.d.ts +16 -0
- package/dist/cdn/cloudflare.d.ts +20 -0
- package/dist/{chunk-2m09t0c0.js → chunk-6v4k9ekm.js} +2 -2
- package/dist/{chunk-rcxq9aaa.js → chunk-7pff0rv9.js} +1 -1
- package/dist/chunk-hwan3cev.js +2 -0
- package/dist/{chunk-mch30cyc.js → chunk-m4vqpkpp.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/dns/cloudflare.d.ts +17 -0
- package/dist/dns/godaddy.d.ts +19 -1
- package/dist/dns/index.js +1 -1
- package/dist/dns/zone-migration.d.ts +0 -8
- package/dist/index.js +16 -16
- 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 +5 -5
- 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 +6 -6
- package/dist/ui/data/services.html +5 -5
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +5 -5
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +5 -5
- package/dist/ui/server/database.html +5 -5
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +1 -1
- package/dist/ui/server/firewall.html +5 -5
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +1 -1
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +5 -5
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-0djsffn6.js +0 -1
- package/dist/bin/chunk-0t3sev1j.js +0 -1
- package/dist/bin/chunk-6tct7e89.js +0 -1
- package/dist/bin/chunk-7v5ff3vc.js +0 -1
- package/dist/bin/chunk-80nra92y.js +0 -1
- package/dist/bin/chunk-akbfefwq.js +0 -1
- package/dist/bin/chunk-b704nznp.js +0 -1
- package/dist/bin/chunk-cjz36ths.js +0 -1
- package/dist/bin/chunk-cxd5cevb.js +0 -2
- package/dist/bin/chunk-dxchg0g1.js +0 -1
- package/dist/bin/chunk-g0ewbkbq.js +0 -1
- package/dist/bin/chunk-gvs85t2j.js +0 -1
- package/dist/bin/chunk-khrye4x9.js +0 -1
- package/dist/bin/chunk-memfxrcn.js +0 -1
- package/dist/bin/chunk-pqr8jqnd.js +0 -1
- package/dist/bin/chunk-rfqk5xym.js +0 -1
- package/dist/bin/chunk-wy20ztb6.js +0 -1
- package/dist/bin/chunk-xcqmwphz.js +0 -1
- package/dist/chunk-qtp90j44.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{md as Z,rd as L,sd as Y,td as _,ud as K}from"./chunk-mfrf9q4b.js";import{wd as U}from"./chunk-82mj52xr.js";import{jg as W}from"./chunk-a7w13qfm.js";import{og as M}from"./chunk-e5ab5twy.js";import{qg as B}from"./chunk-btsyjhk7.js";import{op as j}from"./chunk-ehc63fvs.js";function J(t){let{bucketName:s,domain:l,aliases:e,certificateArn:m,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:b=!1,computeOriginDomain:k,computeOriginPort:R=3008,computeOriginId:P="app-compute",retainOnStackDelete:x=!1}=t,A=x?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=b&&!!k,T=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],F=y?["GET","HEAD"]:["GET","HEAD"],N={},O={};N.S3Bucket={Type:"AWS::S3::Bucket",...A,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},O.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},O.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},N.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...A,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let D;if(a&&y)D="InstallRootRedirectFunction",N[D]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
2
2
|
var request = event.request;
|
|
3
3
|
if (request.uri === '/' || request.uri === '') {
|
|
4
4
|
return {
|
|
@@ -42,7 +42,7 @@ import{ld as Z,qd as L,rd as Y,sd as _,td as K}from"./chunk-cxd5cevb.js";import{
|
|
|
42
42
|
│ │
|
|
43
43
|
│ Verification typically takes 1-2 business days. │
|
|
44
44
|
│ After verification, re-run: bunx bunpress deploy │
|
|
45
|
-
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:O,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:O,stackName:i,bucket:y,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],C=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,f=C("DistributionDomain");if(f&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,f);else if(f&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:O,stackName:i,bucket:C("BucketName")||y,distributionId:C("DistributionId"),distributionDomain:f,domain:e,certificateArn:b,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let b of d.records){let k=b.name.replace(/\.$/,"");if(k===s||k==="")console.log(`Removing existing root A record (${b.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:b.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function le(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(b){console.log(`Note: Could not clean bucket: ${b.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-
|
|
45
|
+
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:O,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:O,stackName:i,bucket:y,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],C=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,f=C("DistributionDomain");if(f&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,f);else if(f&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:O,stackName:i,bucket:C("BucketName")||y,distributionId:C("DistributionId"),distributionDomain:f,domain:e,certificateArn:b,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let b of d.records){let k=b.name.replace(/\.$/,"");if(k===s||k==="")console.log(`Removing existing root A record (${b.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:b.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function le(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(b){console.log(`Note: Could not clean bucket: ${b.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-zdt2rjk6.js"),a=await r({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(b,k,R)=>{e?.("upload",`${b}/${k}: ${R}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:b}=await import("./chunk-zdt2rjk6.js");await b(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Q(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:m,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
46
46
|
const request = event.request;
|
|
47
47
|
var uri = request.uri;
|
|
48
48
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ch as U,dh as L}from"./chunk-ja1vjdn1.js";import{op as K}from"./chunk-ehc63fvs.js";import*as c from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as z}from"node:fs/promises";import{join as M}from"node:path";function R(e){if(e){let r=O(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return O(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function O(e){let{existsSync:t,readFileSync:s}=K("node:fs"),{homedir:r}=K("node:os"),{join:n}=K("node:path"),i=process.env.AWS_SHARED_CREDENTIALS_FILE||n(r(),".aws","credentials");if(!t(i))return null;let o=s(i,"utf-8"),a=null,g,l,u;for(let d of o.split(`
|
|
2
2
|
`)){let y=d.trim();if(!y||y.startsWith("#")||y.startsWith(";"))continue;let h=y.match(/^\[([^\]]+)\]$/);if(h){if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:u};a=h[1],g=void 0,l=void 0,u=void 0;continue}if(a===e){let[S,...m]=y.split("="),p=m.join("=").trim();switch(S.trim().toLowerCase()){case"aws_access_key_id":g=p;break;case"aws_secret_access_key":l=p;break;case"aws_session_token":u=p;break}}}if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:u};return null}function B(e){let{buffer:t,byteOffset:s,byteLength:r}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+r);let n=new ArrayBuffer(r);return new Uint8Array(n).set(new Uint8Array(e)),n}class V{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let r=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",i=typeof e==="string"?t:e.profile,o=r?.endpoint?U({region:n,path:"/",endpoint:r.endpoint}):void 0;this.region=n,this.explicitProfile=i,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=r?.forcePathStyle,this.explicitCredentials=r?.credentials,this.client=new L(r?.credentials,{profile:i,endpoint:r?.endpoint,forcePathStyle:r?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=R(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],r=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(r){let n=Array.isArray(r)?r:[r];for(let i of n)t.push({Name:i.Name,CreationDate:i.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let r;if(this.region!=="us-east-1"&&!this.endpoint)r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
4
4
|
<LocationConstraint>${this.region}</LocationConstraint>
|
|
@@ -89,4 +89,4 @@ host:${o}
|
|
|
89
89
|
${t.map((n)=>`<Object><Key>${n.Key}</Key>${n.VersionId?`<VersionId>${n.VersionId}</VersionId>`:""}</Object>`).join(`
|
|
90
90
|
`)}
|
|
91
91
|
</Delete>`,r=c.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":r}})}}
|
|
92
|
-
export{R as
|
|
92
|
+
export{R as pg,V as qg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ch as d}from"./chunk-0y89hs67.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let p=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(p,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class C{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new d(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
|
|
2
|
-
export{C as
|
|
1
|
+
import{dh as d}from"./chunk-ja1vjdn1.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let p=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(p,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class C{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new d(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
|
|
2
|
+
export{C as _d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{if as lt}from"./chunk-mwgxyc0z.js";import{Bg as Lr,Dg as _}from"./chunk-ww770qpn.js";var si=["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"],Ve={"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}},ai=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],D={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var ci=1e6;function Vr(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function Rt(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,o=0,i=0;for(let s of r){if(n<=0)break;let d=(s.upToQuantity===null?1/0:s.upToQuantity)-o;if(d<=0)continue;let c=Math.min(n,d);i+=c*s.microCentsPerUnit,n-=c,o+=c}if(n>0){let s=r.reduce((a,d)=>Math.max(a,d.microCentsPerUnit),0);i+=n*s}return i}function Br(e,t,r,n){let o=e.entries.filter((a)=>a.meter===t);if(o.length===0)return;let i=o.filter((a)=>a.provider===r),s=i.length>0?i:o.filter((a)=>a.provider==="*");return s.find((a)=>a.region===n)??s.find((a)=>a.region==null)}function Be(e,t,r=0){let n=Br(e,t.meter,t.provider,t.region),o=Math.max(0,t.quantity);if(!n)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:o,includedQuantity:0,billableQuantity:o,costCents:0,unpriced:!0};let i=Math.max(0,n.includedQuantity??0),s=Math.max(0,r-i),a=Math.max(0,i-Math.max(0,r)),d=Math.min(o,a),c=o-d,u=Vr(n),m=Rt(s+c,u)-Rt(s,u);return{meter:t.meter,provider:n.provider,region:n.region??t.region,quantity:o,includedQuantity:d,billableQuantity:c,costCents:m/1e6,unpriced:!1}}function li(e,t){let r=new Map,n=[];for(let o of t){let i=`${o.meter}\x00${o.provider??""}\x00${o.region??""}`,s=r.get(i)??0,a=Be(e,o,s);r.set(i,s+a.quantity),n.push(a)}return{currency:e.currency,totalCents:n.reduce((o,i)=>o+i.costCents,0),lines:n,unpricedMeters:[...new Set(n.filter((o)=>o.unpriced).map((o)=>String(o.meter)))]}}function ui(e){return Math.round(e*100)/100}function mi(e,...t){let r=new Map,n=(i)=>`${i.meter}\x00${i.provider}\x00${i.region??""}`;for(let i of e.entries)r.set(n(i),i);let o=e.currency;for(let i of t){o=i.currency||o;for(let s of i.entries)r.set(n(s),s)}return{currency:o,entries:[...r.values()]}}var B=(e)=>Math.round(e*1e6),N=(e)=>Math.round(e*1e6),Ct={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:N(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:B(8.5)},{upToQuantity:51200,microCentsPerUnit:B(8)},{upToQuantity:null,microCentsPerUnit:B(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:N(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:N(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:N(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:B(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:N(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:N(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:N(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:B(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:B(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:N(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:N(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:N(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:B(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:N(0.05)}]};var Pt=new Map;function Tt(e){let t=Pt.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"}),Pt.set(e,t);return t}var zr={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function Se(e){try{return Tt(e),!0}catch{return!1}}function ze(e,t){let r=Tt(t).formatToParts(e),n=(o)=>r.find((i)=>i.type===o)?.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:zr[n("weekday")]??0}}function kt(e,t){let r=ze(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 W(e,t,r,n,o=0){let i=Date.UTC(t,r-1,n,o),s=new Date(i-kt(new Date(i),e));return new Date(i-kt(s,e))}function Ur(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function z(e,t,r=new Date){let n=Se(t)?t:"UTC",o=ze(r,n),i,s,a;if(e==="daily")i=W(n,o.year,o.month,o.day),s=W(n,o.year,o.month,o.day+1),a=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`;else if(e==="weekly"){let u=(o.weekday+6)%7;i=W(n,o.year,o.month,o.day-u),s=W(n,o.year,o.month,o.day-u+7);let m=ze(i,n);a=`week of ${m.year}-${String(m.month).padStart(2,"0")}-${String(m.day).padStart(2,"0")}`}else i=W(n,o.year,o.month,1),s=W(n,o.year,o.month+1,1),a=Ur(o.year,o.month);let d=s.getTime()-i.getTime(),c=Math.max(0,Math.min(d,r.getTime()-i.getTime()));return{start:i.toISOString(),end:s.toISOString(),elapsedMs:c,totalMs:d,label:a}}function gi(e,t,r=new Date){let n=z(e,t,r),o=new Date(new Date(n.start).getTime()-1),i=z(e,t,o);return{...i,elapsedMs:i.totalMs}}function ne(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 hi(e,t,r=9600){let n=Math.floor(new Date(e).getTime()/3600000)*3600000,o=new Date(t).getTime();if(!Number.isFinite(n)||!Number.isFinite(o))throw Error("hourBucketsBetween requires valid dates");let i=[];for(let s=n;s<o&&i.length<r;s+=3600000)i.push(new Date(s).toISOString());return i}import{createHash as Fr}from"node:crypto";var Ie=1073741824,Ot=[{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/Ie},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/Ie},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/Ie,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/Ie},{match:"image.transform",meter:"image.transformations",field:"count"}];function Hr(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function Qr(e,t=Ot){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>Hr(r,e))}function Jr(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 Wr(e,t){return Fr("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class Ue{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(),o=this.last.get(e);if(!o)return this.last.set(e,{value:t,at:n}),t>0?t:void 0;if(n<o.at)return;if(t<o.value&&t>=o.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:n}),t>=o.value){let i=t-o.value;return i>0?i:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[n,o]of this.last)if(o.at<t)this.last.delete(n),r++;return r}get size(){return this.last.size}}function Dt(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function xt(e,t,r={}){let n=r.mappings??Ot,o=r.counters,i=[];for(let s of t){let a=Qr(s.name,n);if(!a)continue;let d=Jr(s,a);if(d==null)continue;if(a.cumulative){if(!o)continue;let u=[s.projectId,s.environmentId??"",s.resourceId??"",s.name,s.source].join("\x00"),m=o.delta(u,d,s.timestamp);if(m==null)continue;d=m}if(!(d>0))continue;let c={organizationId:e,projectId:s.projectId,environmentId:s.environmentId,resourceId:s.resourceId,provider:Dt(s.attributes,"provider")??r.defaultProvider,region:s.region??Dt(s.attributes,"region"),meter:a.meter,quantity:d,timestamp:s.timestamp,attributes:{source:s.source,signal:s.name}};i.push({...c,key:Wr(c,s.id)})}return i}function Nt(e){let t=new Map;for(let r of e){let n=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),o=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,n].join("\x00"),i=t.get(o);if(i)i.quantity+=r.quantity;else t.set(o,{...r,timestamp:n})}return[...t.values()]}import{createHash as Kr}from"node:crypto";var oe=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},j=(e)=>typeof e==="string"&&e!==""?e:void 0,_e=(e)=>Number(e)===1,jt=(e)=>e==null?void 0:Number(e);function Mt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:jt(e.soft_limit_cents),hardLimitCents:jt(e.hard_limit_cents),thresholds:oe(e.thresholds),meters:oe(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:_e(e.dry_run),enabled:_e(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Fe(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:oe(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:_e(e.simulated),appliedAt:j(e.applied_at),releasedAt:j(e.released_at),error:j(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Lt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(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:oe(e.evidence),acknowledgedAt:j(e.acknowledged_at),createdAt:String(e.created_at)}}function Gr(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 U(e,t,r){return[e,t??"",r??""].join("/")}var Yr=[{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 Zr{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??Ct}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(!Se(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...Yr]).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 o=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,?,?)",[o,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,i,i]),this.getBudget(o)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?Mt(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(Mt)}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,o)=>Number(!!n.projectId)-Number(!!o.projectId)||Number(!!n.environmentId)-Number(!!o.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 o={...n,...t};if(o.softLimitCents==null&&o.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(o.softLimitCents!=null&&o.hardLimitCents!=null&&o.softLimitCents>o.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!Se(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=?",[o.name,o.period,o.timezone,o.currency??"USD",o.softLimitCents??null,o.hardLimitCents??null,JSON.stringify(o.thresholds??[]),JSON.stringify(o.meters??[]),Math.max(0,Math.floor(o.graceSeconds??0)),Math.max(0,o.hysteresisPercent??5),o.dryRun?1:0,o.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((i)=>{for(let s of i){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,ne(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??""},u=this.periodQuantity(s),m=Be(this.priceBook,{meter:s.meter,quantity:s.quantity,provider:s.provider,region:s.region},u);if(m.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)
|
|
1
|
+
import{jf as lt}from"./chunk-8khgprf6.js";import{Cg as Lr,Eg as _}from"./chunk-dz1ec589.js";var si=["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"],Ve={"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}},ai=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],D={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var ci=1e6;function Vr(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function Rt(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,o=0,i=0;for(let s of r){if(n<=0)break;let d=(s.upToQuantity===null?1/0:s.upToQuantity)-o;if(d<=0)continue;let c=Math.min(n,d);i+=c*s.microCentsPerUnit,n-=c,o+=c}if(n>0){let s=r.reduce((a,d)=>Math.max(a,d.microCentsPerUnit),0);i+=n*s}return i}function Br(e,t,r,n){let o=e.entries.filter((a)=>a.meter===t);if(o.length===0)return;let i=o.filter((a)=>a.provider===r),s=i.length>0?i:o.filter((a)=>a.provider==="*");return s.find((a)=>a.region===n)??s.find((a)=>a.region==null)}function Be(e,t,r=0){let n=Br(e,t.meter,t.provider,t.region),o=Math.max(0,t.quantity);if(!n)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:o,includedQuantity:0,billableQuantity:o,costCents:0,unpriced:!0};let i=Math.max(0,n.includedQuantity??0),s=Math.max(0,r-i),a=Math.max(0,i-Math.max(0,r)),d=Math.min(o,a),c=o-d,u=Vr(n),m=Rt(s+c,u)-Rt(s,u);return{meter:t.meter,provider:n.provider,region:n.region??t.region,quantity:o,includedQuantity:d,billableQuantity:c,costCents:m/1e6,unpriced:!1}}function li(e,t){let r=new Map,n=[];for(let o of t){let i=`${o.meter}\x00${o.provider??""}\x00${o.region??""}`,s=r.get(i)??0,a=Be(e,o,s);r.set(i,s+a.quantity),n.push(a)}return{currency:e.currency,totalCents:n.reduce((o,i)=>o+i.costCents,0),lines:n,unpricedMeters:[...new Set(n.filter((o)=>o.unpriced).map((o)=>String(o.meter)))]}}function ui(e){return Math.round(e*100)/100}function mi(e,...t){let r=new Map,n=(i)=>`${i.meter}\x00${i.provider}\x00${i.region??""}`;for(let i of e.entries)r.set(n(i),i);let o=e.currency;for(let i of t){o=i.currency||o;for(let s of i.entries)r.set(n(s),s)}return{currency:o,entries:[...r.values()]}}var B=(e)=>Math.round(e*1e6),N=(e)=>Math.round(e*1e6),Ct={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:N(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:B(8.5)},{upToQuantity:51200,microCentsPerUnit:B(8)},{upToQuantity:null,microCentsPerUnit:B(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:N(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:N(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:N(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:B(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:N(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:N(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:N(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:B(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:B(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:N(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:N(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:N(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:B(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:N(0.05)}]};var Pt=new Map;function Tt(e){let t=Pt.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"}),Pt.set(e,t);return t}var zr={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function Se(e){try{return Tt(e),!0}catch{return!1}}function ze(e,t){let r=Tt(t).formatToParts(e),n=(o)=>r.find((i)=>i.type===o)?.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:zr[n("weekday")]??0}}function kt(e,t){let r=ze(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 W(e,t,r,n,o=0){let i=Date.UTC(t,r-1,n,o),s=new Date(i-kt(new Date(i),e));return new Date(i-kt(s,e))}function Ur(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function z(e,t,r=new Date){let n=Se(t)?t:"UTC",o=ze(r,n),i,s,a;if(e==="daily")i=W(n,o.year,o.month,o.day),s=W(n,o.year,o.month,o.day+1),a=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`;else if(e==="weekly"){let u=(o.weekday+6)%7;i=W(n,o.year,o.month,o.day-u),s=W(n,o.year,o.month,o.day-u+7);let m=ze(i,n);a=`week of ${m.year}-${String(m.month).padStart(2,"0")}-${String(m.day).padStart(2,"0")}`}else i=W(n,o.year,o.month,1),s=W(n,o.year,o.month+1,1),a=Ur(o.year,o.month);let d=s.getTime()-i.getTime(),c=Math.max(0,Math.min(d,r.getTime()-i.getTime()));return{start:i.toISOString(),end:s.toISOString(),elapsedMs:c,totalMs:d,label:a}}function gi(e,t,r=new Date){let n=z(e,t,r),o=new Date(new Date(n.start).getTime()-1),i=z(e,t,o);return{...i,elapsedMs:i.totalMs}}function ne(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 hi(e,t,r=9600){let n=Math.floor(new Date(e).getTime()/3600000)*3600000,o=new Date(t).getTime();if(!Number.isFinite(n)||!Number.isFinite(o))throw Error("hourBucketsBetween requires valid dates");let i=[];for(let s=n;s<o&&i.length<r;s+=3600000)i.push(new Date(s).toISOString());return i}import{createHash as Fr}from"node:crypto";var Ie=1073741824,Ot=[{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/Ie},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/Ie},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/Ie,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/Ie},{match:"image.transform",meter:"image.transformations",field:"count"}];function Hr(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function Qr(e,t=Ot){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>Hr(r,e))}function Jr(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 Wr(e,t){return Fr("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class Ue{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(),o=this.last.get(e);if(!o)return this.last.set(e,{value:t,at:n}),t>0?t:void 0;if(n<o.at)return;if(t<o.value&&t>=o.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:n}),t>=o.value){let i=t-o.value;return i>0?i:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[n,o]of this.last)if(o.at<t)this.last.delete(n),r++;return r}get size(){return this.last.size}}function Dt(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function xt(e,t,r={}){let n=r.mappings??Ot,o=r.counters,i=[];for(let s of t){let a=Qr(s.name,n);if(!a)continue;let d=Jr(s,a);if(d==null)continue;if(a.cumulative){if(!o)continue;let u=[s.projectId,s.environmentId??"",s.resourceId??"",s.name,s.source].join("\x00"),m=o.delta(u,d,s.timestamp);if(m==null)continue;d=m}if(!(d>0))continue;let c={organizationId:e,projectId:s.projectId,environmentId:s.environmentId,resourceId:s.resourceId,provider:Dt(s.attributes,"provider")??r.defaultProvider,region:s.region??Dt(s.attributes,"region"),meter:a.meter,quantity:d,timestamp:s.timestamp,attributes:{source:s.source,signal:s.name}};i.push({...c,key:Wr(c,s.id)})}return i}function Nt(e){let t=new Map;for(let r of e){let n=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),o=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,n].join("\x00"),i=t.get(o);if(i)i.quantity+=r.quantity;else t.set(o,{...r,timestamp:n})}return[...t.values()]}import{createHash as Kr}from"node:crypto";var oe=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},j=(e)=>typeof e==="string"&&e!==""?e:void 0,_e=(e)=>Number(e)===1,jt=(e)=>e==null?void 0:Number(e);function Mt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:jt(e.soft_limit_cents),hardLimitCents:jt(e.hard_limit_cents),thresholds:oe(e.thresholds),meters:oe(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:_e(e.dry_run),enabled:_e(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Fe(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:oe(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:_e(e.simulated),appliedAt:j(e.applied_at),releasedAt:j(e.released_at),error:j(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Lt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(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:oe(e.evidence),acknowledgedAt:j(e.acknowledged_at),createdAt:String(e.created_at)}}function Gr(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 U(e,t,r){return[e,t??"",r??""].join("/")}var Yr=[{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 Zr{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??Ct}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(!Se(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...Yr]).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 o=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,?,?)",[o,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,i,i]),this.getBudget(o)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?Mt(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(Mt)}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,o)=>Number(!!n.projectId)-Number(!!o.projectId)||Number(!!n.environmentId)-Number(!!o.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 o={...n,...t};if(o.softLimitCents==null&&o.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(o.softLimitCents!=null&&o.hardLimitCents!=null&&o.softLimitCents>o.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!Se(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=?",[o.name,o.period,o.timezone,o.currency??"USD",o.softLimitCents??null,o.hardLimitCents??null,JSON.stringify(o.thresholds??[]),JSON.stringify(o.meters??[]),Math.max(0,Math.floor(o.graceSeconds??0)),Math.max(0,o.hysteresisPercent??5),o.dryRun?1:0,o.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((i)=>{for(let s of i){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,ne(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??""},u=this.periodQuantity(s),m=Be(this.priceBook,{meter:s.meter,quantity:s.quantity,provider:s.provider,region:s.region},u);if(m.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)
|
|
2
2
|
VALUES (?,?,?,?,?,?,?,?,?,?,1,?)
|
|
3
3
|
ON CONFLICT(organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start) DO UPDATE SET
|
|
4
4
|
quantity = quantity + excluded.quantity,
|
|
@@ -108,4 +108,4 @@ volumes:
|
|
|
108
108
|
`).map((i)=>i.trim()).filter(Y.test.bind(Y))){let i=await this.inspect(o);if(i)n.push(i)}return n}async create(e){let t=typeof e.desiredState.nativeName==="string"?e.desiredState.nativeName:e.name;if(!Y.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||!Y.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(`
|
|
109
109
|
`).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 Qo{provider="server";type="server_path";root;constructor(e){this.root=Or(e)}capabilities(){return ft(["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(!Y.test(e))throw Error("Server path volume name is invalid.");let t=Or(this.root,e);if(!t.startsWith(`${this.root}${Fo}`)||Uo(t)!==e)throw Error("Server path escaped the managed volume root.");return t}async discover(e,t){return await yt(this.root,{recursive:!0,mode:488}),(await Vo(this.root,{withFileTypes:!0})).filter((n)=>n.isDirectory()&&Y.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 yt(this.root,{recursive:!0,mode:488}),await yt(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 Bo(this.path(e.providerId),{recursive:!0,force:!1})}async usage(e){if(!e.providerId)return{};return{usedBytes:(await zo(this.path(e.providerId))).size}}}var T=(e)=>e==null?void 0:String(e),ve=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},St=(e)=>Number(e)===1,Z=(e)=>e().toISOString();function xr(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:T(e.environment_id),resourceId:T(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:T(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:T(e.filesystem),encrypted:St(e.encrypted),capabilities:ve(e.capabilities,{}),desiredState:ve(e.desired_state,{}),observedState:ve(e.observed_state,{}),backupPolicyId:T(e.backup_policy_id),lastBackupAt:T(e.last_backup_at),orphanedAt:T(e.orphaned_at),adoptedAt:T(e.adopted_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:T(e.deleted_at)}}function bt(e){return{id:String(e.id),volumeId:String(e.volume_id),resourceId:String(e.resource_id),targetPath:String(e.target_path),readOnly:St(e.read_only),uid:e.uid==null?void 0:Number(e.uid),gid:e.gid==null?void 0:Number(e.gid),mode:T(e.mode),propagation:String(e.propagation),driverOptions:ve(e.driver_options,{}),desiredState:String(e.desired_state),observedState:String(e.observed_state),operationId:T(e.operation_id),lastError:T(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Nr(e){return{id:String(e.id),volumeId:String(e.volume_id),recoveryPointId:T(e.recovery_point_id),providerId:T(e.provider_id),name:String(e.name),status:String(e.status),sizeBytes:e.size_bytes==null?void 0:Number(e.size_bytes),encrypted:St(e.encrypted),checksum:T(e.checksum),metadata:ve(e.metadata,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:T(e.deleted_at)}}class je{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?xr(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(xr)}create(e){let t=Z(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 o={...n,...r,updatedAt:Z(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=?",[o.environmentId??null,o.resourceId??null,o.name,o.provider,o.providerId??null,o.type,o.status,o.capacityBytes??null,o.usedBytes??null,o.filesystem??null,o.encrypted?1:0,JSON.stringify(o.capabilities),JSON.stringify(o.desiredState),JSON.stringify(o.observedState),o.backupPolicyId??null,o.lastBackupAt??null,o.orphanedAt??null,o.adoptedAt??null,o.deletedAt??null,o.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(bt)}attachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE id=?").get(e);return t?bt(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=Z(this.now);if(t){let o=bt(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,o.id]),this.attachment(o.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,Z(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(Nr)}snapshot(e){let t=this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE id=?").get(e);return t?Nr(t):void 0}createSnapshot(e){let t=e.id??this.id(),r=Z(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,Z(this.now),e]),this.snapshot(e)}inventory(e,t){return this.list({projectId:e,environmentId:t}).map((r)=>{let n=this.attachments(r.id),o=this.snapshots(r.id),i=r.lastBackupAt?Date.now()-new Date(r.lastBackupAt).getTime():1/0;return{...r,attachments:n,snapshots:o,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 It(e,t){let r=e.getProject(t.projectId);if(!r?.organizationId)return;let n=new je(e),o=new vt,i=new Set(t.manifest.spec.volumes),s=new Set;for(let a of i){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((g)=>g.name===d);if(c?.deletedAt)throw Error(`Compose volume ${d} was permanently deleted; rename it before redeploying.`);let u=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}}),m=c??n.create({organizationId:r.organizationId,projectId:t.projectId,environmentId:t.environmentId,resourceId:u?.id,name:d,provider:"docker",providerId:d,type:"docker",status:"available",encrypted:!1,capabilities:o.capabilities(),desiredState:{composeApplicationId:t.id,composeVolume:a,nativeName:d},observedState:{}});s.add(m.id);let l=new Map;for(let g of Object.values(t.manifest.spec.services))for(let p of g.volumes.filter((h)=>h.source===a)){let h=l.get(p.target)??[];h.push(g.name),l.set(p.target,h),n.upsertAttachment({volumeId:m.id,resourceId:t.resourceId,targetPath:p.target,readOnly:p.readOnly,propagation:"private",driverOptions:{composeServices:h},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 jr(e,t,r){let n=new je(e);for(let o of n.list({projectId:t.projectId,environmentId:t.environmentId}).filter((i)=>i.desiredState.composeApplicationId===t.id)){for(let i of n.attachments(o.id))n.updateAttachment(i.id,{desiredState:"detached",observedState:"detached"});n.update(o.id,o.version,{status:r?"deleted":"available",deletedAt:r?new Date().toISOString():void 0})}}function X(e){return typeof e==="string"&&e?e:void 0}function _t(e,t){try{return JSON.parse(String(e))}catch{return t}}function Me(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:_t(e.manifest,{}),diagnostics:_t(e.diagnostics,[]),templateId:X(e.template_id),templateVersion:X(e.template_version),latestOperationId:X(e.latest_operation_id),createdByActorId:X(e.created_by_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:X(e.deleted_at)}}function Jo(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:X(e.latest_operation_id),observedState:_t(e.observed_state,{}),updatedAt:String(e.updated_at)}}class J{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((p)=>p.severity==="error").length} blocking diagnostic(s)`);let{projectId:r,environmentId:n,name:o,slug:i}=e.manifest.metadata;if(!this.controlPlane.listEnvironments(r).find((p)=>p.id===n))throw Error("Compose project and environment scope was not found");let a=this.getBySlug(r,n,i),d=this.now().toISOString(),c=JSON.stringify(e.manifest),u=JSON.stringify(_(e.diagnostics));if(a){if(a.status==="deleted")throw Error("A deleted Compose application cannot be overwritten; choose another slug");let p=this.controlPlane.getResource(a.resourceId);if(!p)throw Error("Compose application resource was not found");this.controlPlane.updateResource(p.id,p.version,{name:o,provider:p.provider,providerId:p.providerId,desiredState:e.manifest,discoveredState:p.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=?",[o,t.sourceKind,e.sourceHash,e.redactedSource,c,u,t.templateId??null,t.templateVersion??null,d,a.id]);let h=Object.keys(e.manifest.spec.services);if(h.length)this.controlPlane.database.run(`DELETE FROM compose_service_states WHERE application_id=? AND service_name NOT IN (${h.map(()=>"?").join(",")})`,[a.id,...h]);for(let y 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,y.name,y.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 f=this.get(a.id);return It(this.controlPlane,f),f}let m=this.controlPlane.createResource({projectId:r,environmentId:n,kind:"compose_application",slug:i,name:o,desiredState:e.manifest,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),l=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', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[l,m.id,r,n,o,i,t.sourceKind,e.sourceHash,e.redactedSource,c,u,t.templateId??null,t.templateVersion??null,t.createdByActorId??null,d,d]);for(let p 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, '{}', ?)",[l,p.name,p.replicas,d]);this.controlPlane.appendEvent({projectId:r,resourceId:m.id,actorId:t.createdByActorId,type:"compose.application.created",payload:{applicationId:l,sourceHash:e.sourceHash,serviceNames:Object.keys(e.manifest.spec.services),templateId:t.templateId??null}});let g=this.get(l);return It(this.controlPlane,g),g}import(e,t){let r=G(e,t);return{application:this.persist(r,{sourceKind:"compose",createdByActorId:t.createdByActorId}),parsed:r}}fromTemplate(e,t,r){let n=Dr(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 G(e,t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE id=?").get(e);return t?Me(t):void 0}getByResource(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE resource_id=?").get(e);return t?Me(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?Me(n):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM compose_applications ORDER BY updated_at DESC").all().map(Me).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(Jo)}transition(e,t,r={}){let n=this.get(e);if(!n)throw Error(`Compose application ${e} was not found`);let o=this.now().toISOString(),i=t==="deleted"?o: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,o,i,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(_(s.observedState??{})),o]);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 Wo{controlPlane;applications;queue;constructor(e){this.controlPlane=e;this.applications=new J(e),this.queue=new q(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 o=r.removeVolumes?`${e.slug} delete volumes`:e.slug;if(r.confirmation!==o)throw Error(`Type ${o} 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 Ko}from"node:crypto";var Go=/^[a-f0-9]{40,64}$/i,Yo=/^[A-Z][A-Z0-9_]{1,127}$/;function L(e){return typeof e==="string"&&e?e:void 0}function ee(e){try{return JSON.parse(String(e))}catch{return{}}}function Zo(e){let t=ee(e);return Array.isArray(t)?t.map(String):[]}function Et(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:L(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:Zo(e.inherited_secrets),resourceOverrides:ee(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:L(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function be(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:L(e.source_provider),repository:L(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:L(e.url),status:String(e.status),expiresAt:String(e.expires_at),latestOperationId:L(e.latest_operation_id),createdByActorId:L(e.created_by_actor_id),costEstimate:e.cost_estimate==null?void 0:Number(e.cost_estimate),desiredState:ee(e.desired_state),observedState:ee(e.observed_state),teardownError:L(e.teardown_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),destroyedAt:L(e.destroyed_at)}}function Mr(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:ee(e.tags),observedState:ee(e.observed_state),discoveredAt:String(e.discovered_at),deletedAt:L(e.deleted_at)}}function V(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,Math.floor(e))):t}function Le(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,e)):t}function wt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,28)||"preview"}class te{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),o=e.publicAccess??n?.publicAccess??!1,i=e.authenticationRequired??n?.authenticationRequired??!0;if(o&&!i)throw Error("Public preview environments require an authentication policy");let s=[...new Set(e.inheritedSecrets??[])];if(s.some((c)=>!Yo.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),o?1:0,i?1:0,e.allowForks??n.allowForks?1:0,JSON.stringify(e.inheritedSecrets===void 0?n.inheritedSecrets:s),JSON.stringify(_(e.resourceOverrides??n.resourceOverrides)),e.databaseStrategy??n.databaseStrategy,Le(e.maxMonthlyCost,n.maxMonthlyCost,0,1e4),Le(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(_(e.resourceOverrides??{})),e.databaseStrategy??"disabled",Le(e.maxMonthlyCost,25,0,1e4),Le(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?Et(t):void 0}getDefinitionForResource(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE resource_id=?").get(e);return t?Et(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(Et)}listInstances(e={}){return this.controlPlane.database.query("SELECT * FROM preview_instances ORDER BY created_at DESC").all().map(be).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?be(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?be(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?be(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(!Go.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=Ko("sha256").update(`${t.id}:${r}`).digest("hex").slice(0,8),i=`${(e.pullRequestNumber?`pr-${e.pullRequestNumber}`:wt(e.branch)).slice(0,28)}-${n}`,s=`preview-${i}`.slice(0,63),a=t.domainPattern.replaceAll("{name}",i).replaceAll("{project}",wt(t.projectId)).replaceAll("{branch}",wt(e.branch)).replaceAll("{pr}",String(e.pullRequestNumber??"branch")),d=e.now??this.now(),c=d.toISOString(),u=new Date(d.getTime()+t.ttlHours*60*60*1000).toISOString(),m=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(t.id,r);if(m){let p=be(m),h=p.commitSha!==e.commitSha||p.status==="destroyed";if(h)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,u,a,c,p.id]);return{preview:this.getInstance(p.id),created:!1,changed:h,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}let l=this.id(),g=_({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', ?, ?, ?, ?, ?)",[l,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,s,a,u,e.createdByActorId??null,JSON.stringify(g),c,c]),this.controlPlane.appendEvent({projectId:t.projectId,resourceId:t.resourceId,actorId:e.createdByActorId,type:"preview.created",payload:{previewId:l,identityKey:r,commitSha:e.commitSha,expiresAt:u,fork:!!e.fork}}),{preview:this.getInstance(l),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 o=this.now().toISOString(),i=t==="destroyed"?o: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(_(r.observedState??n.observedState)),r.teardownError??null,r.costEstimate??null,i,o,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 o=this.now(),i=V(t,n.ttlHours,1,720),s=new Date(Math.max(o.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=?",[s,o.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(),o=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(_(e.observedState??{})),o]);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 Mr(i)}listResources(e){return this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? ORDER BY kind, provider_resource_id").all(e).map(Mr)}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 Xo{controlPlane;previews;queue;constructor(e){this.controlPlane=e;this.previews=new te(e),this.queue=new q(e)}enqueueDeploy(e,t={}){let r=t.created?"preview.create":"preview.update",n=t.reason==="manual_rebuild"?`:${crypto.randomUUID()}`:"",o=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:o.id}),o}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)),o=(d,c)=>{let u=r.get(d.id)??{preview:d,reasons:[]};if(!u.reasons.includes(c))u.reasons.push(c);r.set(d.id,u)};for(let d of n){if(new Date(d.expiresAt)<=t)o(d,"ttl_expired");if(e.maxAgeHours&&t.getTime()-new Date(d.createdAt).getTime()>=e.maxAgeHours*3600000)o(d,"max_age")}let i=new Map;for(let d of n)i.set(d.definitionId,[...i.get(d.definitionId)??[],d]);for(let[d,c]of i){let u=this.previews.getDefinition(d),m=e.keepCount??u?.keepCount;if(!m)continue;c.sort((l,g)=>g.createdAt.localeCompare(l.createdAt)).slice(m).forEach((l)=>o(l,"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 o of e){let i=o.tags["ts-cloud:preview"],s=o.tags["ts-cloud:project"],a=o.tags["ts-cloud:expires-at"];if(!i||!s||!a){n.push(o.providerResourceId);continue}let d=this.previews.getInstance(i);if(!d||d.projectId!==s||d.expiresAt!==a){r.push(o.providerResourceId);continue}if(this.previews.recordResource({...o,previewId:d.id}),o.estimatedMonthlyCost!==void 0)this.previews.transition(d.id,d.status,{costEstimate:o.estimatedMonthlyCost,observedState:{...d.observedState,lastReconciledAt:new Date().toISOString()}});t.push(o.providerResourceId)}if(r.length)this.controlPlane.appendEvent({type:"preview.reconciliation.leaks",level:"error",payload:{providerResourceIds:r}});return{matched:t,unknownPreviewResources:r,ignoredUntagged:n}}}var ei=["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 qe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function ti(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 o=qe(t.input);if(t.kind.startsWith("compose.")){let s=typeof o.applicationId==="string"?o.applicationId:void 0,a=s?new J(e).get(s):t.resourceId?new J(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 o.service==="string"&&o.service)c.push("--service",o.service);if(typeof o.replicas==="number")c.push("--replicas",String(o.replicas));if(o.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 o.previewId==="string"?o.previewId:void 0,a=s?new te(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 o.revision==="string"&&o.revision)s.push("--to",o.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 i=["deploy","--env",r.slug,"--yes"];if(n)i.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:i,mutates:!0,target:{environment:r.slug,resource:n?.slug}}}function ri(e){let t=e.stderr?.trim()||`Deployment process exited with code ${e.exitCode}`;if(/\b(?:429|rate.?limit|throttl)/i.test(t))return new H(t,"provider_throttled");if(/\b(?:502|503|504|temporar(?:y|ily)|unavailable|provider.?error)/i.test(t))return new H(t,"provider_unavailable");if(/\b(?:network|econn|enotfound|socket|timed?\s*out|fetch failed|dns)\b/i.test(t))return new H(t,"network");return Error(t)}function Xa(e){let t=async(r)=>{r.checkpoint("prepare","Resolving the persisted deployment target.");let n=ti(e.store,r.operation),o=n.target.previewId?new te(e.store):void 0,i=n.target.composeId?new J(e.store):void 0;if(o&&n.target.previewId)o.transition(n.target.previewId,r.operation.kind==="preview.destroy"?"destroying":r.operation.kind==="preview.update"?"updating":"deploying",{operationId:r.operation.id});if(i&&n.target.composeId)i.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(o&&n.target.previewId)o.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(i&&n.target.composeId)i.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 ri(s)}if(r.throwIfCancellationRequested(),o&&n.target.previewId){let a=o.getInstance(n.target.previewId);if(r.operation.kind==="preview.destroy")o.markResourcesDeleted(a.id),o.transition(a.id,"destroyed",{operationId:r.operation.id,observedState:{reconciledResourceIds:o.listResources(a.id).map((d)=>d.providerResourceId),exactCommitSha:a.commitSha}});else{let d=e.store.getResource(a.resourceId)?.provider??"default";o.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}}),o.transition(a.id,"active",{operationId:r.operation.id,observedState:{url:a.url??null,stackName:a.stackName,exactCommitSha:a.commitSha,providerStatus:"deployed"}})}}if(i&&n.target.composeId){let a=i.get(n.target.composeId),d=typeof qe(r.operation.input).service==="string"?String(qe(r.operation.input).service):void 0,c=r.operation.kind==="compose.delete"?"deleted":r.operation.kind==="compose.stop"?"stopped":"running",u=i.transition(a.id,c,{operationId:r.operation.id,services:Object.values(a.manifest.spec.services).filter((m)=>!d||m.name===d).map((m)=>({name:m.name,status:c==="stopped"||c==="deleted"?"stopped":"running",replicas:c==="deleted"?0:m.replicas,healthyReplicas:c==="running"?m.replicas:0,observedState:{command:s.command??null,healthGatePassed:c==="running"}}))});if(c==="deleted")jr(e.store,u,qe(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(ei.map((r)=>[r,t]))}class S extends Error{code;status;details;constructor(e,t,r,n){super(t);this.code=e;this.status=r;this.details=n}}function At(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 oi(e,t,r){return ni("sha256").update(`${e.toUpperCase()}
|
|
110
110
|
${t}
|
|
111
|
-
${JSON.stringify(r)}`).digest("hex")}class ii{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new q(e),this.spendGate=new de(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||!At(n,r))throw new S("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 S("forbidden",`The token is missing the ${t} capability.`,403);let n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,r),o=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope),i=t==="project:read"&&!!n&&!!o&&At(n,o);if(!n||!o||!At(o,n)&&!i)throw new S("forbidden","The token does not grant access to this resource.",403);let s=i?o:n;if(!Lr({membership:e.membership,grants:this.controlPlane.listGrants(e.membership.id),capability:t,target:s}).allowed)throw new S("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 S("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((o)=>String(o.id)));if(r&&!n.has(r))throw new S("not_found","Environment was not found.",404);return this.controlPlane.listResources(t,r).filter((o)=>!o.environmentId||n.has(o.environmentId)).filter((o)=>{try{return this.authorize(e,"project:read",{type:"resource",id:o.id}),!0}catch{return!1}}).map((o)=>({id:o.id,projectId:o.projectId,environmentId:o.environmentId,kind:o.kind,slug:o.slug,name:o.name,provider:o.provider,providerId:o.providerId,metadata:_(o.metadata),version:o.version,createdAt:o.createdAt,updatedAt:o.updatedAt}))}listOperations(e,t){return this.controlPlane.listOperations({projectId:t,limit:500}).filter((n)=>{let o=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",o),!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 o=n.resourceId?{type:"resource",id:n.resourceId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.target(e,o),!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:_(n.payload),createdAt:n.createdAt}))}createDeployment(e,t,r){if(!this.controlPlane.listEnvironments(t.projectId).find((u)=>u.id===t.environmentId))throw new S("not_found","Environment was not found in this project.",404);let o=t.serviceId?{type:"resource",id:t.serviceId}:{type:"environment",id:t.environmentId};this.authorize(e,"deployments:create",o);let i=this.spendGate.check("deploy",{organizationId:e.serviceAccount.organizationId,projectId:t.projectId,environmentId:t.environmentId});if(!i.allowed)throw new S("spend_cap_exceeded",i.reason??"A spend cap is blocking deployments.",402,{action:i.action,budgetId:i.budgetId});let s=oi("POST","/api/v1/deployments",t),a=this.identities.getIdempotency(e.token.id,r);if(a){if(a.requestHash!==s)throw new S("idempotency_conflict","Idempotency-Key was already used for another request.",409);let u=a.operationId?this.controlPlane.getOperation(a.operationId):void 0;if(!u)throw new S("idempotency_unavailable","The original operation is no longer available.",409);return{operation:this.operation(u),replay:!0}}if(t.serviceId){let u=this.controlPlane.getResource(t.serviceId);if(!u||u.projectId!==t.projectId||u.environmentId!==t.environmentId)throw new S("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:_({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:_(e.input),output:_(e.output),error:e.error,attempt:e.attempt,createdAt:e.createdAt,updatedAt:e.updatedAt,startedAt:e.startedAt,finishedAt:e.finishedAt}}}function $e(e){return e.serviceAccount.organizationId}function qr(e){if(e==null)return;if(e==="daily"||e==="weekly"||e==="monthly")return e;throw new S("validation_error","period must be daily, weekly, or monthly.",422)}function re(e,t){if(e==null)return;let r=Number(e);if(!Number.isFinite(r)||r<0||!Number.isInteger(r))throw new S("validation_error",`${t} must be a non-negative integer.`,422);return r}function k(e,t,r,n,o){if(o)e.authorization.authorize(t,r,{type:"environment",id:o});else if(n)e.authorization.authorize(t,r,{type:"project",id:n});else e.authorization.authorize(t,r,{type:"organization"});return{organizationId:$e(t),projectId:n,environmentId:o}}async function hd(e,t,r){let{method:n,url:o}=r,i=e.now?.()??new Date,s=o.searchParams.get("projectId")??void 0,a=o.searchParams.get("environmentId")??void 0;if(n==="GET"&&o.pathname==="/api/v1/usage"){let l=k(e,t,"billing:read",s,a);return e.service.usageReport({...l,period:qr(o.searchParams.get("period")),timezone:o.searchParams.get("timezone")??void 0,now:i})}if(n==="GET"&&o.pathname==="/api/v1/usage/rollups"){let l=k(e,t,"billing:read",s,a),g=o.searchParams.get("from"),p=o.searchParams.get("to");if(!g||!p)throw new S("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(g))||Number.isNaN(Date.parse(p)))throw new S("validation_error","from and to must be ISO-8601 timestamps.",422);let h=o.searchParams.getAll("meter");return{data:e.store.listRollups({...l,from:g,to:p,meters:h.length>0?h:void 0},re(o.searchParams.get("limit"),"limit")??1000)}}if(n==="GET"&&o.pathname==="/api/v1/usage/focus"){let l=k(e,t,"billing:read",s,a),g=o.searchParams.get("from"),p=o.searchParams.get("to");if(!g||!p)throw new S("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(g))||Number.isNaN(Date.parse(p)))throw new S("validation_error","from and to must be ISO-8601 timestamps.",422);if(new Date(p).getTime()-new Date(g).getTime()>31622400000)throw new S("validation_error","The range must not exceed one year.",422);let h=o.searchParams.get("granularity")==="hourly"?"hourly":"daily",f=e.store.listRollups({...l,from:g,to:p},1e4),y=Yt(f,{billingPeriodStart:g,billingPeriodEnd:p,currency:e.store.priceBook.currency,granularity:h});return{contentType:"application/x-ndjson",body:Xe(y),recordCount:y.length}}if(n==="GET"&&o.pathname==="/api/v1/spend/budgets"){let l=k(e,t,"billing:read",s,a);return{data:e.store.listBudgets({organizationId:l.organizationId,projectId:l.projectId})}}if(n==="POST"&&o.pathname==="/api/v1/spend/budgets"){let l=await r.body?.()??{},p={organizationId:k(e,t,"billing:manage",l.projectId,l.environmentId).organizationId,projectId:l.projectId,environmentId:l.environmentId,name:String(l.name??"").trim(),period:qr(l.period??"monthly")??"monthly",timezone:l.timezone,currency:l.currency,softLimitCents:re(l.softLimitCents,"softLimitCents"),hardLimitCents:re(l.hardLimitCents,"hardLimitCents"),thresholds:l.thresholds,meters:l.meters,graceSeconds:re(l.graceSeconds,"graceSeconds"),hysteresisPercent:l.hysteresisPercent,dryRun:l.dryRun!==!1,enabled:l.enabled};try{return{data:e.store.createBudget(p)}}catch(h){throw new S("validation_error",h instanceof Error?h.message:String(h),422)}}let d=/^\/api\/v1\/spend\/budgets\/([^/]+)$/.exec(o.pathname);if(d&&(n==="PATCH"||n==="DELETE")){let l=e.store.getBudget(decodeURIComponent(d[1]));if(!l||l.organizationId!==$e(t))throw new S("not_found","Budget was not found.",404);if(k(e,t,"billing:manage",l.projectId,l.environmentId),n==="DELETE")return{data:{deleted:e.store.deleteBudget(l.id)}};let g=await r.body?.()??{};try{return{data:e.store.updateBudget(l.id,g,re(g.expectedVersion,"expectedVersion"))}}catch(p){let h=p instanceof Error?p.message:String(p);throw new S(h.includes("concurrently")?"conflict":"validation_error",h,h.includes("concurrently")?409:422)}}if(n==="GET"&&o.pathname==="/api/v1/spend/anomalies"){let l=k(e,t,"billing:read",s,a);return{data:e.store.listAnomalies({organizationId:l.organizationId,projectId:l.projectId,since:o.searchParams.get("since")??void 0,unacknowledgedOnly:o.searchParams.get("unacknowledged")==="true",limit:re(o.searchParams.get("limit"),"limit")})}}let c=/^\/api\/v1\/spend\/anomalies\/([^/]+)\/acknowledge$/.exec(o.pathname);if(c&&n==="POST"){let l=e.store.getAnomaly(decodeURIComponent(c[1]));if(!l||l.organizationId!==$e(t))throw new S("not_found","Anomaly was not found.",404);return k(e,t,"billing:manage",l.projectId,l.environmentId),{data:{acknowledged:e.store.acknowledgeAnomaly(l.id)}}}if(n==="GET"&&o.pathname==="/api/v1/spend/signals")return k(e,t,"billing:read",s,a),{data:ae};if(o.pathname==="/api/v1/spend/anomaly-configs"){if(n==="GET"){let l=k(e,t,"billing:read",s,a);return{data:e.service.anomalyConfigs.list({organizationId:l.organizationId,projectId:l.projectId})}}if(n==="POST"){let l=await r.body?.()??{},g=k(e,t,"billing:manage",l.projectId,l.environmentId);try{return{data:e.service.anomalyConfigs.upsert({organizationId:g.organizationId,projectId:l.projectId,environmentId:l.environmentId,signal:String(l.signal??""),enabled:l.enabled,sensitivity:l.sensitivity,seasonLength:l.seasonLength==null?void 0:Number(l.seasonLength),minAbsoluteDelta:l.minAbsoluteDelta==null?void 0:Number(l.minAbsoluteDelta),detectDrops:l.detectDrops,severity:l.severity})}}catch(p){throw new S("validation_error",p instanceof Error?p.message:String(p),422)}}}let u=/^\/api\/v1\/spend\/anomaly-configs\/([^/]+)$/.exec(o.pathname);if(u&&n==="DELETE"){let l=e.service.anomalyConfigs.get(decodeURIComponent(u[1]));if(!l||l.organizationId!==$e(t))throw new S("not_found","Anomaly config was not found.",404);return k(e,t,"billing:manage",l.projectId,l.environmentId),{data:{deleted:e.service.anomalyConfigs.delete(l.id)}}}if(o.pathname==="/api/v1/spend/anomaly-silences"){if(n==="GET"){let l=k(e,t,"billing:read",s,a);return{data:e.service.anomalyConfigs.listSilences({organizationId:l.organizationId,projectId:l.projectId,includeExpired:o.searchParams.get("includeExpired")==="true"})}}if(n==="POST"){let l=await r.body?.()??{},g=k(e,t,"billing:manage",l.projectId);try{return{data:e.service.anomalyConfigs.silence({organizationId:g.organizationId,projectId:l.projectId,signal:l.signal,routePattern:l.routePattern,statusCode:l.statusCode==null?void 0:Number(l.statusCode),reason:String(l.reason??""),expiresAt:l.expiresAt})}}catch(p){throw new S("validation_error",p instanceof Error?p.message:String(p),422)}}}let m=/^\/api\/v1\/spend\/anomaly-silences\/([^/]+)$/.exec(o.pathname);if(m&&n==="DELETE")return k(e,t,"billing:manage",s),{data:{deleted:e.service.anomalyConfigs.removeSilence(decodeURIComponent(m[1]))}};if(n==="GET"&&o.pathname==="/api/v1/spend/enforcement"){let l=k(e,t,"billing:read",s,a);return{data:e.store.listEnforcements({organizationId:l.organizationId,activeOnly:o.searchParams.get("active")!=="false"})}}if(n==="GET"&&o.pathname==="/api/v1/spend/allowance"){let l=k(e,t,"billing:read",s,a),g=o.searchParams.get("operation")??"deploy";if(!["build","deploy","function_invoke","request"].includes(g))throw new S("validation_error","operation must be build, deploy, function_invoke, or request.",422);let h=e.store.listEnforcements({organizationId:l.organizationId,activeOnly:!0}).filter((b)=>(!b.projectId||b.projectId===l.projectId)&&(!b.environmentId||b.environmentId===l.environmentId)),f=Qt(g,h),v=e.store.budgetsForScope(l.organizationId,l.projectId,l.environmentId).map((b)=>e.service.status(b,i));return{operation:g,allowed:f.allowed,blockedBy:f.blockedBy??null,reason:f.reason??null,budgets:v.map((b)=>({id:b.budget.id,name:b.budget.name,usedPercent:b.decision.usedPercent,projectedPercent:b.decision.projectedPercent,level:b.decision.level,timeToCap:b.timeToCap}))}}return}function fd(){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{H as Xa,q as Ya,fo as Za,G as _a,gt as $a,ko as ab,oa as bb,ia as cb,da as db,ca as eb,la as fb,ua as gb,je as hb,qo as ib,ga as jb,vt as kb,Qo as lb,J as mb,Wo as nb,te as ob,Xo as pb,Xa as qb,Pn as rb,$n as sb,Un as tb,Hn as ub,ms as vb,ps as wb,pr as xb,fr as yb,dt as zb,As as Ab,si as Bb,Ve as Cb,ai as Db,D as Eb,ci as Fb,Rt as Gb,Br as Hb,Be as Ib,li as Jb,ui as Kb,mi as Lb,Ct as Mb,Se as Nb,ze as Ob,kt as Pb,W as Qb,z as Rb,gi as Sb,ne as Tb,hi as Ub,Ot as Vb,Qr as Wb,Wr as Xb,Ue as Yb,xt as Zb,Nt as _b,U as $b,Yr as ac,Zr as bc,$t as cc,He as dc,ie as ec,tn as fc,we as gc,Vt as hc,Bt as ic,Ae as jc,on as kc,Ut as lc,Ft as mc,Ht as nc,Qt as oc,Qe as pc,an as qc,dn as rc,Ti as sc,ln as tc,Jt as uc,Re as vc,un as wc,pn as xc,We as yc,ae as zc,Ge as Ac,Ye as Bc,Ze as Cc,Wt as Dc,hn as Ec,Yt as Fc,Xe as Gc,Li as Hc,et as Ic,Wi as Jc,Zt as Kc,de as Lc,Xt as Mc,Zi as Nc,tr as Oc,wn as Pc,Ms as Qc,pe as Rc,ro as Sc,ct as Tc,qs as Uc,so as Vc,ao as Wc,co as Xc,Fs as Yc,lo as Zc,uo as _c,Js as $c,S as ad,ii as bd,hd as cd,fd as dd};
|
|
111
|
+
${JSON.stringify(r)}`).digest("hex")}class ii{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new q(e),this.spendGate=new de(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||!At(n,r))throw new S("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 S("forbidden",`The token is missing the ${t} capability.`,403);let n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,r),o=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope),i=t==="project:read"&&!!n&&!!o&&At(n,o);if(!n||!o||!At(o,n)&&!i)throw new S("forbidden","The token does not grant access to this resource.",403);let s=i?o:n;if(!Lr({membership:e.membership,grants:this.controlPlane.listGrants(e.membership.id),capability:t,target:s}).allowed)throw new S("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 S("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((o)=>String(o.id)));if(r&&!n.has(r))throw new S("not_found","Environment was not found.",404);return this.controlPlane.listResources(t,r).filter((o)=>!o.environmentId||n.has(o.environmentId)).filter((o)=>{try{return this.authorize(e,"project:read",{type:"resource",id:o.id}),!0}catch{return!1}}).map((o)=>({id:o.id,projectId:o.projectId,environmentId:o.environmentId,kind:o.kind,slug:o.slug,name:o.name,provider:o.provider,providerId:o.providerId,metadata:_(o.metadata),version:o.version,createdAt:o.createdAt,updatedAt:o.updatedAt}))}listOperations(e,t){return this.controlPlane.listOperations({projectId:t,limit:500}).filter((n)=>{let o=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",o),!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 o=n.resourceId?{type:"resource",id:n.resourceId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.target(e,o),!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:_(n.payload),createdAt:n.createdAt}))}createDeployment(e,t,r){if(!this.controlPlane.listEnvironments(t.projectId).find((u)=>u.id===t.environmentId))throw new S("not_found","Environment was not found in this project.",404);let o=t.serviceId?{type:"resource",id:t.serviceId}:{type:"environment",id:t.environmentId};this.authorize(e,"deployments:create",o);let i=this.spendGate.check("deploy",{organizationId:e.serviceAccount.organizationId,projectId:t.projectId,environmentId:t.environmentId});if(!i.allowed)throw new S("spend_cap_exceeded",i.reason??"A spend cap is blocking deployments.",402,{action:i.action,budgetId:i.budgetId});let s=oi("POST","/api/v1/deployments",t),a=this.identities.getIdempotency(e.token.id,r);if(a){if(a.requestHash!==s)throw new S("idempotency_conflict","Idempotency-Key was already used for another request.",409);let u=a.operationId?this.controlPlane.getOperation(a.operationId):void 0;if(!u)throw new S("idempotency_unavailable","The original operation is no longer available.",409);return{operation:this.operation(u),replay:!0}}if(t.serviceId){let u=this.controlPlane.getResource(t.serviceId);if(!u||u.projectId!==t.projectId||u.environmentId!==t.environmentId)throw new S("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:_({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:_(e.input),output:_(e.output),error:e.error,attempt:e.attempt,createdAt:e.createdAt,updatedAt:e.updatedAt,startedAt:e.startedAt,finishedAt:e.finishedAt}}}function $e(e){return e.serviceAccount.organizationId}function qr(e){if(e==null)return;if(e==="daily"||e==="weekly"||e==="monthly")return e;throw new S("validation_error","period must be daily, weekly, or monthly.",422)}function re(e,t){if(e==null)return;let r=Number(e);if(!Number.isFinite(r)||r<0||!Number.isInteger(r))throw new S("validation_error",`${t} must be a non-negative integer.`,422);return r}function k(e,t,r,n,o){if(o)e.authorization.authorize(t,r,{type:"environment",id:o});else if(n)e.authorization.authorize(t,r,{type:"project",id:n});else e.authorization.authorize(t,r,{type:"organization"});return{organizationId:$e(t),projectId:n,environmentId:o}}async function hd(e,t,r){let{method:n,url:o}=r,i=e.now?.()??new Date,s=o.searchParams.get("projectId")??void 0,a=o.searchParams.get("environmentId")??void 0;if(n==="GET"&&o.pathname==="/api/v1/usage"){let l=k(e,t,"billing:read",s,a);return e.service.usageReport({...l,period:qr(o.searchParams.get("period")),timezone:o.searchParams.get("timezone")??void 0,now:i})}if(n==="GET"&&o.pathname==="/api/v1/usage/rollups"){let l=k(e,t,"billing:read",s,a),g=o.searchParams.get("from"),p=o.searchParams.get("to");if(!g||!p)throw new S("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(g))||Number.isNaN(Date.parse(p)))throw new S("validation_error","from and to must be ISO-8601 timestamps.",422);let h=o.searchParams.getAll("meter");return{data:e.store.listRollups({...l,from:g,to:p,meters:h.length>0?h:void 0},re(o.searchParams.get("limit"),"limit")??1000)}}if(n==="GET"&&o.pathname==="/api/v1/usage/focus"){let l=k(e,t,"billing:read",s,a),g=o.searchParams.get("from"),p=o.searchParams.get("to");if(!g||!p)throw new S("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(g))||Number.isNaN(Date.parse(p)))throw new S("validation_error","from and to must be ISO-8601 timestamps.",422);if(new Date(p).getTime()-new Date(g).getTime()>31622400000)throw new S("validation_error","The range must not exceed one year.",422);let h=o.searchParams.get("granularity")==="hourly"?"hourly":"daily",f=e.store.listRollups({...l,from:g,to:p},1e4),y=Yt(f,{billingPeriodStart:g,billingPeriodEnd:p,currency:e.store.priceBook.currency,granularity:h});return{contentType:"application/x-ndjson",body:Xe(y),recordCount:y.length}}if(n==="GET"&&o.pathname==="/api/v1/spend/budgets"){let l=k(e,t,"billing:read",s,a);return{data:e.store.listBudgets({organizationId:l.organizationId,projectId:l.projectId})}}if(n==="POST"&&o.pathname==="/api/v1/spend/budgets"){let l=await r.body?.()??{},p={organizationId:k(e,t,"billing:manage",l.projectId,l.environmentId).organizationId,projectId:l.projectId,environmentId:l.environmentId,name:String(l.name??"").trim(),period:qr(l.period??"monthly")??"monthly",timezone:l.timezone,currency:l.currency,softLimitCents:re(l.softLimitCents,"softLimitCents"),hardLimitCents:re(l.hardLimitCents,"hardLimitCents"),thresholds:l.thresholds,meters:l.meters,graceSeconds:re(l.graceSeconds,"graceSeconds"),hysteresisPercent:l.hysteresisPercent,dryRun:l.dryRun!==!1,enabled:l.enabled};try{return{data:e.store.createBudget(p)}}catch(h){throw new S("validation_error",h instanceof Error?h.message:String(h),422)}}let d=/^\/api\/v1\/spend\/budgets\/([^/]+)$/.exec(o.pathname);if(d&&(n==="PATCH"||n==="DELETE")){let l=e.store.getBudget(decodeURIComponent(d[1]));if(!l||l.organizationId!==$e(t))throw new S("not_found","Budget was not found.",404);if(k(e,t,"billing:manage",l.projectId,l.environmentId),n==="DELETE")return{data:{deleted:e.store.deleteBudget(l.id)}};let g=await r.body?.()??{};try{return{data:e.store.updateBudget(l.id,g,re(g.expectedVersion,"expectedVersion"))}}catch(p){let h=p instanceof Error?p.message:String(p);throw new S(h.includes("concurrently")?"conflict":"validation_error",h,h.includes("concurrently")?409:422)}}if(n==="GET"&&o.pathname==="/api/v1/spend/anomalies"){let l=k(e,t,"billing:read",s,a);return{data:e.store.listAnomalies({organizationId:l.organizationId,projectId:l.projectId,since:o.searchParams.get("since")??void 0,unacknowledgedOnly:o.searchParams.get("unacknowledged")==="true",limit:re(o.searchParams.get("limit"),"limit")})}}let c=/^\/api\/v1\/spend\/anomalies\/([^/]+)\/acknowledge$/.exec(o.pathname);if(c&&n==="POST"){let l=e.store.getAnomaly(decodeURIComponent(c[1]));if(!l||l.organizationId!==$e(t))throw new S("not_found","Anomaly was not found.",404);return k(e,t,"billing:manage",l.projectId,l.environmentId),{data:{acknowledged:e.store.acknowledgeAnomaly(l.id)}}}if(n==="GET"&&o.pathname==="/api/v1/spend/signals")return k(e,t,"billing:read",s,a),{data:ae};if(o.pathname==="/api/v1/spend/anomaly-configs"){if(n==="GET"){let l=k(e,t,"billing:read",s,a);return{data:e.service.anomalyConfigs.list({organizationId:l.organizationId,projectId:l.projectId})}}if(n==="POST"){let l=await r.body?.()??{},g=k(e,t,"billing:manage",l.projectId,l.environmentId);try{return{data:e.service.anomalyConfigs.upsert({organizationId:g.organizationId,projectId:l.projectId,environmentId:l.environmentId,signal:String(l.signal??""),enabled:l.enabled,sensitivity:l.sensitivity,seasonLength:l.seasonLength==null?void 0:Number(l.seasonLength),minAbsoluteDelta:l.minAbsoluteDelta==null?void 0:Number(l.minAbsoluteDelta),detectDrops:l.detectDrops,severity:l.severity})}}catch(p){throw new S("validation_error",p instanceof Error?p.message:String(p),422)}}}let u=/^\/api\/v1\/spend\/anomaly-configs\/([^/]+)$/.exec(o.pathname);if(u&&n==="DELETE"){let l=e.service.anomalyConfigs.get(decodeURIComponent(u[1]));if(!l||l.organizationId!==$e(t))throw new S("not_found","Anomaly config was not found.",404);return k(e,t,"billing:manage",l.projectId,l.environmentId),{data:{deleted:e.service.anomalyConfigs.delete(l.id)}}}if(o.pathname==="/api/v1/spend/anomaly-silences"){if(n==="GET"){let l=k(e,t,"billing:read",s,a);return{data:e.service.anomalyConfigs.listSilences({organizationId:l.organizationId,projectId:l.projectId,includeExpired:o.searchParams.get("includeExpired")==="true"})}}if(n==="POST"){let l=await r.body?.()??{},g=k(e,t,"billing:manage",l.projectId);try{return{data:e.service.anomalyConfigs.silence({organizationId:g.organizationId,projectId:l.projectId,signal:l.signal,routePattern:l.routePattern,statusCode:l.statusCode==null?void 0:Number(l.statusCode),reason:String(l.reason??""),expiresAt:l.expiresAt})}}catch(p){throw new S("validation_error",p instanceof Error?p.message:String(p),422)}}}let m=/^\/api\/v1\/spend\/anomaly-silences\/([^/]+)$/.exec(o.pathname);if(m&&n==="DELETE")return k(e,t,"billing:manage",s),{data:{deleted:e.service.anomalyConfigs.removeSilence(decodeURIComponent(m[1]))}};if(n==="GET"&&o.pathname==="/api/v1/spend/enforcement"){let l=k(e,t,"billing:read",s,a);return{data:e.store.listEnforcements({organizationId:l.organizationId,activeOnly:o.searchParams.get("active")!=="false"})}}if(n==="GET"&&o.pathname==="/api/v1/spend/allowance"){let l=k(e,t,"billing:read",s,a),g=o.searchParams.get("operation")??"deploy";if(!["build","deploy","function_invoke","request"].includes(g))throw new S("validation_error","operation must be build, deploy, function_invoke, or request.",422);let h=e.store.listEnforcements({organizationId:l.organizationId,activeOnly:!0}).filter((b)=>(!b.projectId||b.projectId===l.projectId)&&(!b.environmentId||b.environmentId===l.environmentId)),f=Qt(g,h),v=e.store.budgetsForScope(l.organizationId,l.projectId,l.environmentId).map((b)=>e.service.status(b,i));return{operation:g,allowed:f.allowed,blockedBy:f.blockedBy??null,reason:f.reason??null,budgets:v.map((b)=>({id:b.budget.id,name:b.budget.name,usedPercent:b.decision.usedPercent,projectedPercent:b.decision.projectedPercent,level:b.decision.level,timeToCap:b.timeToCap}))}}return}function fd(){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{H as Ya,q as Za,fo as _a,G as $a,gt as ab,ko as bb,oa as cb,ia as db,da as eb,ca as fb,la as gb,ua as hb,je as ib,qo as jb,ga as kb,vt as lb,Qo as mb,J as nb,Wo as ob,te as pb,Xo as qb,Xa as rb,Pn as sb,$n as tb,Un as ub,Hn as vb,ms as wb,ps as xb,pr as yb,fr as zb,dt as Ab,As as Bb,si as Cb,Ve as Db,ai as Eb,D as Fb,ci as Gb,Rt as Hb,Br as Ib,Be as Jb,li as Kb,ui as Lb,mi as Mb,Ct as Nb,Se as Ob,ze as Pb,kt as Qb,W as Rb,z as Sb,gi as Tb,ne as Ub,hi as Vb,Ot as Wb,Qr as Xb,Wr as Yb,Ue as Zb,xt as _b,Nt as $b,U as ac,Yr as bc,Zr as cc,$t as dc,He as ec,ie as fc,tn as gc,we as hc,Vt as ic,Bt as jc,Ae as kc,on as lc,Ut as mc,Ft as nc,Ht as oc,Qt as pc,Qe as qc,an as rc,dn as sc,Ti as tc,ln as uc,Jt as vc,Re as wc,un as xc,pn as yc,We as zc,ae as Ac,Ge as Bc,Ye as Cc,Ze as Dc,Wt as Ec,hn as Fc,Yt as Gc,Xe as Hc,Li as Ic,et as Jc,Wi as Kc,Zt as Lc,de as Mc,Xt as Nc,Zi as Oc,tr as Pc,wn as Qc,Ms as Rc,pe as Sc,ro as Tc,ct as Uc,qs as Vc,so as Wc,ao as Xc,co as Yc,Fs as Zc,lo as _c,uo as $c,Js as ad,S as bd,ii as cd,hd as dd,fd as ed};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{rg as a,sg as b,tg as c,ug as d,vg as e,wg as f,xg as g,yg as h,zg as i}from"./chunk-w32xv8n4.js";import"./chunk-dz1ec589.js";import"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{e as AwsSecretsManagerConfigurationBackend,f as AwsSsmConfigurationBackend,h as ConfigurationService,a as ConfigurationStore,g as ExternalConfigurationBackend,d as LocalEncryptedConfigurationBackend,b as parseDotenv,c as serializeDotenv,i as synchronizeConfiguredConfiguration};
|