@stacksjs/ts-cloud 0.13.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/{chunk-y671cgz5.js → chunk-1qn174w2.js} +1 -1
- package/dist/bin/{chunk-jee6msvx.js → chunk-fr69rgea.js} +2 -2
- package/dist/bin/{chunk-2ahgpy3j.js → chunk-k8wscjd9.js} +1 -1
- package/dist/bin/{chunk-88ysj8n5.js → chunk-kdk3jhyc.js} +1 -1
- package/dist/bin/cli.js +5 -5
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-mcfdtg5w.js → chunk-1bxqrj7m.js} +1 -1
- package/dist/{chunk-2s65yj3g.js → chunk-4w8d2mf0.js} +2 -2
- package/dist/{chunk-r4dpn715.js → chunk-9s5sm0wt.js} +6 -6
- package/dist/{chunk-asmv4fw1.js → chunk-a0d0h33y.js} +19 -19
- package/dist/chunk-a6jazwvy.js +1 -0
- package/dist/{chunk-vk513ge7.js → chunk-b2b79jtk.js} +60 -60
- package/dist/{chunk-y13zcbnp.js → chunk-b9pm7mbd.js} +84 -84
- package/dist/{chunk-hyj2ymp1.js → chunk-bkv2p4hp.js} +6 -6
- package/dist/{chunk-z7v4evbh.js → chunk-cwjskpj4.js} +2 -2
- package/dist/{chunk-xqx5szta.js → chunk-dky93h4d.js} +17 -17
- package/dist/{chunk-dzqz1sm0.js → chunk-etmbw4er.js} +3 -3
- package/dist/{chunk-p9fqsz06.js → chunk-gdbtz492.js} +2 -2
- package/dist/chunk-h1anhx3y.js +1 -0
- package/dist/chunk-hxhe2rkx.js +1 -0
- package/dist/{chunk-42kv07cs.js → chunk-jghkvdgt.js} +1 -1
- package/dist/{chunk-w5fmaaxa.js → chunk-jnt7ab86.js} +4 -4
- package/dist/{chunk-t5tvt2r3.js → chunk-kggfqsgn.js} +94 -94
- package/dist/chunk-kgw1dd9b.js +1 -0
- package/dist/{chunk-j7vsrx9g.js → chunk-mgkgsp9f.js} +5 -5
- package/dist/chunk-phr1cqgf.js +1 -0
- package/dist/{chunk-nhtz2k8d.js → chunk-q4bk0htq.js} +5 -5
- package/dist/{chunk-ngdhqwf3.js → chunk-srh0ctd4.js} +3 -3
- package/dist/{chunk-8s9m8pyb.js → chunk-sxtgx8fj.js} +1 -1
- package/dist/{chunk-65ajja2a.js → chunk-t054j0zn.js} +1 -1
- package/dist/{chunk-6gtqjsg9.js → chunk-t5e5phth.js} +1 -1
- package/dist/{chunk-ds92qg3g.js → chunk-tg6yasej.js} +3 -3
- package/dist/{chunk-0g2jkhy5.js → chunk-trsaqsgv.js} +1 -1
- package/dist/chunk-vjcxf8ma.js +2 -0
- package/dist/{chunk-m5r0dt28.js → chunk-xacvkpf8.js} +2 -2
- package/dist/{chunk-nw0tvrrr.js → chunk-xv3w9q1a.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/dns/delegate-from-config.d.ts +39 -0
- package/dist/dns/index.d.ts +2 -2
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +36 -36
- package/dist/operations/index.js +1 -1
- package/dist/protection/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 +6 -6
- 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 +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +5 -5
- 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 +5 -5
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +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 +5 -5
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +2 -2
- 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 +5 -5
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +5 -5
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +5 -5
- package/dist/ui/serverless/secrets.html +5 -5
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
- package/dist/chunk-05qawkra.js +0 -1
- package/dist/chunk-3qtce4mm.js +0 -1
- package/dist/chunk-3tt5em2c.js +0 -1
- package/dist/chunk-a1p70h5d.js +0 -2
- package/dist/chunk-jdq95b4h.js +0 -1
- package/dist/chunk-wr7tn9j5.js +0 -1
package/dist/aws/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pe,Xt,Xi,Yi,
|
|
1
|
+
import{pe,Xt,Xi,Yi,Jl,wa,Ra,Zi,es,Da,Xe,V,Ye,re,C,ge,an,Pa,Ne,Na,cn,dn,ln,_m,Om,$A,MA,FA,UA,Ct,QA,HA,GA,qA,bt,Lm,$m,Mm,Et,Fm,Um,Qm,un,VA,jA,zA,Yt,KA,WA,JA,ka,Ba,Xl,XA,YA,ZA,Zt,Hm,Gm,er,Ze,pn,xa,Yl,ey,Zl,ty,vt,ry,ny,iy,sy,ne,oy,ay,cy,dy,tr,ly,uy,py,gn,_a,Oa,eu,tu,La,rr}from"../chunk-bkv2p4hp.js";import{me,et,mn,qm}from"../chunk-srh0ctd4.js";import{y}from"../chunk-sxtgx8fj.js";import{ke}from"../chunk-cwjskpj4.js";import{j}from"../chunk-1bxqrj7m.js";import{tt,ie,Be,he,Tt,hn,rs,ns,nr,ir,fn,sr,is,ss,os,as,fe,cs,ds,ls,us,se,ps,gs,ms,T,$a,An,Ma,oe,or}from"../chunk-vjcxf8ma.js";import{h}from"../chunk-t054j0zn.js";import{Ar,Ce}from"../chunk-etmbw4er.js";import{f}from"../chunk-trsaqsgv.js";import{a}from"../chunk-t5e5phth.js";import{yr,n,l,dh}from"../chunk-4w8d2mf0.js";export{oe as ACMClient,or as ACMDnsValidator,n as AWSClient,xa as ApplicationAutoScalingClient,Xt as AwsBackupClient,Om as BedrockAgentClient,_m as BedrockAgentRuntimeClient,ln as BedrockClient,dn as BedrockRuntimeClient,f as CloudFormationClient,y as CloudFrontClient,ge as CloudWatchLogsClient,he as CloudflareProvider,Ct as ComprehendClient,an as ConnectClient,es as CostExplorerClient,An as DnsProviderFactory,Ne as DynamoDBClient,Ar as EC2Client,ke as ECRClient,Xe as ECSClient,rr as EFSClient,Pa as ELBv2Client,Ze as ElastiCacheClient,mn as EmailClient,er as EventBridgeClient,Be as GoDaddyProvider,me as IAMClient,Yl as ImapServer,Zt as KendraClient,C as LambdaClient,Na as OpenSearchClient,tt as PROXIABLE_RECORD_TYPES,ka as PersonalizeClient,Xl as PersonalizeEventsClient,Ba as PersonalizeRuntimeClient,un as PollyClient,ie as PorkbunProvider,j as RDSClient,bt as RekognitionClient,h as Route53Client,Da as Route53DomainsClient,fe as Route53Provider,a as S3Client,et as SESClient,Ye as SNSClient,re as SQSClient,Ce as SSMClient,pe as STSClient,pn as SchedulerClient,V as SecretsManagerClient,vt as SmsClient,La as SmsVoiceClient,Zl as SmtpServer,gn as SupportClient,_a as SupportTemplates,Et as TextractClient,cn as TranscribeClient,Yt as TranslateClient,se as UnifiedDnsValidator,tr as VoiceClient,QA as analyzeSentiment,os as applyDeclaredZoneSettings,ls as applyZoneMigration,l as buildQueryParams,FA as completeWithClaude,qA as containsPii,$m as countFacesInS3Image,sy as createDeliveryReceiptHandler,T as createDnsProvider,gs as createGoDaddyValidator,Zi as createObjectStorageClient,ps as createPorkbunValidator,uy as createRecordingHandler,ms as createRoute53Validator,zA as createSSML,ny as createScheduledSmsHandler,iy as createSmsClient,ry as createSmsInboxHandler,tu as createSmsInfrastructure,py as createVoiceClient,ly as createVoicemailHandler,sr as delegateZone,is as delegateZoneFromConfig,ss as describeDelegation,as as describeZoneSettings,dh as detectCredentialSource,$a as detectDnsProvider,Lm as detectLabelsFromS3,GA as detectLanguage,Ma as dnsProviders,qm as email,cs as exportRoute53Zone,HA as extractEntities,Um as extractFormsFromS3,Qm as extractTablesFromS3,Fm as extractTextFromS3,oy as formatPhoneNumber,UA as generateEmbeddings,cy as getCountryCode,XA as getRecommendations,YA as getSimilarItems,eu as getSmsInfrastructureStatus,Mm as isContentSafe,nr as isNameserverRegistrar,dy as isSamePhoneNumber,ay as isValidPhoneNumber,ir as isZoneHost,Yi as keyMatchesFilters,MA as listClaudeModels,JA as listLanguages,jA as listVoices,Jl as migrateObjectStorage,ne as normalizePhoneNumber,ds as planZoneMigration,Tt as policyTag,wa as providerEndpoint,hn as qualifyName,ns as reconcileDeclaredRecords,Xi as remapKey,$A as requestModelAccess,rs as resolveDeclaredRecords,Ra as resolveObjectStorage,yr as resolveS3Endpoint,Gm as retrieveForRag,fn as sameNameservers,Hm as search,Oa as setupSmsInfrastructure,ey as startImapServer,ty as startSmtpServer,VA as textToSpeech,ZA as trackEvent,KA as translate,WA as translateToMultiple,us as verifyZoneParity};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Cl,Al,Il,Rl,du,uu}from"./chunk-
|
|
1
|
+
import{Cl,Al,Il,Rl,du,uu}from"./chunk-fr69rgea.js";import"./chunk-k8wscjd9.js";import"./chunk-pthfzst7.js";import"./chunk-pd8v6bpd.js";import"./chunk-p197a99s.js";import"./chunk-k3er0h4j.js";import"./chunk-pdw0qjq1.js";export{du as deleteStaticSite,Al as deployStaticSite,uu as deployStaticSiteFull,Cl as generateStaticSiteTemplate,Rl as invalidateCache,Il as uploadStaticFiles};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{jr,q,ji,_t,L}from"./chunk-
|
|
1
|
+
import{jr,q,ji,_t,L}from"./chunk-k8wscjd9.js";import{v}from"./chunk-pd8v6bpd.js";import{w}from"./chunk-pthfzst7.js";import{f}from"./chunk-k3er0h4j.js";import{O}from"./chunk-p197a99s.js";function _(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:A=!1,computeOriginDomain:D,computeOriginPort:E=3008,computeOriginId:F="app-compute",retainOnStackDelete:U=!1}=t,C=U?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},h=A&&!!D,V=h?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],x=h?["GET","HEAD"]:["GET","HEAD"],R={},T={};R.S3Bucket={Type:"AWS::S3::Bucket",...C,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},T.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},T.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},R.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...C,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let y;if(a&&h)y="InstallRootRedirectFunction",R[y]={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{jr,q,ji,_t,L}from"./chunk-2ahgpy3j.js";import{v}from"./chunk-pd8v6bpd.js"
|
|
|
42
42
|
│ │
|
|
43
43
|
│ Verification typically takes 1-2 business days. │
|
|
44
44
|
│ After verification, re-run: bunx bunpress deploy │
|
|
45
|
-
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:T,stackName:i,bucket:h,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:T,stackName:i,bucket:h,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],S=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,b=S("DistributionDomain");if(b&&d)console.log(`Creating DNS records via ${d.name}...`),await H(d,e,b);else if(b&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:T,stackName:i,bucket:S("BucketName")||h,distributionId:S("DistributionId"),distributionDomain:b,domain:e,certificateArn:A,message:"Static site infrastructure deployed successfully with external DNS"}}async function H(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof jr){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 A of d.records){let D=A.name.replace(/\.$/,"");if(D===s||D==="")console.log(`Removing existing root A record (${A.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:A.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 Ti(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 f(m.region||"us-east-1").emptyBucket(i.bucket)}catch(A){console.log(`Note: Could not clean bucket: ${A.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-
|
|
45
|
+
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:T,stackName:i,bucket:h,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:T,stackName:i,bucket:h,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],S=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,b=S("DistributionDomain");if(b&&d)console.log(`Creating DNS records via ${d.name}...`),await H(d,e,b);else if(b&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:T,stackName:i,bucket:S("BucketName")||h,distributionId:S("DistributionId"),distributionDomain:b,domain:e,certificateArn:A,message:"Static site infrastructure deployed successfully with external DNS"}}async function H(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof jr){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 A of d.records){let D=A.name.replace(/\.$/,"");if(D===s||D==="")console.log(`Removing existing root A record (${A.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:A.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 Ti(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 f(m.region||"us-east-1").emptyBucket(i.bucket)}catch(A){console.log(`Note: Could not clean bucket: ${A.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-1qn174w2.js"),a=await r({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(A,D,E)=>{e?.("upload",`${A}/${D}: ${E}`)}});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:A}=await import("./chunk-1qn174w2.js");await A(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 Cl(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:m,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
46
46
|
const request = event.request;
|
|
47
47
|
var uri = request.uri;
|
|
48
48
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{u}from"./chunk-pdw0qjq1.js";import{O}from"./chunk-p197a99s.js";var D=new Set(["A","AAAA","CNAME"]);function P(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 v(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 ze{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 v(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!P(s.status)||n===8)throw r;await v(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!P(0,a.message)||n===8)throw r;await v(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(!ze.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(ze.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(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class xt{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 b="https://api.cloudflare.com/client/v4",w="[ts-cloud]";class qe{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=`${b}${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&&D.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=I(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&&A(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(w)),i=r.map((c)=>({...c,description:c.description?.startsWith(w)?c.description:`${w} ${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 A(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)=>A(s,t[o]))}let r=e,n=t;return Object.keys(n).every((s)=>A(r[s],n[s]))}function I(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:N(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:N(r.slice(3).join(" "))}}function N(e){return e.replace(/\.$/,"")}var E=new Set(["A","AAAA","CNAME","ALIAS"]);function h(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function R(e){return e.replace(/\.$/,"").toLowerCase()}function S(e,t){let r=R(t),n=(e??"@").trim();if(!n||n==="@")return r;let s=R(n);if(s===r||s.endsWith(`.${r}`))return s;return`${s}.${r}`}function Oi(e,t){return e.map((r)=>({...r,name:S(r.name,t),proxied:r.proxied??!1}))}function x(e,t){if(e.type!==t.type)return!1;if(R(e.name)!==R(t.name))return!1;if(E.has(t.type))return!0;if(t.type==="TXT"){let r=h(t.content);if(r)return h(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function k(e,t){if(f(e.content)!==f(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 Li(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((l)=>x(l,a));if(c.length>0&&c.every((l)=>k(l,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"&&h(a.content)!==void 0;if(m)for(let l of c){let C=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!C.success)s.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${C.message||"unknown error"}`)}let p=m||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:p.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>R(d.name)));for(let d of c){let m=new Set(n.filter((l)=>l.type===a&&R(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&R(l.name)===d&&!m.has(f(l.content).toLowerCase()));for(let l of p)s.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class jr{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new O(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:O.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=O.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 Mi(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 g(e){return e.replace(/\.$/,"").toLowerCase()}function T(e){return e.replace(/\.$/,"")}function y(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${T(e.content)}`;return T(e.content)}function M(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Ui(e,t){let r=g(t),n=[],s=[],o=[],i=new Set;for(let a of e){let c=g(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=g(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 p=z(c,d,m.Value,a.TTL);if("reason"in p){s.push({name:c,type:d,reason:p.reason}),o.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:s,warnings:o}}function z(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:g(r)};case"TXT":return{...s,type:"TXT",content:M(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:g(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:g(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:g(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var U=new Set(["TXT","MX","SRV","NS","CAA"]);async function Bi(e,t){let r=[],n=[],s=new Set;try{let o=await e.listRecords(t.zone);for(let i of o.records||[])s.add(`${g(i.name)}|${i.type}|${y(i)}`)}catch{}for(let o of t.records){let i={...o,proxied:!1},a=`${g(o.name)}|${o.type}|${y(o)}`;if(!U.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 Fi(e,t){let r=await e.listRecords(t.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${g(i.name)}|${i.type}`,c=o.get(a)??[];c.push(y(i)),o.set(a,c)}for(let i of t.records){let a=o.get(`${g(i.name)}|${i.type}`),c=y(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 _t{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new q(t),"provider"in e)this.dnsProvider=L(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 L(e){switch(e.provider){case"route53":return new jr(e.region,e.hostedZoneId);case"porkbun":return new ze(e.apiKey,e.secretKey);case"godaddy":return new xt(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new qe(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class Xn{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=L(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=L(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>L(e))}}var ye=new Xn;class q{client;region;constructor(e="us-east-1"){this.client=new u,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 ji{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new q(e),this.route53=new O,t&&t.provider!=="route53")this.dnsProvider=L(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"}}
|
|
1
|
+
import{u}from"./chunk-pdw0qjq1.js";import{O}from"./chunk-p197a99s.js";var D=new Set(["A","AAAA","CNAME"]);function P(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 v(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 ze{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 v(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!P(s.status)||n===8)throw r;await v(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!P(0,a.message)||n===8)throw r;await v(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(!ze.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(ze.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(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class xt{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 b="https://api.cloudflare.com/client/v4",w="[ts-cloud]";class qe{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=`${b}${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&&D.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=I(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&&A(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(w)),i=r.map((c)=>({...c,description:c.description?.startsWith(w)?c.description:`${w} ${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 A(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)=>A(s,t[o]))}let r=e,n=t;return Object.keys(n).every((s)=>A(r[s],n[s]))}function I(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:S(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:S(r.slice(3).join(" "))}}function S(e){return e.replace(/\.$/,"")}var E=new Set(["A","AAAA","CNAME","ALIAS"]);function R(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function N(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 Oi(e,t){return e.map((r)=>({...r,name:N(r.name,t),proxied:r.proxied??!1}))}function x(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(E.has(t.type))return!0;if(t.type==="TXT"){let r=R(t.content);if(r)return R(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function k(e,t){if(f(e.content)!==f(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 Li(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((l)=>x(l,a));if(c.length>0&&c.every((l)=>k(l,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"&&R(a.content)!==void 0;if(m)for(let l of c){let C=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!C.success)s.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${C.message||"unknown error"}`)}let p=m||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:p.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((l)=>l.type===a&&h(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&h(l.name)===d&&!m.has(f(l.content).toLowerCase()));for(let l of p)s.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class jr{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new O(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:O.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=O.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 Mi(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 g(e){return e.replace(/\.$/,"").toLowerCase()}function T(e){return e.replace(/\.$/,"")}function y(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${T(e.content)}`;return T(e.content)}function M(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Ui(e,t){let r=g(t),n=[],s=[],o=[],i=new Set;for(let a of e){let c=g(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=g(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 p=z(c,d,m.Value,a.TTL);if("reason"in p){s.push({name:c,type:d,reason:p.reason}),o.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:s,warnings:o}}function z(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:g(r)};case"TXT":return{...s,type:"TXT",content:M(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:g(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:g(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:g(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var U=new Set(["TXT","MX","SRV","NS","CAA"]);async function Bi(e,t){let r=[],n=[],s=new Set;try{let o=await e.listRecords(t.zone);for(let i of o.records||[])s.add(`${g(i.name)}|${i.type}|${y(i)}`)}catch{}for(let o of t.records){let i={...o,proxied:!1},a=`${g(o.name)}|${o.type}|${y(o)}`;if(!U.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 Fi(e,t){let r=await e.listRecords(t.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${g(i.name)}|${i.type}`,c=o.get(a)??[];c.push(y(i)),o.set(a,c)}for(let i of t.records){let a=o.get(`${g(i.name)}|${i.type}`),c=y(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 _t{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new q(t),"provider"in e)this.dnsProvider=L(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 L(e){switch(e.provider){case"route53":return new jr(e.region,e.hostedZoneId);case"porkbun":return new ze(e.apiKey,e.secretKey);case"godaddy":return new xt(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new qe(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class Xn{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=L(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=L(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>L(e))}}var ve=new Xn;class q{client;region;constructor(e="us-east-1"){this.client=new u,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 ji{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new q(e),this.route53=new O,t&&t.provider!=="route53")this.dnsProvider=L(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"}}
|
|
2
2
|
export{ze,xt,qe,Oi,Li,jr,Mi,Ui,Bi,Fi,q,ji,_t,L,Xn};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{q,ji}from"./chunk-
|
|
1
|
+
import{q,ji}from"./chunk-k8wscjd9.js";import"./chunk-p197a99s.js";import"./chunk-pdw0qjq1.js";export{q as ACMClient,ji as ACMDnsValidator};
|