@stacksjs/ts-cloud 0.12.8 → 0.12.10
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.d.ts +1 -0
- package/dist/aws/index.js +1 -1
- package/dist/aws/sms-voice.d.ts +76 -0
- package/dist/bin/{chunk-m349p8sn.js → chunk-0thy7q96.js} +48 -48
- package/dist/bin/cli.js +113 -113
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-13qjvbqh.js → chunk-0hw5wjjg.js} +1 -1
- package/dist/chunk-1bj94sc2.js +1 -0
- package/dist/{chunk-3mgj3hrh.js → chunk-2k0mt6j5.js} +2 -2
- package/dist/chunk-2qm3rw8b.js +4 -0
- package/dist/{chunk-019wxz6w.js → chunk-3swnmwfc.js} +74 -74
- package/dist/{chunk-aj025v2s.js → chunk-557qj7q9.js} +2 -2
- package/dist/{chunk-86ss83s2.js → chunk-5hkq5081.js} +2 -2
- package/dist/chunk-5pbtmy2k.js +1 -0
- package/dist/{chunk-152he7m3.js → chunk-70v77sqv.js} +2 -2
- package/dist/{chunk-by2bwzk6.js → chunk-7j100g7w.js} +2 -2
- package/dist/chunk-7sc8t7v1.js +1 -0
- package/dist/{chunk-m8fs0233.js → chunk-82gezmen.js} +2 -2
- package/dist/{chunk-y4xkj2f1.js → chunk-982rye5b.js} +2 -2
- package/dist/{chunk-mz0dk78z.js → chunk-a368cs92.js} +1 -1
- package/dist/{chunk-hn40z11p.js → chunk-bcffjsnj.js} +1 -1
- package/dist/chunk-c1hr34a5.js +2 -0
- package/dist/{chunk-wavjkdb8.js → chunk-c8cadhgc.js} +2 -2
- package/dist/{chunk-xcj8zfmg.js → chunk-fbwpm0zm.js} +2 -2
- package/dist/{chunk-jm5mg890.js → chunk-fsssdd5k.js} +2 -2
- package/dist/{chunk-t0xgmhd6.js → chunk-gkj1tpsn.js} +8 -8
- package/dist/chunk-gny5s4kp.js +1 -0
- package/dist/{chunk-73ztr55z.js → chunk-jphewtbx.js} +2 -2
- package/dist/{chunk-h42zck7h.js → chunk-jxrs1219.js} +3 -3
- package/dist/{chunk-x3hay61c.js → chunk-pb47hr0h.js} +1 -1
- package/dist/chunk-qpjcd415.js +22 -0
- package/dist/{chunk-6kpbveb8.js → chunk-qrte4gy2.js} +1 -1
- package/dist/{chunk-tz9myq9a.js → chunk-rg7d67xk.js} +2 -2
- package/dist/{chunk-1qdne0bf.js → chunk-w2ddj42w.js} +1 -1
- package/dist/chunk-xkw7h4pw.js +1 -0
- package/dist/{chunk-sxaxzcbx.js → chunk-y3tbcxb7.js} +120 -114
- package/dist/deploy/index.d.ts +2 -0
- package/dist/deploy/index.js +1 -1
- package/dist/deploy/site-config-editor.d.ts +26 -0
- package/dist/deploy/site-ports.d.ts +20 -2
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.js +8 -8
- package/dist/operations/index.d.ts +24 -0
- package/dist/operations/index.js +1 -0
- package/dist/operations/inventory.d.ts +168 -0
- package/dist/operations/inventory.test.d.ts +1 -0
- package/dist/operations/site-attach.d.ts +95 -0
- package/dist/operations/site-attach.test.d.ts +1 -0
- package/dist/protection/index.js +1 -1
- package/dist/push/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +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 +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +5 -5
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +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 +2 -2
- 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 +7 -3
- package/dist/chunk-a84gmpyh.js +0 -1
- package/dist/chunk-nms5q44e.js +0 -1
- package/dist/chunk-qm32ytbr.js +0 -1
- package/dist/chunk-t3t9ymec.js +0 -1
- package/dist/chunk-y2v22hkv.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{he as a}from"./chunk-2k0mt6j5.js";import"./chunk-jphewtbx.js";import"./chunk-a368cs92.js";import"./chunk-fsssdd5k.js";import"./chunk-0hw5wjjg.js";export{a as buildAndPushServerlessImage};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{a as
|
|
1
|
+
import{wi as s}from"./chunk-a368cs92.js";class a{client;region;constructor(e="us-east-1",r){this.region=e,this.client=new s(void 0,{profile:r})}async createRepository(e){let r={repositoryName:e.repositoryName};if(e.imageTagMutability)r.imageTagMutability=e.imageTagMutability;if(e.imageScanningConfiguration)r.imageScanningConfiguration=e.imageScanningConfiguration;if(e.encryptionConfiguration)r.encryptionConfiguration=e.encryptionConfiguration;if(e.tags&&e.tags.length>0)r.tags=e.tags;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeRepositories(e){let r={};if(e?.repositoryNames&&e.repositoryNames.length>0)r.repositoryNames=e.repositoryNames;if(e?.registryId)r.registryId=e.registryId;if(e?.maxResults)r.maxResults=e.maxResults;if(e?.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repositories:t.repositories?.map((i)=>this.parseRepository(i)),nextToken:t.nextToken}}async getAuthorizationToken(e){let r={};if(e&&e.length>0)r.registryIds=e;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).authorizationData?.map((i)=>({authorizationToken:i.authorizationToken,expiresAt:i.expiresAt,proxyEndpoint:i.proxyEndpoint}))}}async deleteRepository(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeImages(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.imageIds&&e.imageIds.length>0)r.imageIds=e.imageIds;if(e.filter)r.filter=e.filter;if(e.maxResults)r.maxResults=e.maxResults;if(e.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageDetails:t.imageDetails?.map((i)=>this.parseImageDetail(i)),nextToken:t.nextToken}}async batchDeleteImage(e){let r={repositoryName:e.repositoryName,imageIds:e.imageIds};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageIds:t.imageIds,failures:t.failures}}async putLifecyclePolicy(e){let r={repositoryName:e.repositoryName,lifecyclePolicyText:e.lifecyclePolicyText};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText}}async getLifecyclePolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText,lastEvaluatedAt:t.lastEvaluatedAt}}async setRepositoryPolicy(e){let r={repositoryName:e.repositoryName,policyText:e.policyText};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async getRepositoryPolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async tagResource(e){let r={resourceArn:e.resourceArn,tags:e.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTagsForResource(e){let r={resourceArn:e};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).tags}}createLifecyclePolicyText(e){return JSON.stringify({rules:e.map((r)=>({rulePriority:r.rulePriority,description:r.description,selection:r.selection,action:r.action}))})}async getDockerLoginCommand(){let e=await this.getAuthorizationToken();if(!e.authorizationData?.[0])throw Error("Failed to get authorization token");let r=e.authorizationData[0],t=r.authorizationToken||"",i=r.proxyEndpoint||"";return`echo "${Buffer.from(t,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${i}`}getRegistryUri(e){return`${e}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(e){return{repositoryArn:e.repositoryArn,registryId:e.registryId,repositoryName:e.repositoryName,repositoryUri:e.repositoryUri,createdAt:e.createdAt,imageTagMutability:e.imageTagMutability,imageScanningConfiguration:e.imageScanningConfiguration,encryptionConfiguration:e.encryptionConfiguration}}parseImageDetail(e){return{registryId:e.registryId,repositoryName:e.repositoryName,imageDigest:e.imageDigest,imageTags:e.imageTags,imageSizeInBytes:e.imageSizeInBytes,imagePushedAt:e.imagePushedAt,imageScanStatus:e.imageScanStatus,imageScanFindingsSummary:e.imageScanFindingsSummary}}}
|
|
2
|
+
export{a as Vf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Uf as U}from"./chunk-7j100g7w.js";import{eg as Z,jg as _,ng as K,rg as L,sg as Y}from"./chunk-rg7d67xk.js";import{tg as M}from"./chunk-982rye5b.js";import{si as W}from"./chunk-c8cadhgc.js";import{ui as B}from"./chunk-70v77sqv.js";import{Qu as j}from"./chunk-0hw5wjjg.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{sf as U}from"./chunk-by2bwzk6.js";import{Ef as Z,Jf as _,Nf as K,Rf as L,
|
|
|
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-1bj94sc2.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-1bj94sc2.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
|
|
|
@@ -57,4 +57,4 @@ import{sf as U}from"./chunk-by2bwzk6.js";import{Ef as Z,Jf as _,Nf as K,Rf as L,
|
|
|
57
57
|
|
|
58
58
|
return request;
|
|
59
59
|
}`}};let b={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(l&&e)b.Aliases=[l],b.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else b.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(a.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:b}},d.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},d.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},a.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},l&&m)a.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:m,Name:l,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},a.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:m,Name:l,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},d.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${l||s}`,Resources:a,Outputs:d}}async function X(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let u=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!u)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return G({siteName:t.siteName,region:t.region,domain:u,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",l="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let m=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new W(l),a=new M,d=new L("us-east-1"),b=new Y("us-east-1"),k=t.hostedZoneId,R=t.certificateArn;if(e&&!k){let u=await a.findHostedZoneForDomain(e);if(u)k=u.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:m,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!R&&k){let u=await d.findCertificateByDomain(e);if(u&&u.Status==="ISSUED")R=u.CertificateArn;else R=(await b.requestAndValidate({domainName:e,hostedZoneId:k,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let P=!1,x;try{let u=await r.describeStacks({stackName:i});if(u.Stacks.length>0){let C=u.Stacks[0],f=C.StackStatus;if(f==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),P=!1;else if(f==="DELETE_COMPLETE")P=!1;else P=!0,x=(C.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(u){if(u.message?.includes("does not exist")||u.code==="ValidationError")P=!1;else throw u}let A=x||m;if(!P){let u=new B(s),C=new U,f=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await C.listDistributions();for(let n of o){let g=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))g=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let p=n.Aliases.Items.CNAME;if(typeof p==="string")g=[p];else if(Array.isArray(p))g=p}}if(g.includes(e)){f=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let c=(await C.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,S;if(c){let I=[];if(Array.isArray(c))I=c;else if(c.Origin)I=Array.isArray(c.Origin)?c.Origin:[c.Origin];else I=[c];for(let h of I){let E=(h.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(E){S=E[1];break}}}if(S){let I=e.replace(/\./g,"-");if(!S.startsWith(I)&&!S.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${S}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${S}`),k&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"A",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"AAAA",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(h){console.log(`Note: Could not update Route53 records: ${h.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:S,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:R,message:"Using existing CloudFront distribution"}}}}}catch{}if(k)try{let n=(await a.listResourceRecordSets({HostedZoneId:k})).ResourceRecordSets||[];for(let g of n)if(g.Name===`${e}.`&&(g.Type==="A"||g.Type==="AAAA")){if(g.AliasTarget){console.log(`Found orphaned Route53 ${g.Type} record for ${e}, cleaning up...`);try{await a.deleteRecord({HostedZoneId:k,RecordSet:g}),console.log(`Deleted orphaned Route53 ${g.Type} record for ${e}`)}catch(p){console.log(`Note: Could not delete Route53 record: ${p.message}`)}}}}catch{}}if(!f)try{if((await u.headBucket(m)).exists){console.log(`Found orphaned S3 bucket ${m}, cleaning up...`);try{let n=u.emptyBucket(m).then(()=>u.deleteBucket(m)),g=new Promise((p,c)=>setTimeout(()=>c(Error("Bucket cleanup timeout")),30000));await Promise.race([n,g]),console.log(`Deleted orphaned S3 bucket ${m}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let g=Date.now().toString(36);A=`${m}-${g}`,console.log(`Using alternative bucket name: ${A}`)}}}catch{}}let y=Q({bucketName:A,domain:e,certificateArn:R,hostedZoneId:k,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),T=Object.entries(t.tags||{}).map(([u,C])=>({Key:u,Value:C}));T.push({Key:"ManagedBy",Value:"ts-cloud"}),T.push({Key:"Application",Value:t.siteName});let F,N=!1;if(P){N=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${A}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${R||"not specified"}`);try{F=(await r.updateStack({stackName:i,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:T})).StackId,console.log(`Update initiated, stack ID: ${F}`)}catch(u){if(u.message?.includes("No updates are to be performed")){let C=await r.describeStacks({stackName:i});F=C.Stacks[0].StackId;let f=C.Stacks[0]?.Outputs||[],o=(n)=>f.find((g)=>g.OutputKey===n)?.OutputValue;return{success:!0,stackId:F,stackName:i,bucket:o("BucketName")||A,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:R,message:"Static site infrastructure is already up to date"}}else throw u}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${A}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${R||"not specified"}`),console.log("Stack does not exist, creating..."),F=(await r.createStack({stackName:i,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:T,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${F}`);console.log(`Waiting for stack to reach ${N?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,N?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(u){if(u.message?.includes("must be verified")||u.message?.includes("Access denied for operation")||u.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let C=new U;if(e)try{let f=await C.listDistributions();for(let o of f){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let g=o.Aliases.Items.CNAME;if(typeof g==="string")n=[g];else if(Array.isArray(g))n=g}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let p=(await C.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,c;if(p){let S=[];if(Array.isArray(p))S=p;else if(p.Origin)S=Array.isArray(p.Origin)?p.Origin:[p.Origin];else S=[p];for(let I of S){let v=(I.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(v){c=v[1];break}}}if(c)return console.log(`Using existing S3 bucket: ${c}`),{success:!0,stackName:`existing-${o.Id}`,bucket:c,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:R,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let f=new B(s);if((await f.headBucket(A)).exists)console.log(`Using existing S3 bucket: ${A}`);else console.log(`Creating S3 bucket: ${A}...`),await f.createBucket(A);await f.putBucketWebsite(A,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await f.putPublicAccessBlock(A,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${A} configured`);let n=`OAC-${A}`;console.log(`Creating Origin Access Control: ${n}...`);let g=await C.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${g.Id} ready`),console.log("Creating CloudFront distribution...");let p=await C.createDistributionForS3({bucketName:A,bucketRegion:s,originAccessControlId:g.Id,aliases:e?[e]:[],certificateArn:R,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||A}`});console.log(`CloudFront distribution ${p.Id} created`),console.log("Updating S3 bucket policy...");let c=U.getS3BucketPolicyForCloudFront(A,p.ARN);if(await f.putBucketPolicy(A,c),console.log("S3 bucket policy updated"),e&&k){console.log(`Creating Route53 records for ${e}...`);try{await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"A",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:p.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"AAAA",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:p.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(S){console.log(`Note: Could not create Route53 records: ${S.message}`)}}return{success:!0,stackName:`direct-${p.Id}`,bucket:A,distributionId:p.Id,distributionDomain:p.DomainName,domain:e,certificateArn:R,message:"Static site infrastructure created via direct API calls"}}catch(f){return console.log(`Direct API creation failed: ${f.message}`),{success:!1,stackId:F,stackName:i,bucket:A,message:`Deployment failed: ${f.message}`}}}return{success:!1,stackId:F,stackName:i,bucket:A,message:`Stack deployment failed: ${u.message}`}}let D=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],w=(u)=>D.find((C)=>C.OutputKey===u)?.OutputValue;return{success:!0,stackId:F,stackName:i,bucket:w("BucketName")||A,distributionId:w("DistributionId"),distributionDomain:w("DistributionDomain"),domain:e,certificateArn:R,message:"Static site infrastructure deployed successfully"}}async function ee(t){let{sourceDir:s,bucket:l,region:e,cacheControl:m="max-age=31536000, public",onProgress:i}=t,r=new B(e),{readdir:a}=await import("node:fs/promises"),{join:d,relative:b}=await import("node:path"),{createHash:k}=await import("node:crypto");async function R(D){let w=[],u=await a(D,{withFileTypes:!0});for(let C of u){let f=d(D,C.name);if(C.isDirectory())w.push(...await R(f));else w.push(f)}return w}function P(D){let w=D.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[w||""]||"application/octet-stream"}function x(D){return k("md5").update(D).digest("hex")}async function A(){let D=new Map,w;do{let u=await r.listObjects({bucket:l,maxKeys:1000,continuationToken:w});for(let C of u.objects){let f=C.ETag?.replace(/"/g,"")||"";D.set(C.Key,f)}w=u.nextContinuationToken}while(w);return D}let y=await R(s),T=[],F=0,N=0,O=await A();for(let D of y){let w=b(s,D),u=P(D),C=D.endsWith(".html")?"max-age=3600, public":m;try{let f=Buffer.from(await Bun.file(D).arrayBuffer()),o=x(f),n=O.get(w);if(n&&n===o){N++,i?.(F+N,y.length,w);continue}await r.putObject({bucket:l,key:w,body:f,contentType:u,cacheControl:C}),F++,i?.(F+N,y.length,w)}catch(f){T.push(`Failed to upload ${w}: ${f.message}`)}}return{uploaded:F,skipped:N,errors:T}}async function te(t){return{invalidationId:(await new U().invalidateAll(t)).Id}}async function Ae(t,s="us-east-1"){let l=new W(s);try{let r=((await l.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((a)=>a.OutputKey==="BucketName")?.OutputValue;if(r)await new B(s).emptyBucket(r)}catch{}await l.deleteStack(t);let e=await l.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function Ce(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await X(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(d){console.log(`Note: Could not clean bucket: ${d.message}`)}}e?.("upload","Uploading files to S3...");let r=await ee({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(d,b,k)=>{e?.("upload",`${d}/${b}: ${k}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await te(i.distributionId);e?.("complete","Deployment complete!");let a=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:a}}
|
|
60
|
-
export{J as
|
|
60
|
+
export{J as Td,G as Ud,le as Vd,Q as Wd,X as Xd,ee as Yd,te as Zd,Ae as _d,Ce as $d};
|
|
@@ -41,4 +41,4 @@ fi
|
|
|
41
41
|
systemctl enable nftables >/dev/null 2>&1 || true
|
|
42
42
|
echo "ts-cloud: L3/L4 mitigation active"
|
|
43
43
|
`}var b=["off","monitor","rate_limit","challenge","lockdown"];function D(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function T(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
|
|
44
|
-
export{_ as
|
|
44
|
+
export{_ as Fm,S as Gm,k as Hm,x as Im,P as Jm,C as Km,D as Lm,T as Mm};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import{rj as g,uj as b,vj as f,wj as y}from"./chunk-2qm3rw8b.js";function C(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(t,e="/var/www"){let r=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${r}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${r}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${C(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function tt(t){if(!t)return[];let e=[];for(let r of t.split(`
|
|
2
|
+
`)){let n=r.trim();if(!n.startsWith("site:"))continue;let[,o,s,i]=n.split(":");if(!o||s!=="no")continue;e.push({name:o,size:i||"?"})}return e}function et(t,e,r){let n=t.map((s)=>` ${e}-${s.name} (${s.size})`).join(`
|
|
3
|
+
`),o=t.length===1?"it":"them";return`This server still holds ${t.length} site tree${t.length===1?"":"s"} with nothing running for ${o}:
|
|
4
|
+
${n}
|
|
5
|
+
`+"A site moved off this box keeps its files here on purpose — they are the rollback, and they are what makes "+`the move reversible until this server is destroyed. Destroying it now discards that.
|
|
6
|
+
Verify the site is serving from its new home first, then re-run with ${r} to destroy it anyway.`}var D="ts-cloud/project",T="ts-cloud/environment",R="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function it(t){let e={};for(let[r,n]of Object.entries(t?.labels??{}))if(typeof n==="string")e[r]=n;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:d(t?.datacenter?.location?.name)??d(t?.datacenter?.name)??d(t?.location),labels:e,project:d(e[D]),environment:d(e[T]),role:d(e[R])}}function E(t){return t.slug?.trim()||"app"}function _(t){let e=[];for(let r of t){let n=E(r);for(let o of r.proxies??[]){let s=d(o?.to);if(!s)continue;e.push({slug:n,host:s,path:d(o?.path)??"/",...j(o)})}}return e.sort((r,n)=>r.slug.localeCompare(n.slug)||r.host.localeCompare(n.host)||r.path.localeCompare(n.path))}function j(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((o)=>typeof o==="string").join(", "),kind:"app"};let r=t?.static;if(typeof r==="string"&&r.trim())return{target:r.trim(),kind:"static"};if(r&&typeof r==="object"&&d(r.dir))return{target:d(r.dir),kind:"static"};let n=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(n)return{target:n,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function I(t){let e=new Map;for(let r of t){let n=e.get(r.slug);if(n)n.push(r);else e.set(r.slug,[r])}return[...e.entries()].map(([r,n])=>({slug:r,routes:n})).sort((r,n)=>n.routes.length-r.routes.length||r.slug.localeCompare(n.slug))}async function st(t,e,r=g){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let n=await e(t.ipv4,f(r));if(n.code!==0){let o=n.stderr.trim().split(`
|
|
7
|
+
`)[0]||`remote command exited ${n.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:o}}return{server:t.name,ip:t.ipv4,routes:_(y(n.stdout))}}catch(n){let o=n instanceof Error?n.message.split(`
|
|
8
|
+
`)[0]:String(n);return{server:t.name,ip:t.ipv4,routes:[],unavailable:o}}}function u(t,e){let r=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${r||"/"}`}function ot(t,e,r){let n=new Set(e.filter((a)=>a.slug===r).map((a)=>u(a.host,a.path))),o=[],s=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&n.has(u(a.domain,a.path)))o.push(a);else s.push(a);return{present:o,absent:s,loopback:i,foreign:e.filter((a)=>a.slug!==r)}}function H(t,e,r){let n=new Set;for(let o of e)for(let s of o.routes)if(s.slug===r)n.add(u(s.host,s.path));return t.filter((o)=>!o.loopbackOnly&&o.domain!==void 0&&!n.has(u(o.domain,o.path)))}function at(t){let{slug:e,servers:r,probes:n,declared:o}=t,s=[];if(s.push(r.length===0?"No servers found.":`${r.length} server${r.length===1?"":"s"}:`),r.length>0)s.push("");let i=new Map(n.map((a)=>[a.server,a]));for(let a of r){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);s.push(` ${a.name} ${p.join(" ")}`),s.push(` ${A(a)}`);let c=i.get(a.name);if(!c)s.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)s.push(` could not read ${g}: ${c.unavailable}`);else s.push(...L(c,e));s.push("")}return s.push(...N(t)),s}function A(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function L(t,e){let r=I(t.routes);if(r.length===0)return[` serves nothing: ${g} is empty or absent`];let n=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${r.length} project${r.length===1?"":"s"}:`];for(let o of r){n.push(` ${o.slug}${o.slug===e?" (this project)":""}`);for(let s of o.routes)n.push(` ${s.host}${s.path==="/"?"/":s.path} -> ${U(s)}`)}return n}function U(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function N(t){let{slug:e,declared:r,probes:n,servers:o}=t;if(r.length===0)return[`This project ('${e}') declares no sites.`];let s=[`This project ('${e}') declares ${r.length} site${r.length===1?"":"s"}: `+r.map((c)=>c.name).join(", ")],i=r.filter((c)=>c.loopbackOnly);if(i.length>0)s.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=n.filter((c)=>!c.unavailable);if(a.length===0)return s.push(" Nothing to reconcile them against: no box reported what it serves."),s;let p=H(r,a,e);if(s.push(` ${r.length-i.length-p.length} routed by a box above`),p.length>0){s.push(` ${p.length} not routed by any box above: ${p.map((k)=>k.name).join(", ")}`);let c=n.length-a.length,m=o.length-n.length;if(c>0)s.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(m>0)s.push(` Either they were never deployed, or they are on one of the ${m} server${m===1?"":"s"} this run did not probe.`);else s.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return s}async function lt(t){let e=[];for(let r of t.steps)try{e.push({step:r,state:await r.satisfied()?"satisfied":"pending"})}catch(n){e.push({step:r,state:"unknown",reason:n instanceof Error?n.message:String(n)})}return e}function v(t){return t.filter((e)=>e.state!=="satisfied")}function M(t){return v(t).some((e)=>e.step.destructive===!0)}function dt(t,e){let r=v(e),n=[`${t.operation} ${t.target}`];if(r.length===0)return n.push(" Nothing to do — every step is already satisfied."),n;for(let{step:s,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[s.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(n.push(` ${p}${s.title}${c.length>0?` [${c.join(", ")}]`:""}`),s.change)n.push(` ${s.change.from} → ${s.change.to}`);if(a)n.push(` could not check: ${a}`)}let o=r.filter((s)=>s.step.destructive).length;return n.push(` ${r.length} step(s) would run`+(o>0?`, ${o} irreversible — re-run with --confirm ${t.target}`:"")),n}async function pt(t,e,r={}){let n={operation:t.operation,target:t.target,steps:[],success:!0};if(M(e)&&r.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:o,state:s}of e){if(s==="satisfied"){n.steps.push({id:o.id,title:o.title,state:"skipped"}),r.log?.(`skip ${o.title} (already done)`);continue}r.audit?.({operation:t.operation,target:t.target,step:o.id,state:"started"});try{await o.apply(),n.steps.push({id:o.id,title:o.title,state:"applied"}),r.log?.(`done ${o.title}`),r.audit?.({operation:t.operation,target:t.target,step:o.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return n.steps.push({id:o.id,title:o.title,state:"failed",error:a}),n.success=!1,r.log?.(`FAIL ${o.title}: ${a}`),r.audit?.({operation:t.operation,target:t.target,step:o.id,state:"failed",error:a}),n}}return n}function z(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function gt(t,e,r){if(z(e),t===e)throw Error(`'${t}' is already named that.`);if((await r.takenNames()).some((s)=>s===e&&s!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let o=[];if(r.providerName&&r.renameProvider){let{providerName:s,renameProvider:i}=r;o.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await s()===e,apply:()=>i(e)})}if(r.stateName&&r.writeStateName){let{stateName:s,writeStateName:i}=r;o.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await s();return a===void 0||a===e},apply:()=>i(e)})}if(r.remoteHostname&&r.setRemoteHostname){let{remoteHostname:s,setRemoteHostname:i}=r;o.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await s()===e,apply:()=>i(e)})}return o.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>r.inventoryName()===e,apply:async()=>{await r.renameInventory(e)}}),{operation:"server:rename",target:t,steps:o}}function ht(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
|
|
9
|
+
`)}function $t(t,e,r){let n=e.trim();if(!n)return{problem:"No server named."};let[o,...s]=t.filter((c)=>c.name===n);if(o&&s.length===0)return{server:o};let i=t.filter((c)=>c.project===n);if(i.length>1&&r)i=i.filter((c)=>!c.environment||c.environment===r);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${n}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${n}'. Nothing is named that, and no box carries the label ts-cloud/project=${n}.`}}function yt(t,e){let r=[];if(!e.project)r.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)r.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")r.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)r.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return r}function S(t,e){let r=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${r||"/"}`}function vt(t,e,r){let n=[],o=b(r.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),s=new Map;for(let i of r)if(i.slug!==t)s.set(S(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=o.get(i.port);if(a)n.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=s.get(S(i.domain,i.path));if(a)n.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return n}function St(t){return t.registryRead&&t.conflicts.length===0}function bt(t){let{slug:e,owner:r,server:n,declared:o,conflicts:s}=t,i=[];i.push(`Attach '${e}' to '${n.name}' (${n.ipv4??"no IPv4"}), owned by '${r}'.`,""),i.push(` ${o.length} site${o.length===1?"":"s"} would deploy onto this box:`);for(let a of o){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${n.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(s.length>0){i.push(` ${s.length} conflict${s.length===1?"":"s"} with what the box already serves:`);for(let a of s)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${n.name}' already serves.`);return i}function h(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function w(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function B(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(x(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
|
|
10
|
+
`)}function x(t,e){return`^${t}-${e}-((queue|daemon)-.*|scheduler)\\.service$`}function W(t,e){return O(x(t,e))}function O(t){return[`ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(t)} | while read -r unit; do`,' systemctl is-active "$unit" >/dev/null 2>&1 && echo "active:$unit" || true',"done"].join(`
|
|
11
|
+
`)}function F(t){return!t.split(`
|
|
12
|
+
`).some((e)=>e.trim().startsWith("active:"))}function V(t,e,r){let n=h(t,e);return["set -eu",`test -d ${l(r)} || { echo "no site tree at ${r}" >&2; exit 1; }`,`rm -f ${l(n)}`,`tar czf ${l(n)} -C "$(dirname ${l(r)})" "$(basename ${l(r)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${w(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(n)} | cut -d' ' -f1`].join(`
|
|
13
|
+
`)}function q(t,e,r){let n=h(t,e);return["set -eu",`test -f ${l(n)} || { echo "archive not staged at ${n}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(r)})"`,`tar xzf ${l(n)} -C "$(dirname ${l(r)})" "$(basename ${l(r)})"`,`tar xzf ${l(n)} -C /etc/systemd/system --wildcards ${l(w(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(n)}`].join(`
|
|
14
|
+
`)}function G(t,e,r){return[`test -d ${l(r)} && echo tree:present || echo tree:absent`,`systemctl is-active ${t}-${e}.service >/dev/null 2>&1 && echo unit:active || echo unit:inactive`].join(`
|
|
15
|
+
`)}function K(t){return t.includes("tree:present")&&t.includes("unit:active")}function Z(t,e="/",r=10){let n=`http://127.0.0.1:${t}${e.startsWith("/")?e:`/${e}`}`;return["set -eu",`for i in $(seq 1 ${r}); do`,` if curl -fsS -o /dev/null --max-time 5 ${l(n)}; then echo healthy; exit 0; fi`," sleep 3","done",`echo "no healthy response from ${n}" >&2`,"exit 1"].join(`
|
|
16
|
+
`)}function J(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(P(t,e))} || true); do`,' systemctl disable --now "$unit" 2>/dev/null || true',"done",`rm -f /etc/rpx/sites.d/${t}.json 2>/dev/null || true`,"systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true"].join(`
|
|
17
|
+
`)}function P(t,e){return`^${t}-${e}[-@.]`}function Q(t,e){return O(P(t,e))}function X(t){return!t.split(`
|
|
18
|
+
`).some((e)=>e.trim().startsWith("active:"))}function xt(t,e){return`/tmp/ts-cloud-move-${t}-${e}-certs.tar.gz`}function Ot(t,e){return["set -u",...e.map((r)=>`if [ -s ${l(`${t}/${r}.crt`)} ]; then echo "cert:${r}:$(sha256sum ${l(`${t}/${r}.crt`)} | cut -d' ' -f1)"; else echo "cert:${r}:absent"; fi`)].join(`
|
|
19
|
+
`)}function Pt(t){let e=new Map;for(let r of t.split(`
|
|
20
|
+
`)){let n=r.trim();if(!n.startsWith("cert:"))continue;let[,o,s]=n.split(":");if(o&&s)e.set(o,s)}return e}function kt(t,e){for(let[r,n]of t){if(n==="absent")continue;if(e.get(r)!==n)return!1}return!0}function Ct(t,e,r){let n=e.flatMap((o)=>[`${o}.crt`,`${o}.key`]);return["set -eu",`rm -f ${l(r)}`,`cd ${l(t)} 2>/dev/null || { echo "no certs dir at ${t}" >&2; exit 0; }`,`TS_CLOUD_CERTS="$(ls ${n.map(l).join(" ")} 2>/dev/null | tr '\\n' ' ' || true)"`,'[ -n "$TS_CLOUD_CERTS" ] || { echo "no certificates to carry"; exit 0; }',`tar czf ${l(r)} $TS_CLOUD_CERTS`].join(`
|
|
21
|
+
`)}function Dt(t,e){return["set -eu",`[ -s ${l(e)} ] || { echo "no certificate archive staged"; exit 0; }`,`mkdir -p ${l(t)}`,`tar xzf ${l(e)} -C ${l(t)}`,`chmod 600 ${l(t)}/*.key 2>/dev/null || true`,`rm -f ${l(e)}`].join(`
|
|
22
|
+
`)}async function Tt(t,e){let{slug:r,siteName:n,appBase:o,from:s,to:i,targetAddress:a}=t;if(s===i)throw Error(`'${n}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${n}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${s} so the snapshot is consistent`,satisfied:async()=>F(await e.runOnSource(W(r,n))),apply:async()=>{await e.runOnSource(B(r,n))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${s}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${s}`,change:{from:`${s}:${o}`,to:h(r,n)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(V(r,n,o))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:s,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:s,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:h(r,n),to:`${i}:${o}`},satisfied:async()=>K(await e.runOnTarget(G(r,n,o))),apply:async()=>{await e.runOnTarget(q(r,n,o))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(Z(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${s}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${s}, leaving its files in place`,satisfied:async()=>X(await e.runOnSource(Q(r,n))),apply:async()=>{await e.runOnSource(J(r,n))}}),{operation:"site:move",target:n,steps:p}}export{Y as zi,tt as Ai,et as Bi,D as Ci,T as Di,R as Ei,it as Fi,_ as Gi,I as Hi,st as Ii,ot as Ji,H as Ki,at as Li,lt as Mi,v as Ni,M as Oi,dt as Pi,pt as Qi,z as Ri,gt as Si,ht as Ti,$t as Ui,yt as Vi,vt as Wi,St as Xi,bt as Yi,h as Zi,w as _i,B as $i,W as aj,F as bj,V as cj,q as dj,G as ej,K as fj,Z as gj,J as hj,Q as ij,X as jj,xt as kj,Ot as lj,Pt as mj,kt as nj,Ct as oj,Dt as pj,Tt as qj};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Tf as y}from"./chunk-y4xkj2f1.js";import{$h as Z}from"./chunk-mz0dk78z.js";var E=new Set(["A","AAAA","CNAME"]);function x(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function S(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,s=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,s))}class R{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let n=1;n<=8;n+=1){let s,o=new AbortController,i=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{s=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(c){if(r=c,n===8)throw c;await S(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!x(s.status)||n===8)throw r;await S(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!x(0,a.message)||n===8)throw r;await S(n,s);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!R.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${s.message??"unknown provider error"}`];let o=[];for(let i of s.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)o.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return!0;return s.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===n&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)s.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)s.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)s.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,s);if(R.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e,t.type);if(s.success){let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(o?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,i),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return{success:!1,message:"Failed to list records"};let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/dns/getNS/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/dns/updateNS/${r}`,{ns:t}),!0}catch{return!1}}}class w{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let n=`${this.baseUrl}${t}`,s={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let i=await fetch(n,o);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;return s}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),o=s.filter((i)=>i.data!==t.content);if(o.length===s.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var O="https://api.cloudflare.com/client/v4",T="[ts-cloud]";class v{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let n=`${O}${t}`,s={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let a=await(await fetch(n,o)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let s=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!s.result||s.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=s.result[0].id;return this.zoneCache.set(r,o),{id:o,name:s.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},s=r??e.proxied;if(s!==void 0&&E.has(e.type)){if(n.proxied=s,s)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let o=z(e);if(o)n.data=o,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),n=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??o?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let i=o.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let s=[],o=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${o}`);if(s.push(...a.result||[]),a.result_info)i=o<a.result_info.total_pages,o++;else i=!1}return{success:!0,records:s.map((a)=>this.fromCloudflareRecord(a))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let s=await this.getZoneDetails(r);if(s)return{...s,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(o){let i=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(i))throw o;let a=await this.getZoneDetails(r);if(!a)throw o;return{...a,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),n=new Set;for(let s of r.result||[]){if(s.status!=="active")continue;for(let o of s.hosts||[])n.add(o.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(o.result&&o.result.length>0)return o.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),s=n.id,o=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${s}/dns_records/${a.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),n={};for(let s of r.result||[])n[s.id]=s.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),s=[],o=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&b(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),s.push({id:i,from:c,to:a})}catch(d){o.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:s,failed:o}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let n=await this.getZoneId(e),o=(await this.getPhaseRules(e,t)).filter((c)=>!(c.description||"").startsWith(T)),i=r.map((c)=>({...c,description:c.description?.startsWith(T)?c.description:`${T} ${c.description||t}`})),a=[...o,...i].map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}function b(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((s,o)=>b(s,t[o]))}let r=e,n=t;return Object.keys(n).every((s)=>b(r[s],n[s]))}function z(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:V(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,s,o]=r.slice(0,3).map(Number);if(![n,s,o].every(Number.isFinite))return null;return{priority:n,weight:s,port:o,target:V(r.slice(3).join(" "))}}function V(e){return e.replace(/\.$/,"")}var L=new Set(["A","AAAA","CNAME","ALIAS"]);function A(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function p(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function M(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let s=h(n);if(s===r||s.endsWith(`.${r}`))return s;return`${s}.${r}`}function U(e,t){return e.map((r)=>({...r,name:M(r.name,t),proxied:r.proxied??!1}))}function q(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(L.has(t.type))return!0;if(t.type==="TXT"){let r=A(t.content);if(r)return A(p(e.content))===r;return p(e.content)===p(t.content)}return p(e.content)===p(t.content)}function j(e,t){if(p(e.content)!==p(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function F(e){let{provider:t,zone:r,records:n}=e,s={outcomes:[],warnings:[]};if(n.length===0)return s;let o=await t.listRecords(r);if(!o.success)return s.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),s;let i=o.records;for(let a of n){let c=i.filter((u)=>q(u,a));if(c.length>0&&c.every((u)=>j(u,a))){s.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},m=a.type==="TXT"&&A(a.content)!==void 0;if(m)for(let u of c){let I=await t.deleteRecord(r,{name:u.name,type:u.type,content:u.content});if(!I.success)s.warnings.push(`could not remove superseded ${u.type} at ${u.name}: ${I.message||"unknown error"}`)}let g=m||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(g.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:g.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let m=new Set(n.filter((u)=>u.type===a&&h(u.name)===d).map((u)=>p(u.content).toLowerCase())),g=i.filter((u)=>u.type===a&&h(u.name)===d&&!m.has(p(u.content).toLowerCase()));for(let u of g)s.warnings.push(`${d} has an undeclared ${a} record (${u.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class C{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new y(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let n=await this.client.findHostedZoneForDomain(e);if(n){let s=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,s),s}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),s=[];for(let o of n.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let i of o.ResourceRecords||[]){let a=i.Value,c;if(o.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(o.Type==="TXT"&&a.startsWith('"')&&a.endsWith('"'))a=a.slice(1,-1);s.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:a,ttl:o.TTL,priority:c})}}return{success:!0,records:s}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:y.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=y.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}async function G(e,t){let r=[],n,s;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:s,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(n=o.NextRecordName,s=o.NextRecordType,!n)break}return r}function l(e){return e.replace(/\.$/,"").toLowerCase()}function _(e){return e.replace(/\.$/,"")}function P(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${_(e.content)}`;return _(e.content)}function W(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function H(e,t){let r=l(t),n=[],s=[],o=[],i=new Set;for(let a of e){let c=l(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){s.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){s.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let m=l(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:m,ttl:300,translatedFrom:`${d} ALIAS → ${m}`}),a.AliasTarget.EvaluateTargetHealth)o.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let m of a.ResourceRecords||[]){let g=K(c,d,m.Value,a.TTL);if("reason"in g){s.push({name:c,type:d,reason:g.reason}),o.push(`${d} ${c}: ${g.reason}`);continue}n.push(g)}}return{zone:r,records:n,skipped:s,warnings:o}}function K(e,t,r,n){let s={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...s,type:t==="PTR"?"CNAME":t,content:l(r)};case"TXT":return{...s,type:"TXT",content:W(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:l(i.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=o.slice(0,3).map(Number);return{...s,type:"SRV",content:l(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:l(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var X=new Set(["TXT","MX","SRV","NS","CAA"]);async function B(e,t){let r=[],n=[],s=new Set;try{let o=await e.listRecords(t.zone);for(let i of o.records||[])s.add(`${l(i.name)}|${i.type}|${P(i)}`)}catch{}for(let o of t.records){let i={...o,proxied:!1},a=`${l(o.name)}|${o.type}|${P(o)}`;if(!X.has(o.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(o);else n.push({record:o,message:d.message||"unknown provider error"});continue}if(s.has(a)){r.push(o);continue}let c=await e.createRecord(t.zone,i);if(c.success)s.add(a),r.push(o);else n.push({record:o,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Y(e,t){let r=await e.listRecords(t.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${l(i.name)}|${i.type}`,c=o.get(a)??[];c.push(P(i)),o.set(a,c)}for(let i of t.records){let a=o.get(`${l(i.name)}|${i.type}`),c=P(i);if(a?.some((d)=>d===c))n.push(i);else s.push({record:i,found:a?.join(", ")})}return{matched:n,missing:s,ok:s.length===0}}class N{client;region;constructor(e="us-east-1"){this.client=new Z,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((n)=>({CertificateArn:n.CertificateArn,DomainName:n.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((n)=>n.DomainName===e||n.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let n=0;n<t;n++){let s=await this.describeCertificate({CertificateArn:e});if(s.Status==="ISSUED")return s;if(s.Status==="FAILED"||s.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let n=r.DomainName.slice(2),s=t.split("."),o=n.split(".");if(s.slice(-o.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}}return!1}}class J{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new N(e),this.route53=new y,t&&t.provider!=="route53")this.dnsProvider=f(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(s){if(!await this.acm.waitForCertificateValidation(i,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let i=n||s[0]?.domainName;for(let a of s){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});o.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of s){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});o.push({...i,changeId:a.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,s=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=n||s[0]?.domainName;for(let i of s)try{await this.dnsProvider.deleteRecord(o,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let o of s)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class D{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new N(t),"provider"in e)this.dnsProvider=f(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:s=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let i=await this.acm.getDnsValidationRecords(o);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(o,s*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,records:s.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!i.success)n.push(`Failed to delete record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:s}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let i=o.SubjectAlternativeNames||[o.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:n,maxWaitMinutes:s})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:s=[],waitForValidation:o=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...s),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function Q(e,t,r){return new D({provider:"porkbun",apiKey:e,secretKey:t},r)}function ee(e,t,r,n){return new D({provider:"godaddy",apiKey:e,apiSecret:t,environment:n},r)}function te(e,t,r){return new D({provider:"route53",region:e,hostedZoneId:t},r||e)}function f(e){switch(e.provider){case"route53":return new C(e.region,e.hostedZoneId);case"porkbun":return new R(e.apiKey,e.secretKey);case"godaddy":return new w(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new v(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Ae(e,t){for(let r of t){let n=f(r);if(await n.canManageDomain(e))return n}return null}class k{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,n=process.env.GODADDY_API_SECRET;if(r&&n){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,o)}let s=process.env.CLOUDFLARE_API_TOKEN;if(s)this.addCloudflare(s,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((s)=>s.provider===e);if(!r)return null;let n=f(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=f(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>f(e))}}var Ce=new k;
|
|
2
|
-
export{E as
|
|
1
|
+
import{tg as y}from"./chunk-982rye5b.js";import{wi as Z}from"./chunk-a368cs92.js";var E=new Set(["A","AAAA","CNAME"]);function x(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function S(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,s=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,s))}class R{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let n=1;n<=8;n+=1){let s,o=new AbortController,i=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{s=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(c){if(r=c,n===8)throw c;await S(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!x(s.status)||n===8)throw r;await S(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!x(0,a.message)||n===8)throw r;await S(n,s);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!R.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${s.message??"unknown provider error"}`];let o=[];for(let i of s.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)o.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return!0;return s.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===n&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)s.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)s.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)s.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,s);if(R.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e,t.type);if(s.success){let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(o?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,i),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return{success:!1,message:"Failed to list records"};let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/dns/getNS/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/dns/updateNS/${r}`,{ns:t}),!0}catch{return!1}}}class w{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let n=`${this.baseUrl}${t}`,s={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let i=await fetch(n,o);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;return s}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),o=s.filter((i)=>i.data!==t.content);if(o.length===s.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var O="https://api.cloudflare.com/client/v4",T="[ts-cloud]";class v{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let n=`${O}${t}`,s={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let a=await(await fetch(n,o)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let s=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!s.result||s.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=s.result[0].id;return this.zoneCache.set(r,o),{id:o,name:s.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},s=r??e.proxied;if(s!==void 0&&E.has(e.type)){if(n.proxied=s,s)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let o=z(e);if(o)n.data=o,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),n=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??o?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let i=o.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let s=[],o=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${o}`);if(s.push(...a.result||[]),a.result_info)i=o<a.result_info.total_pages,o++;else i=!1}return{success:!0,records:s.map((a)=>this.fromCloudflareRecord(a))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let s=await this.getZoneDetails(r);if(s)return{...s,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(o){let i=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(i))throw o;let a=await this.getZoneDetails(r);if(!a)throw o;return{...a,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),n=new Set;for(let s of r.result||[]){if(s.status!=="active")continue;for(let o of s.hosts||[])n.add(o.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(o.result&&o.result.length>0)return o.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),s=n.id,o=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${s}/dns_records/${a.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),n={};for(let s of r.result||[])n[s.id]=s.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),s=[],o=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&b(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),s.push({id:i,from:c,to:a})}catch(d){o.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:s,failed:o}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let n=await this.getZoneId(e),o=(await this.getPhaseRules(e,t)).filter((c)=>!(c.description||"").startsWith(T)),i=r.map((c)=>({...c,description:c.description?.startsWith(T)?c.description:`${T} ${c.description||t}`})),a=[...o,...i].map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}function b(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((s,o)=>b(s,t[o]))}let r=e,n=t;return Object.keys(n).every((s)=>b(r[s],n[s]))}function z(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:V(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,s,o]=r.slice(0,3).map(Number);if(![n,s,o].every(Number.isFinite))return null;return{priority:n,weight:s,port:o,target:V(r.slice(3).join(" "))}}function V(e){return e.replace(/\.$/,"")}var L=new Set(["A","AAAA","CNAME","ALIAS"]);function A(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function p(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function M(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let s=h(n);if(s===r||s.endsWith(`.${r}`))return s;return`${s}.${r}`}function U(e,t){return e.map((r)=>({...r,name:M(r.name,t),proxied:r.proxied??!1}))}function q(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(L.has(t.type))return!0;if(t.type==="TXT"){let r=A(t.content);if(r)return A(p(e.content))===r;return p(e.content)===p(t.content)}return p(e.content)===p(t.content)}function j(e,t){if(p(e.content)!==p(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function F(e){let{provider:t,zone:r,records:n}=e,s={outcomes:[],warnings:[]};if(n.length===0)return s;let o=await t.listRecords(r);if(!o.success)return s.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),s;let i=o.records;for(let a of n){let c=i.filter((u)=>q(u,a));if(c.length>0&&c.every((u)=>j(u,a))){s.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},m=a.type==="TXT"&&A(a.content)!==void 0;if(m)for(let u of c){let I=await t.deleteRecord(r,{name:u.name,type:u.type,content:u.content});if(!I.success)s.warnings.push(`could not remove superseded ${u.type} at ${u.name}: ${I.message||"unknown error"}`)}let g=m||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(g.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:g.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let m=new Set(n.filter((u)=>u.type===a&&h(u.name)===d).map((u)=>p(u.content).toLowerCase())),g=i.filter((u)=>u.type===a&&h(u.name)===d&&!m.has(p(u.content).toLowerCase()));for(let u of g)s.warnings.push(`${d} has an undeclared ${a} record (${u.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class C{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new y(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let n=await this.client.findHostedZoneForDomain(e);if(n){let s=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,s),s}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),s=[];for(let o of n.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let i of o.ResourceRecords||[]){let a=i.Value,c;if(o.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(o.Type==="TXT"&&a.startsWith('"')&&a.endsWith('"'))a=a.slice(1,-1);s.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:a,ttl:o.TTL,priority:c})}}return{success:!0,records:s}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:y.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=y.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}async function G(e,t){let r=[],n,s;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:s,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(n=o.NextRecordName,s=o.NextRecordType,!n)break}return r}function l(e){return e.replace(/\.$/,"").toLowerCase()}function _(e){return e.replace(/\.$/,"")}function P(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${_(e.content)}`;return _(e.content)}function W(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function H(e,t){let r=l(t),n=[],s=[],o=[],i=new Set;for(let a of e){let c=l(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){s.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){s.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let m=l(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:m,ttl:300,translatedFrom:`${d} ALIAS → ${m}`}),a.AliasTarget.EvaluateTargetHealth)o.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let m of a.ResourceRecords||[]){let g=K(c,d,m.Value,a.TTL);if("reason"in g){s.push({name:c,type:d,reason:g.reason}),o.push(`${d} ${c}: ${g.reason}`);continue}n.push(g)}}return{zone:r,records:n,skipped:s,warnings:o}}function K(e,t,r,n){let s={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...s,type:t==="PTR"?"CNAME":t,content:l(r)};case"TXT":return{...s,type:"TXT",content:W(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:l(i.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=o.slice(0,3).map(Number);return{...s,type:"SRV",content:l(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:l(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var X=new Set(["TXT","MX","SRV","NS","CAA"]);async function B(e,t){let r=[],n=[],s=new Set;try{let o=await e.listRecords(t.zone);for(let i of o.records||[])s.add(`${l(i.name)}|${i.type}|${P(i)}`)}catch{}for(let o of t.records){let i={...o,proxied:!1},a=`${l(o.name)}|${o.type}|${P(o)}`;if(!X.has(o.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(o);else n.push({record:o,message:d.message||"unknown provider error"});continue}if(s.has(a)){r.push(o);continue}let c=await e.createRecord(t.zone,i);if(c.success)s.add(a),r.push(o);else n.push({record:o,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Y(e,t){let r=await e.listRecords(t.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${l(i.name)}|${i.type}`,c=o.get(a)??[];c.push(P(i)),o.set(a,c)}for(let i of t.records){let a=o.get(`${l(i.name)}|${i.type}`),c=P(i);if(a?.some((d)=>d===c))n.push(i);else s.push({record:i,found:a?.join(", ")})}return{matched:n,missing:s,ok:s.length===0}}class N{client;region;constructor(e="us-east-1"){this.client=new Z,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((n)=>({CertificateArn:n.CertificateArn,DomainName:n.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((n)=>n.DomainName===e||n.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let n=0;n<t;n++){let s=await this.describeCertificate({CertificateArn:e});if(s.Status==="ISSUED")return s;if(s.Status==="FAILED"||s.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let n=r.DomainName.slice(2),s=t.split("."),o=n.split(".");if(s.slice(-o.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}}return!1}}class J{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new N(e),this.route53=new y,t&&t.provider!=="route53")this.dnsProvider=f(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(s){if(!await this.acm.waitForCertificateValidation(i,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let i=n||s[0]?.domainName;for(let a of s){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});o.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of s){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});o.push({...i,changeId:a.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,s=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=n||s[0]?.domainName;for(let i of s)try{await this.dnsProvider.deleteRecord(o,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let o of s)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class D{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new N(t),"provider"in e)this.dnsProvider=f(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:s=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let i=await this.acm.getDnsValidationRecords(o);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(o,s*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,records:s.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!i.success)n.push(`Failed to delete record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:s}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let i=o.SubjectAlternativeNames||[o.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:n,maxWaitMinutes:s})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:s=[],waitForValidation:o=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...s),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function Q(e,t,r){return new D({provider:"porkbun",apiKey:e,secretKey:t},r)}function ee(e,t,r,n){return new D({provider:"godaddy",apiKey:e,apiSecret:t,environment:n},r)}function te(e,t,r){return new D({provider:"route53",region:e,hostedZoneId:t},r||e)}function f(e){switch(e.provider){case"route53":return new C(e.region,e.hostedZoneId);case"porkbun":return new R(e.apiKey,e.secretKey);case"godaddy":return new w(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new v(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Ae(e,t){for(let r of t){let n=f(r);if(await n.canManageDomain(e))return n}return null}class k{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,n=process.env.GODADDY_API_SECRET;if(r&&n){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,o)}let s=process.env.CLOUDFLARE_API_TOKEN;if(s)this.addCloudflare(s,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((s)=>s.provider===e);if(!r)return null;let n=f(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=f(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>f(e))}}var Ce=new k;
|
|
2
|
+
export{E as Xf,R as Yf,w as Zf,T as _f,v as $f,A as ag,M as bg,U as cg,F as dg,C as eg,G as fg,H as gg,B as hg,Y as ig,D as jg,Q as kg,ee as lg,te as mg,f as ng,Ae as og,k as pg,Ce as qg,N as rg,J as sg};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Gm as w}from"./chunk-pb47hr0h.js";var L="\x00";function k(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function y(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function d(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!k(t.path,i.path))return!1;if(t.host&&!y(t.host,i.host??""))return!1;return!0}function m(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class A{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>d(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||p(s.action)>p(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=m(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!d(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=m(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function p(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function I(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function C(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var h="protection.controls",b=24,x=4,M={ipRules:{allow:[],block:[]}};function f(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function g(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(b,Math.max(0.25,e))}var R=500;class P{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(h);if(!t||typeof t!=="object"||Array.isArray(t))return{...M,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(h,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:f(i.attackMode,t),mitigationPause:f(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+g(t.hours,x)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+g(t.hours,b)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!w(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>R)throw Error(`At most ${R} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function D(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function E(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function T(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function v(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:T(o,i)}}}}export{L as a,k as b,d as c,m as d,A as e,I as f,C as g,h,b as i,x as j,P as k,D as l,E as m,T as n,v as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Wf as a}from"./chunk-fbwpm0zm.js";import"./chunk-a368cs92.js";import"./chunk-0hw5wjjg.js";export{a as RDSClient};
|