@stacksjs/ts-cloud 0.12.16 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-9wjgxjqp.js → chunk-22c3pk8s.js} +48 -48
  3. package/dist/bin/chunk-2ahgpy3j.js +2 -0
  4. package/dist/bin/chunk-2synp9gh.js +1 -0
  5. package/dist/bin/{chunk-zhpzxnpg.js → chunk-2v0qm547.js} +1 -1
  6. package/dist/bin/{chunk-52wgrpe8.js → chunk-88ysj8n5.js} +1 -1
  7. package/dist/bin/{chunk-6tty6sjf.js → chunk-8bbw6qc2.js} +1 -1
  8. package/dist/bin/{chunk-2shtky1g.js → chunk-9qndhwbe.js} +1 -1
  9. package/dist/bin/{chunk-a76krpa1.js → chunk-bdgkeqv6.js} +1 -1
  10. package/dist/bin/chunk-c82rh7qe.js +1 -0
  11. package/dist/bin/{chunk-e3d9m062.js → chunk-d4bb9qg9.js} +1 -1
  12. package/dist/bin/{chunk-tpjepvwa.js → chunk-d6kqbp8q.js} +1 -1
  13. package/dist/bin/{chunk-a8rn2wym.js → chunk-dk38j1qr.js} +9 -9
  14. package/dist/bin/{chunk-9vrnrxay.js → chunk-e1cxh9rj.js} +2 -2
  15. package/dist/bin/{chunk-9k60q9qz.js → chunk-edaq5jef.js} +3 -3
  16. package/dist/bin/{chunk-srw2jmh3.js → chunk-fbycbnvj.js} +4 -4
  17. package/dist/bin/chunk-fj89173b.js +1 -0
  18. package/dist/bin/{chunk-xyk8qe2c.js → chunk-gxwsq3k0.js} +21 -21
  19. package/dist/bin/{chunk-ebdybz7x.js → chunk-hwp5xp1c.js} +35 -35
  20. package/dist/bin/{chunk-ndbtr4mb.js → chunk-jee6msvx.js} +3 -3
  21. package/dist/bin/chunk-kjatss6s.js +1 -0
  22. package/dist/bin/{chunk-mekcw1zn.js → chunk-kxa4t4wh.js} +2 -2
  23. package/dist/bin/{chunk-8sxb2rr0.js → chunk-m5sjzxm3.js} +1 -1
  24. package/dist/bin/{chunk-7xszcdqn.js → chunk-n56c0j1e.js} +4 -4
  25. package/dist/bin/{chunk-be7rhw60.js → chunk-rzt92fwv.js} +3 -3
  26. package/dist/bin/{chunk-zav02r6k.js → chunk-vwzgtsn9.js} +1 -1
  27. package/dist/bin/{chunk-dvm4n8m8.js → chunk-w0g72e50.js} +1 -1
  28. package/dist/bin/chunk-wb8y7zey.js +1 -0
  29. package/dist/bin/{chunk-y24gfke7.js → chunk-x4gsw45d.js} +5 -5
  30. package/dist/bin/{chunk-hzj5r6b7.js → chunk-xs62dg7t.js} +2 -2
  31. package/dist/bin/{chunk-k7w2ztw9.js → chunk-xtp2zf3j.js} +1 -1
  32. package/dist/bin/{chunk-5qann9n2.js → chunk-xw9vcdwt.js} +1 -1
  33. package/dist/bin/{chunk-3zq0wkz2.js → chunk-y671cgz5.js} +1 -1
  34. package/dist/bin/cli.js +76 -76
  35. package/dist/bin/dashboard-server.js +1 -1
  36. package/dist/chunk-05qawkra.js +1 -0
  37. package/dist/{chunk-qszktnnz.js → chunk-0g2jkhy5.js} +1 -1
  38. package/dist/{chunk-crpjqnjb.js → chunk-2s65yj3g.js} +4 -4
  39. package/dist/chunk-3qtce4mm.js +1 -0
  40. package/dist/chunk-3tt5em2c.js +1 -0
  41. package/dist/{chunk-hw3p6pth.js → chunk-42kv07cs.js} +1 -1
  42. package/dist/{chunk-nr1bdzwy.js → chunk-65ajja2a.js} +1 -1
  43. package/dist/{chunk-rtg6nw3n.js → chunk-6gtqjsg9.js} +3 -3
  44. package/dist/{chunk-a7v15116.js → chunk-8s9m8pyb.js} +1 -1
  45. package/dist/chunk-a1p70h5d.js +2 -0
  46. package/dist/{chunk-j9rv5m58.js → chunk-asmv4fw1.js} +19 -19
  47. package/dist/{chunk-a6zymyfs.js → chunk-ds92qg3g.js} +4 -4
  48. package/dist/{chunk-93mgdgd5.js → chunk-dzqz1sm0.js} +3 -3
  49. package/dist/{chunk-wz57brcf.js → chunk-hyj2ymp1.js} +6 -6
  50. package/dist/{chunk-1zz5n6q8.js → chunk-j7vsrx9g.js} +5 -5
  51. package/dist/chunk-jdq95b4h.js +1 -0
  52. package/dist/{chunk-wxv3ypt5.js → chunk-m5r0dt28.js} +2 -2
  53. package/dist/{chunk-bga3mw5f.js → chunk-mcfdtg5w.js} +1 -1
  54. package/dist/{chunk-4ywy6dp5.js → chunk-ngdhqwf3.js} +3 -3
  55. package/dist/{chunk-6znnde1s.js → chunk-nhtz2k8d.js} +5 -5
  56. package/dist/{chunk-kazw813q.js → chunk-nw0tvrrr.js} +1 -1
  57. package/dist/{chunk-d1tv3wx0.js → chunk-p9fqsz06.js} +2 -2
  58. package/dist/{chunk-qzwack6w.js → chunk-r4dpn715.js} +7 -7
  59. package/dist/{chunk-ajq92t46.js → chunk-t5tvt2r3.js} +124 -124
  60. package/dist/{chunk-jk7ecnmc.js → chunk-vk513ge7.js} +78 -78
  61. package/dist/{chunk-mherymtx.js → chunk-w5fmaaxa.js} +4 -4
  62. package/dist/chunk-wr7tn9j5.js +1 -0
  63. package/dist/{chunk-7hjsnwcv.js → chunk-xqx5szta.js} +27 -27
  64. package/dist/{chunk-thghrpf9.js → chunk-y13zcbnp.js} +101 -101
  65. package/dist/{chunk-bgrre2px.js → chunk-z7v4evbh.js} +2 -2
  66. package/dist/deploy/index.js +1 -1
  67. package/dist/dns/delegate-from-config.d.ts +50 -0
  68. package/dist/dns/delegate-from-config.test.d.ts +1 -0
  69. package/dist/dns/delegation.d.ts +110 -0
  70. package/dist/dns/delegation.test.d.ts +1 -0
  71. package/dist/dns/index.d.ts +4 -0
  72. package/dist/dns/index.js +1 -1
  73. package/dist/dns/porkbun-nameservers.test.d.ts +1 -0
  74. package/dist/drivers/index.js +1 -1
  75. package/dist/index.d.ts +1 -1
  76. package/dist/index.js +49 -49
  77. package/dist/operations/index.js +1 -1
  78. package/dist/protection/index.js +1 -1
  79. package/dist/spend/index.js +1 -1
  80. package/dist/ui/404.html +1 -1
  81. package/dist/ui/accept-invitation.html +1 -1
  82. package/dist/ui/access-denied.html +1 -1
  83. package/dist/ui/account/automation.html +6 -6
  84. package/dist/ui/account/security.html +2 -2
  85. package/dist/ui/applications/compose.html +6 -6
  86. package/dist/ui/applications/new.html +1 -1
  87. package/dist/ui/data/backups.html +6 -6
  88. package/dist/ui/data/services.html +6 -6
  89. package/dist/ui/data/volumes.html +6 -6
  90. package/dist/ui/index.html +6 -6
  91. package/dist/ui/infrastructure/topology.html +6 -6
  92. package/dist/ui/integrations.html +2 -2
  93. package/dist/ui/operations/alerts.html +6 -6
  94. package/dist/ui/operations/configuration.html +6 -6
  95. package/dist/ui/operations/jobs.html +5 -5
  96. package/dist/ui/operations/maintenance.html +5 -5
  97. package/dist/ui/operations/observability.html +6 -6
  98. package/dist/ui/operations/previews.html +6 -6
  99. package/dist/ui/operations/queue.html +6 -6
  100. package/dist/ui/operations/regions.html +5 -5
  101. package/dist/ui/operations/releases.html +6 -6
  102. package/dist/ui/operations/spend.html +6 -6
  103. package/dist/ui/operations/workloads.html +6 -6
  104. package/dist/ui/security.html +2 -2
  105. package/dist/ui/server/actions.html +6 -6
  106. package/dist/ui/server/activity.html +1 -1
  107. package/dist/ui/server/capacity.html +6 -6
  108. package/dist/ui/server/database.html +6 -6
  109. package/dist/ui/server/deployments.html +6 -6
  110. package/dist/ui/server/diagnostics.html +2 -2
  111. package/dist/ui/server/firewall.html +6 -6
  112. package/dist/ui/server/fleet.html +6 -6
  113. package/dist/ui/server/logs.html +6 -6
  114. package/dist/ui/server/metrics.html +6 -6
  115. package/dist/ui/server/security.html +2 -2
  116. package/dist/ui/server/services.html +2 -2
  117. package/dist/ui/server/sites.html +6 -6
  118. package/dist/ui/server/ssh-keys.html +6 -6
  119. package/dist/ui/server/team.html +5 -5
  120. package/dist/ui/server/terminal.html +2 -2
  121. package/dist/ui/serverless/alarms.html +6 -6
  122. package/dist/ui/serverless/assets.html +2 -2
  123. package/dist/ui/serverless/cost.html +2 -2
  124. package/dist/ui/serverless/data.html +6 -6
  125. package/dist/ui/serverless/deployments.html +2 -2
  126. package/dist/ui/serverless/firewall.html +2 -2
  127. package/dist/ui/serverless/functions.html +6 -6
  128. package/dist/ui/serverless/logs.html +6 -6
  129. package/dist/ui/serverless/metrics.html +2 -2
  130. package/dist/ui/serverless/queues.html +6 -6
  131. package/dist/ui/serverless/secrets.html +6 -6
  132. package/dist/ui/serverless/traces.html +6 -6
  133. package/dist/ui/serverless.html +5 -5
  134. package/package.json +3 -3
  135. package/dist/bin/chunk-005sxfmc.js +0 -1
  136. package/dist/bin/chunk-4vgbynq6.js +0 -1
  137. package/dist/bin/chunk-bwvnfc74.js +0 -1
  138. package/dist/bin/chunk-cy4wwpnf.js +0 -1
  139. package/dist/bin/chunk-dxfsq94k.js +0 -2
  140. package/dist/bin/chunk-dy10cmt9.js +0 -1
  141. package/dist/chunk-8fcrgq31.js +0 -1
  142. package/dist/chunk-8msfne57.js +0 -2
  143. package/dist/chunk-eadp23eh.js +0 -1
  144. package/dist/chunk-jpbgr1wg.js +0 -1
  145. package/dist/chunk-w7710vzg.js +0 -1
  146. package/dist/chunk-xfdpxsbc.js +0 -1
@@ -1 +1 @@
1
- import"./chunk-xyk8qe2c.js";import"./chunk-6tty6sjf.js";import"./chunk-a8rn2wym.js";import{Zt}from"./chunk-9wjgxjqp.js";import"./chunk-pdw0qjq1.js";import"./chunk-t7seq21w.js";import"./chunk-k3er0h4j.js";import"./chunk-8sxb2rr0.js";import"./chunk-ebdybz7x.js";import"./chunk-pd8v6bpd.js";import"./chunk-hzj5r6b7.js";import"./chunk-9jmnmhpy.js";import"./chunk-pthfzst7.js";import"./chunk-dxfsq94k.js";import"./chunk-mekcw1zn.js";import"./chunk-b48j6k55.js";import"./chunk-mcqkjhgp.js";import"./chunk-y1r1evt0.js";import"./chunk-y24gfke7.js";import"./chunk-srw2jmh3.js";import"./chunk-7xszcdqn.js";import"./chunk-be7rhw60.js";import"./chunk-9vrnrxay.js";import"./chunk-94cfdvrn.js";import"./chunk-p197a99s.js";import"./chunk-7jwxgxxf.js";import n from"node:process";function r(o){let e=n.argv.indexOf(o);return e===-1?void 0:n.argv[e+1]}function t(o){return n.argv.includes(o)}async function i(){let o=await Zt({host:r("--host")??"127.0.0.1",port:Number(r("--port")??7676),environment:r("--env"),box:t("--box"),verbose:t("--verbose")});console.log("ts-cloud Local Dashboard"),console.log(`Serving ${o.url}`),await new Promise((e)=>{let s=()=>{o.server.stop(!0),e()};n.once("SIGINT",s),n.once("SIGTERM",s)})}i();
1
+ import"./chunk-gxwsq3k0.js";import"./chunk-8bbw6qc2.js";import"./chunk-dk38j1qr.js";import{er}from"./chunk-22c3pk8s.js";import"./chunk-pdw0qjq1.js";import"./chunk-t7seq21w.js";import"./chunk-k3er0h4j.js";import"./chunk-m5sjzxm3.js";import"./chunk-hwp5xp1c.js";import"./chunk-pd8v6bpd.js";import"./chunk-xs62dg7t.js";import"./chunk-9jmnmhpy.js";import"./chunk-pthfzst7.js";import"./chunk-2ahgpy3j.js";import"./chunk-kxa4t4wh.js";import"./chunk-b48j6k55.js";import"./chunk-mcqkjhgp.js";import"./chunk-y1r1evt0.js";import"./chunk-x4gsw45d.js";import"./chunk-fbycbnvj.js";import"./chunk-n56c0j1e.js";import"./chunk-rzt92fwv.js";import"./chunk-e1cxh9rj.js";import"./chunk-94cfdvrn.js";import"./chunk-p197a99s.js";import"./chunk-7jwxgxxf.js";import n from"node:process";function r(o){let e=n.argv.indexOf(o);return e===-1?void 0:n.argv[e+1]}function t(o){return n.argv.includes(o)}async function i(){let o=await er({host:r("--host")??"127.0.0.1",port:Number(r("--port")??7676),environment:r("--env"),box:t("--box"),verbose:t("--verbose")});console.log("ts-cloud Local Dashboard"),console.log(`Serving ${o.url}`),await new Promise((e)=>{let s=()=>{o.server.stop(!0),e()};n.once("SIGINT",s),n.once("SIGTERM",s)})}i();
@@ -0,0 +1 @@
1
+ import{yr,n,l,ah}from"./chunk-2s65yj3g.js";export{n as AWSClient,l as buildQueryParams,ah as detectCredentialSource,yr as resolveS3Endpoint};
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-crpjqnjb.js";class f{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
1
+ import{n}from"./chunk-2s65yj3g.js";class f{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
2
  export{f};
@@ -1,6 +1,6 @@
1
- import*as T from"node:crypto";import{existsSync as W,readFileSync as J}from"node:fs";import{homedir as B}from"node:os";import{join as K}from"node:path";var z={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},H={nbsp:" ",copy:"©",reg:"®",trade:"™",euro:"€",pound:"£",yen:"¥",cent:"¢",deg:"°",micro:"µ",middot:"·",bull:"•",hellip:"…",prime:"′",Prime:"″",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",ndash:"–",mdash:"—",iexcl:"¡",iquest:"¿",sect:"§",para:"¶",dagger:"†",Dagger:"‡",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",times:"×",divide:"÷",plusmn:"±",ne:"≠",le:"≤",ge:"≥",infin:"∞",fnof:"ƒ",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",equiv:"≡",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜"};class R{customEntities={};useHtmlEntities;constructor(t=!1){this.useHtmlEntities=t}addEntity(t,e){this.customEntities[t]=e}decodeEntities(t){let e=t.indexOf("&");if(e===-1)return t;let r=t.length,i="",s=0;while(e!==-1&&e<r){if(e>s)i+=t.substring(s,e);let a=t.indexOf(";",e+1);if(a===-1||a-e>32){i+="&",s=e+1,e=t.indexOf("&",s);continue}let o=t.substring(e+1,a);if(o.charCodeAt(0)===35){let c=o.length,h=0,A=!1;if(c>2&&(o.charCodeAt(1)===120||o.charCodeAt(1)===88)){A=!0;for(let m=2;m<c;m++){let f=o.charCodeAt(m);if(f>=48&&f<=57)h=h<<4|f-48;else if(f>=65&&f<=70)h=h<<4|f-55;else if(f>=97&&f<=102)h=h<<4|f-87;else{A=!1;break}}}else if(c>1){A=!0;for(let m=1;m<c;m++){let f=o.charCodeAt(m);if(f>=48&&f<=57)h=h*10+(f-48);else{A=!1;break}}}if(A)i+=String.fromCodePoint(h);else i+=t.substring(e,a+1)}else{let c=this.customEntities[o];if(c===void 0){let h=o.length;if(h>=2&&h<=4){let A=o.charCodeAt(0);if(A===108&&h===2&&o.charCodeAt(1)===116)c="<";else if(A===103&&h===2&&o.charCodeAt(1)===116)c=">";else if(A===97&&h===3&&o.charCodeAt(1)===109&&o.charCodeAt(2)===112)c="&";else if(A===113&&h===4)c=o==="quot"?'"':void 0;else if(A===97&&h===4)c=o==="apos"?"'":void 0}if(c===void 0)c=z[o]??(this.useHtmlEntities?H[o]:void 0)}if(c!==void 0)i+=c;else i+=t.substring(e,a+1)}s=a+1,e=t.indexOf("&",s)}if(s<r)i+=t.substring(s);return i}}var P=[];P[38]="&amp;";P[60]="&lt;";P[62]="&gt;";P[34]="&quot;";P[39]="&apos;";var L={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,alwaysCreateTextNode:!1,trimValues:!0,parseTagValue:!0,parseAttributeValue:!1,processEntities:!0,htmlEntities:!1,commentPropName:!1,cdataPropName:!1,piPropName:!1,preserveOrder:!1,stopNodes:[],unpairedTags:[],isArray:void 0,tagValueProcessor:void 0,attributeValueProcessor:void 0,updateTag:void 0,numberParseOptions:{hex:!0,leadingZeros:!0,scientific:!0},ignorePiTags:!1,transformAttributeName:void 0,transformTagName:void 0,ignoreDeclaration:!1};function _(t){return t===32||t===9||t===10||t===13}function x(t){return t>=65&&t<=90||t>=97&&t<=122||t===95||t===58||t>=192&&t<=214||t>=216&&t<=246||t>=248&&t<=767||t>=880&&t<=893||t>=895&&t<=8191||t>=8204&&t<=8205||t>=8304&&t<=8591||t>=11264&&t<=12271||t>=12289&&t<=55295||t>=63744&&t<=64975||t>=65008&&t<=65533}function V(t){return x(t)||t===45||t===46||t>=48&&t<=57||t===183||t>=768&&t<=879||t>=8255&&t<=8256}var X=/^0x[\da-fA-F]+$/,M=/^[+-]?\d+(\.\d+)?[eE][+-]?\d+$/,G=/^[+-]?(\d+\.?\d*|\.\d+)$/;function D(t,e){return t.charCodeAt(e)===91&&t.charCodeAt(e+1)===67&&t.charCodeAt(e+2)===68&&t.charCodeAt(e+3)===65&&t.charCodeAt(e+4)===84&&t.charCodeAt(e+5)===65&&t.charCodeAt(e+6)===91}function k(t,e){let r=t.charCodeAt(e),i=t.charCodeAt(e+1),s=t.charCodeAt(e+2),a=t.charCodeAt(e+3),o=t.charCodeAt(e+4),c=t.charCodeAt(e+5),h=t.charCodeAt(e+6);return(r===68||r===100)&&(i===79||i===111)&&(s===67||s===99)&&(a===84||a===116)&&(o===89||o===121)&&(c===80||c===112)&&(h===69||h===101)}function Y(t,e,r){if(e>=r||!x(t.charCodeAt(e)))return e;e++;while(e<r&&V(t.charCodeAt(e)))e++;return e}class v{options;entityDecoder;unpairedSet;exactStopNodes;wildcardStopSuffixes;needsJPath;_ignoreAttributes=!0;_textNodeName="#text";_commentPropName=!1;_cdataPropName=!1;_piPropName=!1;_alwaysCreateTextNode=!1;_trimValues=!0;_processEntities=!0;_parseTagValue=!0;_parseAttributeValue=!1;_removeNSPrefix=!1;_attrPrefix="@_";_attrsGroupName=!1;_ignorePiTags=!1;_ignoreDeclaration=!1;constructor(t){this.options={...L,...t},this.entityDecoder=new R(this.options.htmlEntities),this.unpairedSet=new Set(this.options.unpairedTags),this.exactStopNodes=new Set,this.wildcardStopSuffixes=[];for(let e of this.options.stopNodes)if(e.startsWith("*."))this.wildcardStopSuffixes.push(e.substring(2));else this.exactStopNodes.add(e);this._ignoreAttributes=this.options.ignoreAttributes,this._textNodeName=this.options.textNodeName,this._commentPropName=this.options.commentPropName,this._cdataPropName=this.options.cdataPropName,this._piPropName=this.options.piPropName,this._alwaysCreateTextNode=this.options.alwaysCreateTextNode,this._trimValues=this.options.trimValues,this._processEntities=this.options.processEntities,this._parseTagValue=this.options.parseTagValue,this._parseAttributeValue=this.options.parseAttributeValue,this._removeNSPrefix=this.options.removeNSPrefix,this._attrPrefix=this.options.attributeNamePrefix,this._attrsGroupName=this.options.attributesGroupName,this._ignorePiTags=this.options.ignorePiTags,this._ignoreDeclaration=this.options.ignoreDeclaration,this.needsJPath=this.options.stopNodes.length>0||this.options.isArray!==void 0||this.options.updateTag!==void 0||this.options.tagValueProcessor!==void 0||this.options.attributeValueProcessor!==void 0}addEntity(t,e){this.entityDecoder.addEntity(t,e)}parse(t){if(t instanceof Uint8Array)t=new TextDecoder().decode(t);let e=t;if(this.options.preserveOrder)return this.parseOrdered(e);return this.parseUnordered(e)}parseUnordered(t){let e={},r=t.length,i=0;if(r>0&&t.charCodeAt(0)===65279)i=1;return i=this.parseChildren(t,i,r,e,"",[]),e}parseOrdered(t){let e=t.length,r=0;if(e>0&&t.charCodeAt(0)===65279)r=1;let i=[];return this.parseChildrenOrdered(t,r,e,i,""),i}readTagName(t,e,r){return Y(t,e,r)}extractTagName(t,e,r){let i=t.substring(e,r);if(this._removeNSPrefix){let s=i.indexOf(":");if(s!==-1)i=i.substring(s+1)}if(this.options.transformTagName)i=this.options.transformTagName(i);return i}parseAttributes(t,e,r,i,s){let a=0,o=this._removeNSPrefix,c=this.options.transformAttributeName,h=this._trimValues,A=this._processEntities,m=this.options.attributeValueProcessor;while(e<r){let f=t.charCodeAt(e);while(f===32||f===9||f===10||f===13){if(e++,e>=r)break;f=t.charCodeAt(e)}if(e>=r)break;if(f===62||f===47)break;let b=e;if(!x(f))break;e++;while(e<r&&V(t.charCodeAt(e)))e++;let p=t.substring(b,e);if(o){let C=p.indexOf(":");if(C!==-1)p=p.substring(C+1)}if(c)p=c(p);while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===61){e++;while(e<r&&_(t.charCodeAt(e)))e++;if(e>=r)break;let C=t.charCodeAt(e);if(C===34||C===39){e++;let E=e;while(e<r&&t.charCodeAt(e)!==C)e++;let d=t.substring(E,e);if(h&&d.length>0){let u=d.charCodeAt(0),g=d.charCodeAt(d.length-1);if(u<=32||g<=32)d=d.trim()}if(A)d=this.entityDecoder.decodeEntities(d);if(m)d=m(p,d,i)??d;if(s[p]=d,a++,e<r)e++}}else s[p]="true",a++}return a>0?-e-1:e}processTagValue(t,e,r,i,s){if(this._trimValues){let a=t.length;if(a>0){let o=t.charCodeAt(0),c=t.charCodeAt(a-1);if(o<=32||c<=32)t=t.trim()}}if(this._processEntities)t=this.entityDecoder.decodeEntities(t);if(this.options.tagValueProcessor){let a=this.options.tagValueProcessor(e,t,r,i,s);if(a!==void 0)t=a}if(!t)return t;if(this._parseTagValue)return this.parseValue(t);return t}parseValue(t){if(t==="true")return!0;if(t==="false")return!1;if(!t)return t;let e=t.charCodeAt(0);if(!(e>=48&&e<=57||e===43||e===45||e===46))return t;let i=this.options.numberParseOptions;if(i.skipLike?.test(t))return t;if(i.hex&&e===48&&X.test(t))return Number.parseInt(t,16);if(t.length>1&&e===48&&t.charCodeAt(1)!==46){if(i.leadingZeros)return t}if(i.scientific&&M.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}if(G.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}return t}parseAttributeValue(t){if(!this._parseAttributeValue)return t;return this.parseValue(t)}isStopNode(t){if(this.exactStopNodes.has(t))return!0;for(let e of this.wildcardStopSuffixes)if(t.endsWith(`.${e}`)||t===e)return!0;return!1}readStopNodeContent(t,e,r,i){let s=`</${i}`,a=t.indexOf(s,e);if(a===-1)return{content:t.substring(e),pos:r};let o=t.substring(e,a),c=a+s.length;while(c<r&&t.charCodeAt(c)!==62)c++;if(c<r)c++;return{content:o,pos:c}}addToObj(t,e,r,i,s,a){let o=t[e];if(o!==void 0)if(!Array.isArray(o))t[e]=[o,r];else o.push(r);else if(this.options.isArray?.(e,i,s,a))t[e]=[r];else t[e]=r}flushText(t,e,r,i){if(!t&&!e)return;let s=this._textNodeName;if(e){let a=t;if(a&&this._processEntities)a=this.entityDecoder.decodeEntities(a);let o=e+a;if(this._trimValues&&o.length>0){let c=o.charCodeAt(0),h=o.charCodeAt(o.length-1);if(c<=32||h<=32)o=o.trim()}if(this.options.tagValueProcessor){let c=this.options.tagValueProcessor(s,o,r,!1,!0);if(c!==void 0)o=c}if(o){let c=this._parseTagValue?this.parseValue(o):o;if(c!==void 0&&c!=="")this.addToObj(i,s,c,r,!0,!1)}}else{let a=this.processTagValue(t,s,r,!1,!0);if(a!==void 0&&a!=="")this.addToObj(i,s,a,r,!0,!1)}}parseChildren(t,e,r,i,s,a){let o="",c="",h=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let u=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!o)o=t.substring(u,e);else o+=t.substring(u,e);continue}if(e+1>=r)break;let m=t.charCodeAt(e+1);if(m===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(o||c)this.flushText(o,c,s,i),o="",c="";e+=4;let u=t.indexOf("-->",e);if(u===-1){e=r;break}if(this._commentPropName){let g=t.substring(e,u);this.addToObj(i,this._commentPropName,g,s,!0,!1)}e=u+3;continue}if(m===33&&e+8<r&&D(t,e+2)){e+=9;let u=t.indexOf("]]>",e);if(u===-1){e=r;break}let g=t.substring(e,u);if(this._cdataPropName)this.flushText(o,c,s,i),o="",c="",this.addToObj(i,this._cdataPropName,g,s,!0,!1);else{if(o){let y=o;if(this._processEntities)y=this.entityDecoder.decodeEntities(y);c+=y,o=""}c+=g}e=u+3;continue}if(m===33&&e+9<r&&k(t,e+2)){e+=9;let u=1;while(e<r&&u>0){let g=t.charCodeAt(e);if(g===60)u++;else if(g===62)u--;e++}continue}if(m===63){e+=2;let u=e;while(e<r&&!_(t.charCodeAt(e))&&t.charCodeAt(e)!==63)e++;let g=t.substring(u,e),y=t.indexOf("?>",e);if(y===-1){e=r;break}let N=t.substring(e,y).trim();if(g==="xml"){if(!this._ignoreDeclaration&&this._piPropName){let w=this.parsePiAttributes(N);this.addToObj(i,this._piPropName,{[g]:w},s,!0,!1)}}else if(!this._ignorePiTags&&this._piPropName)this.addToObj(i,this._piPropName,{[g]:N},s,!0,!1);e=y+2;continue}if(m===47){if(o||c)this.flushText(o,c,s,i),o="",c="";e+=2;let u=e,g=this.readTagName(t,e,r),y=this.extractTagName(t,u,g);e=g;while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;if(a.length>0&&a[a.length-1]===y){a.pop();continue}return e}if(o||c)this.flushText(o,c,s,i),o="",c="";e++;let f=e,b=this.readTagName(t,e,r),p=this.extractTagName(t,f,b);if(!p){e=b+1;continue}e=b;let C=h?s?`${s}.${p}`:p:"",E={},d=!1;if(!this._ignoreAttributes){let u=this.parseAttributes(t,e,r,C,E);if(u<0)e=-u-1,d=!0;else e=u}else while(e<r){let u=t.charCodeAt(e);if(u===62||u===47)break;if(u===34||u===39){e++;while(e<r&&t.charCodeAt(e)!==u)e++}e++}if(this.options.updateTag){if(this.options.updateTag(p,C,E)===!1){while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47)e+=2;else if(e<r&&t.charCodeAt(e)===62){e++;let g=`</${p}>`,y=t.indexOf(g,e);if(y!==-1)e=y+g.length}continue}}while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47){if(e+=2,d||this._alwaysCreateTextNode){let u={};if(d)this.applyAttributes(u,E,C);if(this._alwaysCreateTextNode)u[this._textNodeName]="";this.addToObj(i,p,u,C,!0,!1)}else this.addToObj(i,p,"",C,!0,!1);continue}if(e<r&&t.charCodeAt(e)===62){if(e++,this.unpairedSet.has(p)){if(d){let N={};this.applyAttributes(N,E,C),this.addToObj(i,p,N,C,!0,!1)}else this.addToObj(i,p,"",C,!0,!1);a.push(p);continue}if(this.exactStopNodes.size>0||this.wildcardStopSuffixes.length>0){if(this.isStopNode(C)){let N=this.readStopNodeContent(t,e,r,p),w={};if(d)this.applyAttributes(w,E,C);if(N.content)w[this._textNodeName]=N.content;this.addToObj(i,p,w,C,!0,!1),e=N.pos;continue}}let u={};if(d)this.applyAttributes(u,E,C);e=this.parseChildren(t,e,r,u,C,a);let g=this._textNodeName,y=u[g];if(!d&&!this._alwaysCreateTextNode){let N=!0;for(let w in u)if(w!==g){N=!1;break}if(N){this.addToObj(i,p,y!==void 0?y:"",C,!0,!1);continue}}this.addToObj(i,p,u,C,!1,!1)}}if(o||c)this.flushText(o,c,s,i);return e}parseChildrenOrdered(t,e,r,i,s){let a="",o=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let d=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!a)a=t.substring(d,e);else a+=t.substring(d,e);continue}if(e+1>=r)break;let h=t.charCodeAt(e+1);if(h===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(a){let u=this.processTagValue(a,this._textNodeName,s,!1,!0);if(u!==void 0&&u!=="")i.push({[this._textNodeName]:u});a=""}e+=4;let d=t.indexOf("-->",e);if(d===-1){e=r;break}if(this._commentPropName)i.push({[this._commentPropName]:[{[this._textNodeName]:t.substring(e,d)}]});e=d+3;continue}if(h===33&&e+8<r&&D(t,e+2)){e+=9;let d=t.indexOf("]]>",e);if(d===-1){e=r;break}let u=t.substring(e,d);if(this._cdataPropName){if(a){let g=this.processTagValue(a,this._textNodeName,s,!1,!0);if(g!==void 0&&g!=="")i.push({[this._textNodeName]:g});a=""}i.push({[this._cdataPropName]:[{[this._textNodeName]:u}]})}else a+=u;e=d+3;continue}if(h===33&&e+9<r&&k(t,e+2)){e+=9;let d=1;while(e<r&&d>0){let u=t.charCodeAt(e);if(u===60)d++;else if(u===62)d--;e++}continue}if(h===63){e+=2;let d=t.indexOf("?>",e);if(d===-1){e=r;break}e=d+2;continue}if(h===47){if(a){let u=this.processTagValue(a,this._textNodeName,s,!1,!0);if(u!==void 0&&u!=="")i.push({[this._textNodeName]:u});a=""}e+=2,e=this.readTagName(t,e,r);while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;return e}if(a){let d=this.processTagValue(a,this._textNodeName,s,!1,!0);if(d!==void 0&&d!=="")i.push({[this._textNodeName]:d});a=""}e++;let A=e,m=this.readTagName(t,e,r),f=this.extractTagName(t,A,m);if(!f){e=m+1;continue}e=m;let b=o?s?`${s}.${f}`:f:"",p={},C=!1;if(!this._ignoreAttributes){let d=this.parseAttributes(t,e,r,b,p);if(d<0)e=-d-1,C=!0;else e=d}else while(e<r){let d=t.charCodeAt(e);if(d===62||d===47)break;if(d===34||d===39){e++;while(e<r&&t.charCodeAt(e)!==d)e++}e++}while(e<r&&_(t.charCodeAt(e)))e++;let E={[f]:[]};if(C){E[":@"]={};for(let u in p)E[":@"][this._attrPrefix+u]=this.parseAttributeValue(p[u])}if(e<r&&t.charCodeAt(e)===47){e+=2,i.push(E);continue}if(e<r&&t.charCodeAt(e)===62)e++,e=this.parseChildrenOrdered(t,e,r,E[f],b),i.push(E)}if(a){let c=this.processTagValue(a,this._textNodeName,s,!1,!0);if(c!==void 0&&c!=="")i.push({[this._textNodeName]:c})}return e}applyAttributes(t,e,r){let i=this._attrPrefix;if(this._attrsGroupName){let s={};for(let a in e)s[i+a]=this.parseAttributeValue(e[a]);t[this._attrsGroupName]=s}else for(let s in e)t[i+s]=this.parseAttributeValue(e[s])}parsePiAttributes(t){let e={},r=0,i=t.length;while(r<i){while(r<i&&_(t.charCodeAt(r)))r++;if(r>=i)break;let s=r;while(r<i&&!_(t.charCodeAt(r))&&t.charCodeAt(r)!==61)r++;let a=t.substring(s,r);if(!a)break;while(r<i&&_(t.charCodeAt(r)))r++;if(r<i&&t.charCodeAt(r)===61){r++;while(r<i&&_(t.charCodeAt(r)))r++;if(r<i){let o=t.charCodeAt(r);if(o===34||o===39){r++;let c=r;while(r<i&&t.charCodeAt(r)!==o)r++;if(e[a]=t.substring(c,r),r<i)r++}}}}return e}}function mr(t){let e=t.endpoint||`s3.${t.region}.amazonaws.com`,r=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.pathname!=="/"&&r.pathname!==""||r.search||r.hash||r.username||r.password)throw Error("S3 endpoint must be an HTTP(S) origin without a path");let i=r.protocol.slice(0,-1),s=r.host;if(!t.bucket)return{protocol:i,host:s,path:t.path};if(t.forcePathStyle){let a=t.path==="/"?`/${t.bucket}`:`/${t.bucket}${t.path}`;return{protocol:i,host:s,path:a}}return{protocol:i,host:`${t.bucket}.${s}`,path:t.path}}class n{credentials;config;cache;xmlParser;constructor(t,e){this.config={maxRetries:3,retryDelay:1000,cacheEnabled:!0,defaultCacheTTL:60000,...e},this.credentials=t||this.loadCredentials(),this.cache=new Map,this.xmlParser=new v({ignoreAttributes:!1,attributeNamePrefix:"@_",textNodeName:"#text",parseAttributeValue:!0,trimValues:!0})}loadCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=process.env.AWS_SESSION_TOKEN;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:r};let i=this.loadCredentialsFromFile();if(i)return i;return{accessKeyId:"",secretAccessKey:""}}loadCredentialsFromFile(){let t=this.config?.profile||process.env.AWS_PROFILE||"default",e=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(!W(e))return null;try{let r=J(e,"utf-8"),i=this.parseCredentialsFile(r,t);if(i.accessKeyId&&i.secretAccessKey)return i}catch{}return null}parseCredentialsFile(t,e){let r=t.split(`
2
- `),i="",s="",a="",o;for(let c of r){let h=c.trim();if(!h||h.startsWith("#"))continue;let A=h.match(/^\[([^\]]+)\]$/);if(A){i=A[1];continue}if(i===e){let[m,...f]=h.split("="),b=f.join("=").trim();if(m.trim()==="aws_access_key_id")s=b;else if(m.trim()==="aws_secret_access_key")a=b;else if(m.trim()==="aws_session_token")o=b}}return{accessKeyId:s,secretAccessKey:a,sessionToken:o}}ec2CredentialsCache;async getCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:process.env.AWS_SESSION_TOKEN};let r=this.loadCredentialsFromFile();if(r)return r;if(this.ec2CredentialsCache){let i=Date.now();if(this.ec2CredentialsCache.expiration>i+300000)return this.ec2CredentialsCache.credentials}try{let s=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),o=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}})).text(),h=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${o}`,{headers:{"X-aws-ec2-metadata-token":s}})).json(),A={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.Token};return this.ec2CredentialsCache={credentials:A,expiration:new Date(h.Expiration).getTime()},A}catch(i){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request(t){if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey){let i=this.getFromCache(t.cacheKey);if(i!==null)return i}let e=t.retries??this.config.maxRetries??3,r=null;for(let i=0;i<=e;i++)try{let s=await this.makeRequest(t);if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey)this.setInCache(t.cacheKey,s,t.cacheTTL??this.config.defaultCacheTTL??60000);return s}catch(s){if(r=s,!this.shouldRetry(s))throw s;if(i===e)throw s;let o=this.calculateRetryDelay(i);await this.sleep(o)}throw r||Error("Request failed after retries")}async makeRequest(t){let e=t.credentials||(this.credentials?.accessKeyId?this.credentials:await this.getCredentials());if(!e||!e.accessKeyId||!e.secretAccessKey)throw Error("AWS credentials not provided");let r=this.buildUrl(t),i=this.signRequest(t,e),s=await fetch(r,{method:t.method,headers:i,body:t.body}),a=await s.text();if(!s.ok)throw this.parseError(a,s.status,s.headers);if(!a||a.trim()===""){if(t.returnHeaders)return{body:null,headers:this.headersToObject(s.headers)};return null}if(t.rawResponse){if(t.returnHeaders)return{body:a,headers:this.headersToObject(s.headers)};return a}let o;if(a.startsWith("<"))o=this.parseXmlResponse(a);else try{o=JSON.parse(a)}catch{o=a}if(t.returnHeaders)return{body:o,headers:this.headersToObject(s.headers)};return o}headersToObject(t){let e={};return t.forEach((r,i)=>{e[i]=r}),e}buildUrl(t){let{service:e,region:r,queryParams:i}=t,{path:s}=t,a,o="https";if(e==="s3"){let h=mr({region:r,path:s,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});o=h.protocol,a=h.host,s=h.path}else if(e==="cloudfront")a="cloudfront.amazonaws.com";else if(e==="iam")a="iam.amazonaws.com";else if(e==="route53")a="route53.amazonaws.com";else if(e==="route53domains")a="route53domains.us-east-1.amazonaws.com";else if(e==="ecr")a=`api.ecr.${r}.amazonaws.com`;else if(e==="ses")a=`email.${r}.amazonaws.com`;else a=`${e}.${r}.amazonaws.com`;let c=`${o}://${a}${s}`;if(i&&Object.keys(i).length>0){let h=Object.keys(i).map((A)=>`${this.uriEncode(A)}=${this.uriEncode(i[A])}`).join("&");c+=`?${h}`}return c}signRequest(t,e){let{service:r,region:i,method:s,queryParams:a,body:o}=t,{path:c}=t,h=new Date,A=this.getAmzDate(h),m=this.getDateStamp(h),f;if(r==="s3"){let S=mr({region:i,path:c,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});f=S.host,c=S.path}else if(r==="cloudfront")f="cloudfront.amazonaws.com";else if(r==="iam")f="iam.amazonaws.com";else if(r==="route53")f="route53.amazonaws.com";else if(r==="route53domains")f="route53domains.us-east-1.amazonaws.com";else if(r==="ecr")f=`api.ecr.${i}.amazonaws.com`;else if(r==="ses")f=`email.${i}.amazonaws.com`;else f=`${r}.${i}.amazonaws.com`;let b={host:f,"x-amz-date":A,...t.headers||{}};if(e.sessionToken)b["x-amz-security-token"]=e.sessionToken;if(o){if(!Object.keys(b).some((O)=>O.toLowerCase()==="content-type"))b["content-type"]="application/x-www-form-urlencoded";b["content-length"]=Buffer.byteLength(o).toString()}let p=this.sha256(o||"");b["x-amz-content-sha256"]=p;let C=c,E=a?Object.keys(a).sort().map((S)=>`${this.uriEncode(S)}=${this.uriEncode(a[S])}`).join("&"):"",d=Object.keys(b).sort((S,O)=>S.toLowerCase().localeCompare(O.toLowerCase())),u=d.map((S)=>`${S.toLowerCase()}:${b[S].trim()}
1
+ import*as T from"node:crypto";import{existsSync as W,readFileSync as J}from"node:fs";import{homedir as B}from"node:os";import{join as K}from"node:path";var z={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},H={nbsp:" ",copy:"©",reg:"®",trade:"™",euro:"€",pound:"£",yen:"¥",cent:"¢",deg:"°",micro:"µ",middot:"·",bull:"•",hellip:"…",prime:"′",Prime:"″",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",ndash:"–",mdash:"—",iexcl:"¡",iquest:"¿",sect:"§",para:"¶",dagger:"†",Dagger:"‡",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",times:"×",divide:"÷",plusmn:"±",ne:"≠",le:"≤",ge:"≥",infin:"∞",fnof:"ƒ",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",equiv:"≡",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜"};class R{customEntities={};useHtmlEntities;constructor(t=!1){this.useHtmlEntities=t}addEntity(t,e){this.customEntities[t]=e}decodeEntities(t){let e=t.indexOf("&");if(e===-1)return t;let r=t.length,i="",s=0;while(e!==-1&&e<r){if(e>s)i+=t.substring(s,e);let a=t.indexOf(";",e+1);if(a===-1||a-e>32){i+="&",s=e+1,e=t.indexOf("&",s);continue}let o=t.substring(e+1,a);if(o.charCodeAt(0)===35){let c=o.length,h=0,A=!1;if(c>2&&(o.charCodeAt(1)===120||o.charCodeAt(1)===88)){A=!0;for(let m=2;m<c;m++){let f=o.charCodeAt(m);if(f>=48&&f<=57)h=h<<4|f-48;else if(f>=65&&f<=70)h=h<<4|f-55;else if(f>=97&&f<=102)h=h<<4|f-87;else{A=!1;break}}}else if(c>1){A=!0;for(let m=1;m<c;m++){let f=o.charCodeAt(m);if(f>=48&&f<=57)h=h*10+(f-48);else{A=!1;break}}}if(A)i+=String.fromCodePoint(h);else i+=t.substring(e,a+1)}else{let c=this.customEntities[o];if(c===void 0){let h=o.length;if(h>=2&&h<=4){let A=o.charCodeAt(0);if(A===108&&h===2&&o.charCodeAt(1)===116)c="<";else if(A===103&&h===2&&o.charCodeAt(1)===116)c=">";else if(A===97&&h===3&&o.charCodeAt(1)===109&&o.charCodeAt(2)===112)c="&";else if(A===113&&h===4)c=o==="quot"?'"':void 0;else if(A===97&&h===4)c=o==="apos"?"'":void 0}if(c===void 0)c=z[o]??(this.useHtmlEntities?H[o]:void 0)}if(c!==void 0)i+=c;else i+=t.substring(e,a+1)}s=a+1,e=t.indexOf("&",s)}if(s<r)i+=t.substring(s);return i}}var P=[];P[38]="&amp;";P[60]="&lt;";P[62]="&gt;";P[34]="&quot;";P[39]="&apos;";var L={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,alwaysCreateTextNode:!1,trimValues:!0,parseTagValue:!0,parseAttributeValue:!1,processEntities:!0,htmlEntities:!1,commentPropName:!1,cdataPropName:!1,piPropName:!1,preserveOrder:!1,stopNodes:[],unpairedTags:[],isArray:void 0,tagValueProcessor:void 0,attributeValueProcessor:void 0,updateTag:void 0,numberParseOptions:{hex:!0,leadingZeros:!0,scientific:!0},ignorePiTags:!1,transformAttributeName:void 0,transformTagName:void 0,ignoreDeclaration:!1};function _(t){return t===32||t===9||t===10||t===13}function x(t){return t>=65&&t<=90||t>=97&&t<=122||t===95||t===58||t>=192&&t<=214||t>=216&&t<=246||t>=248&&t<=767||t>=880&&t<=893||t>=895&&t<=8191||t>=8204&&t<=8205||t>=8304&&t<=8591||t>=11264&&t<=12271||t>=12289&&t<=55295||t>=63744&&t<=64975||t>=65008&&t<=65533}function V(t){return x(t)||t===45||t===46||t>=48&&t<=57||t===183||t>=768&&t<=879||t>=8255&&t<=8256}var X=/^0x[\da-fA-F]+$/,M=/^[+-]?\d+(\.\d+)?[eE][+-]?\d+$/,G=/^[+-]?(\d+\.?\d*|\.\d+)$/;function D(t,e){return t.charCodeAt(e)===91&&t.charCodeAt(e+1)===67&&t.charCodeAt(e+2)===68&&t.charCodeAt(e+3)===65&&t.charCodeAt(e+4)===84&&t.charCodeAt(e+5)===65&&t.charCodeAt(e+6)===91}function k(t,e){let r=t.charCodeAt(e),i=t.charCodeAt(e+1),s=t.charCodeAt(e+2),a=t.charCodeAt(e+3),o=t.charCodeAt(e+4),c=t.charCodeAt(e+5),h=t.charCodeAt(e+6);return(r===68||r===100)&&(i===79||i===111)&&(s===67||s===99)&&(a===84||a===116)&&(o===89||o===121)&&(c===80||c===112)&&(h===69||h===101)}function Y(t,e,r){if(e>=r||!x(t.charCodeAt(e)))return e;e++;while(e<r&&V(t.charCodeAt(e)))e++;return e}class v{options;entityDecoder;unpairedSet;exactStopNodes;wildcardStopSuffixes;needsJPath;_ignoreAttributes=!0;_textNodeName="#text";_commentPropName=!1;_cdataPropName=!1;_piPropName=!1;_alwaysCreateTextNode=!1;_trimValues=!0;_processEntities=!0;_parseTagValue=!0;_parseAttributeValue=!1;_removeNSPrefix=!1;_attrPrefix="@_";_attrsGroupName=!1;_ignorePiTags=!1;_ignoreDeclaration=!1;constructor(t){this.options={...L,...t},this.entityDecoder=new R(this.options.htmlEntities),this.unpairedSet=new Set(this.options.unpairedTags),this.exactStopNodes=new Set,this.wildcardStopSuffixes=[];for(let e of this.options.stopNodes)if(e.startsWith("*."))this.wildcardStopSuffixes.push(e.substring(2));else this.exactStopNodes.add(e);this._ignoreAttributes=this.options.ignoreAttributes,this._textNodeName=this.options.textNodeName,this._commentPropName=this.options.commentPropName,this._cdataPropName=this.options.cdataPropName,this._piPropName=this.options.piPropName,this._alwaysCreateTextNode=this.options.alwaysCreateTextNode,this._trimValues=this.options.trimValues,this._processEntities=this.options.processEntities,this._parseTagValue=this.options.parseTagValue,this._parseAttributeValue=this.options.parseAttributeValue,this._removeNSPrefix=this.options.removeNSPrefix,this._attrPrefix=this.options.attributeNamePrefix,this._attrsGroupName=this.options.attributesGroupName,this._ignorePiTags=this.options.ignorePiTags,this._ignoreDeclaration=this.options.ignoreDeclaration,this.needsJPath=this.options.stopNodes.length>0||this.options.isArray!==void 0||this.options.updateTag!==void 0||this.options.tagValueProcessor!==void 0||this.options.attributeValueProcessor!==void 0}addEntity(t,e){this.entityDecoder.addEntity(t,e)}parse(t){if(t instanceof Uint8Array)t=new TextDecoder().decode(t);let e=t;if(this.options.preserveOrder)return this.parseOrdered(e);return this.parseUnordered(e)}parseUnordered(t){let e={},r=t.length,i=0;if(r>0&&t.charCodeAt(0)===65279)i=1;return i=this.parseChildren(t,i,r,e,"",[]),e}parseOrdered(t){let e=t.length,r=0;if(e>0&&t.charCodeAt(0)===65279)r=1;let i=[];return this.parseChildrenOrdered(t,r,e,i,""),i}readTagName(t,e,r){return Y(t,e,r)}extractTagName(t,e,r){let i=t.substring(e,r);if(this._removeNSPrefix){let s=i.indexOf(":");if(s!==-1)i=i.substring(s+1)}if(this.options.transformTagName)i=this.options.transformTagName(i);return i}parseAttributes(t,e,r,i,s){let a=0,o=this._removeNSPrefix,c=this.options.transformAttributeName,h=this._trimValues,A=this._processEntities,m=this.options.attributeValueProcessor;while(e<r){let f=t.charCodeAt(e);while(f===32||f===9||f===10||f===13){if(e++,e>=r)break;f=t.charCodeAt(e)}if(e>=r)break;if(f===62||f===47)break;let b=e;if(!x(f))break;e++;while(e<r&&V(t.charCodeAt(e)))e++;let p=t.substring(b,e);if(o){let C=p.indexOf(":");if(C!==-1)p=p.substring(C+1)}if(c)p=c(p);while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===61){e++;while(e<r&&_(t.charCodeAt(e)))e++;if(e>=r)break;let C=t.charCodeAt(e);if(C===34||C===39){e++;let E=e;while(e<r&&t.charCodeAt(e)!==C)e++;let d=t.substring(E,e);if(h&&d.length>0){let u=d.charCodeAt(0),g=d.charCodeAt(d.length-1);if(u<=32||g<=32)d=d.trim()}if(A)d=this.entityDecoder.decodeEntities(d);if(m)d=m(p,d,i)??d;if(s[p]=d,a++,e<r)e++}}else s[p]="true",a++}return a>0?-e-1:e}processTagValue(t,e,r,i,s){if(this._trimValues){let a=t.length;if(a>0){let o=t.charCodeAt(0),c=t.charCodeAt(a-1);if(o<=32||c<=32)t=t.trim()}}if(this._processEntities)t=this.entityDecoder.decodeEntities(t);if(this.options.tagValueProcessor){let a=this.options.tagValueProcessor(e,t,r,i,s);if(a!==void 0)t=a}if(!t)return t;if(this._parseTagValue)return this.parseValue(t);return t}parseValue(t){if(t==="true")return!0;if(t==="false")return!1;if(!t)return t;let e=t.charCodeAt(0);if(!(e>=48&&e<=57||e===43||e===45||e===46))return t;let i=this.options.numberParseOptions;if(i.skipLike?.test(t))return t;if(i.hex&&e===48&&X.test(t))return Number.parseInt(t,16);if(t.length>1&&e===48&&t.charCodeAt(1)!==46){if(i.leadingZeros)return t}if(i.scientific&&M.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}if(G.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}return t}parseAttributeValue(t){if(!this._parseAttributeValue)return t;return this.parseValue(t)}isStopNode(t){if(this.exactStopNodes.has(t))return!0;for(let e of this.wildcardStopSuffixes)if(t.endsWith(`.${e}`)||t===e)return!0;return!1}readStopNodeContent(t,e,r,i){let s=`</${i}`,a=t.indexOf(s,e);if(a===-1)return{content:t.substring(e),pos:r};let o=t.substring(e,a),c=a+s.length;while(c<r&&t.charCodeAt(c)!==62)c++;if(c<r)c++;return{content:o,pos:c}}addToObj(t,e,r,i,s,a){let o=t[e];if(o!==void 0)if(!Array.isArray(o))t[e]=[o,r];else o.push(r);else if(this.options.isArray?.(e,i,s,a))t[e]=[r];else t[e]=r}flushText(t,e,r,i){if(!t&&!e)return;let s=this._textNodeName;if(e){let a=t;if(a&&this._processEntities)a=this.entityDecoder.decodeEntities(a);let o=e+a;if(this._trimValues&&o.length>0){let c=o.charCodeAt(0),h=o.charCodeAt(o.length-1);if(c<=32||h<=32)o=o.trim()}if(this.options.tagValueProcessor){let c=this.options.tagValueProcessor(s,o,r,!1,!0);if(c!==void 0)o=c}if(o){let c=this._parseTagValue?this.parseValue(o):o;if(c!==void 0&&c!=="")this.addToObj(i,s,c,r,!0,!1)}}else{let a=this.processTagValue(t,s,r,!1,!0);if(a!==void 0&&a!=="")this.addToObj(i,s,a,r,!0,!1)}}parseChildren(t,e,r,i,s,a){let o="",c="",h=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let u=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!o)o=t.substring(u,e);else o+=t.substring(u,e);continue}if(e+1>=r)break;let m=t.charCodeAt(e+1);if(m===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(o||c)this.flushText(o,c,s,i),o="",c="";e+=4;let u=t.indexOf("-->",e);if(u===-1){e=r;break}if(this._commentPropName){let g=t.substring(e,u);this.addToObj(i,this._commentPropName,g,s,!0,!1)}e=u+3;continue}if(m===33&&e+8<r&&D(t,e+2)){e+=9;let u=t.indexOf("]]>",e);if(u===-1){e=r;break}let g=t.substring(e,u);if(this._cdataPropName)this.flushText(o,c,s,i),o="",c="",this.addToObj(i,this._cdataPropName,g,s,!0,!1);else{if(o){let y=o;if(this._processEntities)y=this.entityDecoder.decodeEntities(y);c+=y,o=""}c+=g}e=u+3;continue}if(m===33&&e+9<r&&k(t,e+2)){e+=9;let u=1;while(e<r&&u>0){let g=t.charCodeAt(e);if(g===60)u++;else if(g===62)u--;e++}continue}if(m===63){e+=2;let u=e;while(e<r&&!_(t.charCodeAt(e))&&t.charCodeAt(e)!==63)e++;let g=t.substring(u,e),y=t.indexOf("?>",e);if(y===-1){e=r;break}let N=t.substring(e,y).trim();if(g==="xml"){if(!this._ignoreDeclaration&&this._piPropName){let w=this.parsePiAttributes(N);this.addToObj(i,this._piPropName,{[g]:w},s,!0,!1)}}else if(!this._ignorePiTags&&this._piPropName)this.addToObj(i,this._piPropName,{[g]:N},s,!0,!1);e=y+2;continue}if(m===47){if(o||c)this.flushText(o,c,s,i),o="",c="";e+=2;let u=e,g=this.readTagName(t,e,r),y=this.extractTagName(t,u,g);e=g;while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;if(a.length>0&&a[a.length-1]===y){a.pop();continue}return e}if(o||c)this.flushText(o,c,s,i),o="",c="";e++;let f=e,b=this.readTagName(t,e,r),p=this.extractTagName(t,f,b);if(!p){e=b+1;continue}e=b;let C=h?s?`${s}.${p}`:p:"",E={},d=!1;if(!this._ignoreAttributes){let u=this.parseAttributes(t,e,r,C,E);if(u<0)e=-u-1,d=!0;else e=u}else while(e<r){let u=t.charCodeAt(e);if(u===62||u===47)break;if(u===34||u===39){e++;while(e<r&&t.charCodeAt(e)!==u)e++}e++}if(this.options.updateTag){if(this.options.updateTag(p,C,E)===!1){while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47)e+=2;else if(e<r&&t.charCodeAt(e)===62){e++;let g=`</${p}>`,y=t.indexOf(g,e);if(y!==-1)e=y+g.length}continue}}while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47){if(e+=2,d||this._alwaysCreateTextNode){let u={};if(d)this.applyAttributes(u,E,C);if(this._alwaysCreateTextNode)u[this._textNodeName]="";this.addToObj(i,p,u,C,!0,!1)}else this.addToObj(i,p,"",C,!0,!1);continue}if(e<r&&t.charCodeAt(e)===62){if(e++,this.unpairedSet.has(p)){if(d){let N={};this.applyAttributes(N,E,C),this.addToObj(i,p,N,C,!0,!1)}else this.addToObj(i,p,"",C,!0,!1);a.push(p);continue}if(this.exactStopNodes.size>0||this.wildcardStopSuffixes.length>0){if(this.isStopNode(C)){let N=this.readStopNodeContent(t,e,r,p),w={};if(d)this.applyAttributes(w,E,C);if(N.content)w[this._textNodeName]=N.content;this.addToObj(i,p,w,C,!0,!1),e=N.pos;continue}}let u={};if(d)this.applyAttributes(u,E,C);e=this.parseChildren(t,e,r,u,C,a);let g=this._textNodeName,y=u[g];if(!d&&!this._alwaysCreateTextNode){let N=!0;for(let w in u)if(w!==g){N=!1;break}if(N){this.addToObj(i,p,y!==void 0?y:"",C,!0,!1);continue}}this.addToObj(i,p,u,C,!1,!1)}}if(o||c)this.flushText(o,c,s,i);return e}parseChildrenOrdered(t,e,r,i,s){let a="",o=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let d=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!a)a=t.substring(d,e);else a+=t.substring(d,e);continue}if(e+1>=r)break;let h=t.charCodeAt(e+1);if(h===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(a){let u=this.processTagValue(a,this._textNodeName,s,!1,!0);if(u!==void 0&&u!=="")i.push({[this._textNodeName]:u});a=""}e+=4;let d=t.indexOf("-->",e);if(d===-1){e=r;break}if(this._commentPropName)i.push({[this._commentPropName]:[{[this._textNodeName]:t.substring(e,d)}]});e=d+3;continue}if(h===33&&e+8<r&&D(t,e+2)){e+=9;let d=t.indexOf("]]>",e);if(d===-1){e=r;break}let u=t.substring(e,d);if(this._cdataPropName){if(a){let g=this.processTagValue(a,this._textNodeName,s,!1,!0);if(g!==void 0&&g!=="")i.push({[this._textNodeName]:g});a=""}i.push({[this._cdataPropName]:[{[this._textNodeName]:u}]})}else a+=u;e=d+3;continue}if(h===33&&e+9<r&&k(t,e+2)){e+=9;let d=1;while(e<r&&d>0){let u=t.charCodeAt(e);if(u===60)d++;else if(u===62)d--;e++}continue}if(h===63){e+=2;let d=t.indexOf("?>",e);if(d===-1){e=r;break}e=d+2;continue}if(h===47){if(a){let u=this.processTagValue(a,this._textNodeName,s,!1,!0);if(u!==void 0&&u!=="")i.push({[this._textNodeName]:u});a=""}e+=2,e=this.readTagName(t,e,r);while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;return e}if(a){let d=this.processTagValue(a,this._textNodeName,s,!1,!0);if(d!==void 0&&d!=="")i.push({[this._textNodeName]:d});a=""}e++;let A=e,m=this.readTagName(t,e,r),f=this.extractTagName(t,A,m);if(!f){e=m+1;continue}e=m;let b=o?s?`${s}.${f}`:f:"",p={},C=!1;if(!this._ignoreAttributes){let d=this.parseAttributes(t,e,r,b,p);if(d<0)e=-d-1,C=!0;else e=d}else while(e<r){let d=t.charCodeAt(e);if(d===62||d===47)break;if(d===34||d===39){e++;while(e<r&&t.charCodeAt(e)!==d)e++}e++}while(e<r&&_(t.charCodeAt(e)))e++;let E={[f]:[]};if(C){E[":@"]={};for(let u in p)E[":@"][this._attrPrefix+u]=this.parseAttributeValue(p[u])}if(e<r&&t.charCodeAt(e)===47){e+=2,i.push(E);continue}if(e<r&&t.charCodeAt(e)===62)e++,e=this.parseChildrenOrdered(t,e,r,E[f],b),i.push(E)}if(a){let c=this.processTagValue(a,this._textNodeName,s,!1,!0);if(c!==void 0&&c!=="")i.push({[this._textNodeName]:c})}return e}applyAttributes(t,e,r){let i=this._attrPrefix;if(this._attrsGroupName){let s={};for(let a in e)s[i+a]=this.parseAttributeValue(e[a]);t[this._attrsGroupName]=s}else for(let s in e)t[i+s]=this.parseAttributeValue(e[s])}parsePiAttributes(t){let e={},r=0,i=t.length;while(r<i){while(r<i&&_(t.charCodeAt(r)))r++;if(r>=i)break;let s=r;while(r<i&&!_(t.charCodeAt(r))&&t.charCodeAt(r)!==61)r++;let a=t.substring(s,r);if(!a)break;while(r<i&&_(t.charCodeAt(r)))r++;if(r<i&&t.charCodeAt(r)===61){r++;while(r<i&&_(t.charCodeAt(r)))r++;if(r<i){let o=t.charCodeAt(r);if(o===34||o===39){r++;let c=r;while(r<i&&t.charCodeAt(r)!==o)r++;if(e[a]=t.substring(c,r),r<i)r++}}}}return e}}function yr(t){let e=t.endpoint||`s3.${t.region}.amazonaws.com`,r=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.pathname!=="/"&&r.pathname!==""||r.search||r.hash||r.username||r.password)throw Error("S3 endpoint must be an HTTP(S) origin without a path");let i=r.protocol.slice(0,-1),s=r.host;if(!t.bucket)return{protocol:i,host:s,path:t.path};if(t.forcePathStyle){let a=t.path==="/"?`/${t.bucket}`:`/${t.bucket}${t.path}`;return{protocol:i,host:s,path:a}}return{protocol:i,host:`${t.bucket}.${s}`,path:t.path}}class n{credentials;config;cache;xmlParser;constructor(t,e){this.config={maxRetries:3,retryDelay:1000,cacheEnabled:!0,defaultCacheTTL:60000,...e},this.credentials=t||this.loadCredentials(),this.cache=new Map,this.xmlParser=new v({ignoreAttributes:!1,attributeNamePrefix:"@_",textNodeName:"#text",parseAttributeValue:!0,trimValues:!0})}loadCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=process.env.AWS_SESSION_TOKEN;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:r};let i=this.loadCredentialsFromFile();if(i)return i;return{accessKeyId:"",secretAccessKey:""}}loadCredentialsFromFile(){let t=this.config?.profile||process.env.AWS_PROFILE||"default",e=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(!W(e))return null;try{let r=J(e,"utf-8"),i=this.parseCredentialsFile(r,t);if(i.accessKeyId&&i.secretAccessKey)return i}catch{}return null}parseCredentialsFile(t,e){let r=t.split(`
2
+ `),i="",s="",a="",o;for(let c of r){let h=c.trim();if(!h||h.startsWith("#"))continue;let A=h.match(/^\[([^\]]+)\]$/);if(A){i=A[1];continue}if(i===e){let[m,...f]=h.split("="),b=f.join("=").trim();if(m.trim()==="aws_access_key_id")s=b;else if(m.trim()==="aws_secret_access_key")a=b;else if(m.trim()==="aws_session_token")o=b}}return{accessKeyId:s,secretAccessKey:a,sessionToken:o}}ec2CredentialsCache;async getCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:process.env.AWS_SESSION_TOKEN};let r=this.loadCredentialsFromFile();if(r)return r;if(this.ec2CredentialsCache){let i=Date.now();if(this.ec2CredentialsCache.expiration>i+300000)return this.ec2CredentialsCache.credentials}try{let s=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),o=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}})).text(),h=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${o}`,{headers:{"X-aws-ec2-metadata-token":s}})).json(),A={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.Token};return this.ec2CredentialsCache={credentials:A,expiration:new Date(h.Expiration).getTime()},A}catch(i){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request(t){if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey){let i=this.getFromCache(t.cacheKey);if(i!==null)return i}let e=t.retries??this.config.maxRetries??3,r=null;for(let i=0;i<=e;i++)try{let s=await this.makeRequest(t);if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey)this.setInCache(t.cacheKey,s,t.cacheTTL??this.config.defaultCacheTTL??60000);return s}catch(s){if(r=s,!this.shouldRetry(s))throw s;if(i===e)throw s;let o=this.calculateRetryDelay(i);await this.sleep(o)}throw r||Error("Request failed after retries")}async makeRequest(t){let e=t.credentials||(this.credentials?.accessKeyId?this.credentials:await this.getCredentials());if(!e||!e.accessKeyId||!e.secretAccessKey)throw Error("AWS credentials not provided");let r=this.buildUrl(t),i=this.signRequest(t,e),s=await fetch(r,{method:t.method,headers:i,body:t.body}),a=await s.text();if(!s.ok)throw this.parseError(a,s.status,s.headers);if(!a||a.trim()===""){if(t.returnHeaders)return{body:null,headers:this.headersToObject(s.headers)};return null}if(t.rawResponse){if(t.returnHeaders)return{body:a,headers:this.headersToObject(s.headers)};return a}let o;if(a.startsWith("<"))o=this.parseXmlResponse(a);else try{o=JSON.parse(a)}catch{o=a}if(t.returnHeaders)return{body:o,headers:this.headersToObject(s.headers)};return o}headersToObject(t){let e={};return t.forEach((r,i)=>{e[i]=r}),e}buildUrl(t){let{service:e,region:r,queryParams:i}=t,{path:s}=t,a,o="https";if(e==="s3"){let h=yr({region:r,path:s,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});o=h.protocol,a=h.host,s=h.path}else if(e==="cloudfront")a="cloudfront.amazonaws.com";else if(e==="iam")a="iam.amazonaws.com";else if(e==="route53")a="route53.amazonaws.com";else if(e==="route53domains")a="route53domains.us-east-1.amazonaws.com";else if(e==="ecr")a=`api.ecr.${r}.amazonaws.com`;else if(e==="ses")a=`email.${r}.amazonaws.com`;else a=`${e}.${r}.amazonaws.com`;let c=`${o}://${a}${s}`;if(i&&Object.keys(i).length>0){let h=Object.keys(i).map((A)=>`${this.uriEncode(A)}=${this.uriEncode(i[A])}`).join("&");c+=`?${h}`}return c}signRequest(t,e){let{service:r,region:i,method:s,queryParams:a,body:o}=t,{path:c}=t,h=new Date,A=this.getAmzDate(h),m=this.getDateStamp(h),f;if(r==="s3"){let S=yr({region:i,path:c,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});f=S.host,c=S.path}else if(r==="cloudfront")f="cloudfront.amazonaws.com";else if(r==="iam")f="iam.amazonaws.com";else if(r==="route53")f="route53.amazonaws.com";else if(r==="route53domains")f="route53domains.us-east-1.amazonaws.com";else if(r==="ecr")f=`api.ecr.${i}.amazonaws.com`;else if(r==="ses")f=`email.${i}.amazonaws.com`;else f=`${r}.${i}.amazonaws.com`;let b={host:f,"x-amz-date":A,...t.headers||{}};if(e.sessionToken)b["x-amz-security-token"]=e.sessionToken;if(o){if(!Object.keys(b).some((O)=>O.toLowerCase()==="content-type"))b["content-type"]="application/x-www-form-urlencoded";b["content-length"]=Buffer.byteLength(o).toString()}let p=this.sha256(o||"");b["x-amz-content-sha256"]=p;let C=c,E=a?Object.keys(a).sort().map((S)=>`${this.uriEncode(S)}=${this.uriEncode(a[S])}`).join("&"):"",d=Object.keys(b).sort((S,O)=>S.toLowerCase().localeCompare(O.toLowerCase())),u=d.map((S)=>`${S.toLowerCase()}:${b[S].trim()}
3
3
  `).join(""),g=d.map((S)=>S.toLowerCase()).join(";"),y=[s,C,E,u,g,p].join(`
4
4
  `),N="AWS4-HMAC-SHA256",w=r;if(r==="email")w="ses";let I=`${m}/${i}/${w}/aws4_request`,F=[N,A,I,this.sha256(y)].join(`
5
- `),q=this.getSignatureKey(e.secretAccessKey,m,i,w),U=this.hmac(q,F),j=`${N} Credential=${e.accessKeyId}/${I}, SignedHeaders=${g}, Signature=${U}`;return{...b,Authorization:j}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return T.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return T.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=T.createHmac("sha256",`AWS4${t}`).update(e).digest(),a=T.createHmac("sha256",s).update(r).digest(),o=T.createHmac("sha256",a).update(i).digest();return T.createHmac("sha256",o).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let a=s.ErrorResponse.Error;return i.code=a.Code,i.message=`AWS Error [${a.Code}]: ${a.Message||"Unknown error"}`,i.type=a.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function l(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,a)=>{e[`${r}.${a+1}`]=String(s)});else if(typeof i==="object")for(let[s,a]of Object.entries(i))e[`${r}.${s}`]=String(a);else e[r]=String(i)}return e}function th(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",a=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(W(a))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
- export{mr,n,l,th};
5
+ `),q=this.getSignatureKey(e.secretAccessKey,m,i,w),U=this.hmac(q,F),j=`${N} Credential=${e.accessKeyId}/${I}, SignedHeaders=${g}, Signature=${U}`;return{...b,Authorization:j}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return T.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return T.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=T.createHmac("sha256",`AWS4${t}`).update(e).digest(),a=T.createHmac("sha256",s).update(r).digest(),o=T.createHmac("sha256",a).update(i).digest();return T.createHmac("sha256",o).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let a=s.ErrorResponse.Error;return i.code=a.Code,i.message=`AWS Error [${a.Code}]: ${a.Message||"Unknown error"}`,i.type=a.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function l(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,a)=>{e[`${r}.${a+1}`]=String(s)});else if(typeof i==="object")for(let[s,a]of Object.entries(i))e[`${r}.${s}`]=String(a);else e[r]=String(i)}return e}function ah(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",a=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(W(a))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
+ export{yr,n,l,ah};
@@ -0,0 +1 @@
1
+ import{j}from"./chunk-mcfdtg5w.js";import"./chunk-2s65yj3g.js";export{j as RDSClient};
@@ -0,0 +1 @@
1
+ import{Ea}from"./chunk-w5fmaaxa.js";import"./chunk-z7v4evbh.js";import"./chunk-2s65yj3g.js";import"./chunk-y13zcbnp.js";export{Ea as buildAndPushServerlessImage};
@@ -1 +1 @@
1
- import{Dr}from"./chunk-qzwack6w.js";var Sd="\x00";function no(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function f(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function yi(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!no(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function Ii(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class io{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>yi(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=Ii(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!yi(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=Ii(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Cd(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function bd(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var Ed="protection.controls",Si=24,so=4,g={ipRules:{allow:[],block:[]}};function m(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function p(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Si,Math.max(0.25,e))}var h=500;class oo{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Ed);if(!t||typeof t!=="object"||Array.isArray(t))return{...g,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(Ed,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:m(i.attackMode,t),mitigationPause:m(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+p(t.hours,so)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+p(t.hours,Si)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!Dr(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>h)throw Error(`At most ${h} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function vd(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function Td(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function ao(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function uA(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:ao(o,i)}}}}export{Sd,no,yi,Ii,io,Cd,bd,Ed,Si,so,oo,vd,Td,ao,uA};
1
+ import{Br}from"./chunk-r4dpn715.js";var wd="\x00";function lo(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function f(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function bi(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!lo(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function Ei(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class uo{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>bi(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=Ei(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!bi(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=Ei(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Rd(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function Dd(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var Pd="protection.controls",vi=24,po=4,g={ipRules:{allow:[],block:[]}};function m(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function p(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(vi,Math.max(0.25,e))}var h=500;class go{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Pd);if(!t||typeof t!=="object"||Array.isArray(t))return{...g,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(Pd,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:m(i.attackMode,t),mitigationPause:m(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+p(t.hours,po)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+p(t.hours,vi)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!Br(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>h)throw Error(`At most ${h} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Nd(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function kd(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function mo(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function AA(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:mo(o,i)}}}}export{wd,lo,bi,Ei,uo,Rd,Dd,Pd,vi,po,go,Nd,kd,mo,AA};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-crpjqnjb.js";class h{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{n}from"./chunk-2s65yj3g.js";class h{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
3
3
  <Name>${e.Name}</Name>
4
4
  <CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
@@ -1,5 +1,5 @@
1
- import{mr,n}from"./chunk-crpjqnjb.js";import{Le}from"./chunk-d1tv3wx0.js";import*as l from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as U}from"node:fs/promises";import{join as L}from"node:path";function Nt(e){if(e){let i=R(e);if(!i)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return i}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return R(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function R(e){let{existsSync:t,readFileSync:s}=Le("node:fs"),{homedir:i}=Le("node:os"),{join:r}=Le("node:path"),o=process.env.AWS_SHARED_CREDENTIALS_FILE||r(i(),".aws","credentials");if(!t(o))return null;let c=s(o,"utf-8"),g=null,d,u,y;for(let h of c.split(`
2
- `)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};g=p[1],d=void 0,u=void 0,y=void 0;continue}if(g===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":d=f;break;case"aws_secret_access_key":u=f;break;case"aws_session_token":y=f;break}}}if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};return null}function B(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let r=new ArrayBuffer(i);return new Uint8Array(r).set(new Uint8Array(e)),r}class a{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,r=typeof e==="string"?e:e.region??"us-east-1",o=typeof e==="string"?t:e.profile,c=i?.endpoint?mr({region:r,path:"/",endpoint:i.endpoint}):void 0;this.region=r,this.explicitProfile=o,this.endpoint=c?.host,this.endpointProtocol=c?.protocol??"https",this.forcePathStyle=i?.forcePathStyle,this.explicitCredentials=i?.credentials,this.client=new n(i?.credentials,{profile:o,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=Nt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],i=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(i){let r=Array.isArray(i)?i:[i];for(let o of r)t.push({Name:o.Name,CreationDate:o.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let i;if(this.region!=="us-east-1"&&!this.endpoint)i=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{yr,n}from"./chunk-2s65yj3g.js";import{Me}from"./chunk-p9fqsz06.js";import*as l from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as U}from"node:fs/promises";import{join as L}from"node:path";function kt(e){if(e){let i=R(e);if(!i)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return i}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return R(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function R(e){let{existsSync:t,readFileSync:s}=Me("node:fs"),{homedir:i}=Me("node:os"),{join:r}=Me("node:path"),o=process.env.AWS_SHARED_CREDENTIALS_FILE||r(i(),".aws","credentials");if(!t(o))return null;let c=s(o,"utf-8"),g=null,d,u,y;for(let h of c.split(`
2
+ `)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};g=p[1],d=void 0,u=void 0,y=void 0;continue}if(g===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":d=f;break;case"aws_secret_access_key":u=f;break;case"aws_session_token":y=f;break}}}if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};return null}function B(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let r=new ArrayBuffer(i);return new Uint8Array(r).set(new Uint8Array(e)),r}class a{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,r=typeof e==="string"?e:e.region??"us-east-1",o=typeof e==="string"?t:e.profile,c=i?.endpoint?yr({region:r,path:"/",endpoint:i.endpoint}):void 0;this.region=r,this.explicitProfile=o,this.endpoint=c?.host,this.endpointProtocol=c?.protocol??"https",this.forcePathStyle=i?.forcePathStyle,this.explicitCredentials=i?.credentials,this.client=new n(i?.credentials,{profile:o,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=kt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],i=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(i){let r=Array.isArray(i)?i:[i];for(let o of r)t.push({Name:o.Name,CreationDate:o.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let i;if(this.region!=="us-east-1"&&!this.endpoint)i=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
4
4
  <LocationConstraint>${this.region}</LocationConstraint>
5
5
  </CreateBucketConfiguration>`,s["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,headers:s,body:i})}async deleteBucket(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`})}async emptyAndDeleteBucket(e){let t=!0;while(t){let s=await this.listAllObjects({bucket:e});if(s.length===0){t=!1;break}let i=s.map((r)=>r.Key);for(let r=0;r<i.length;r+=1000){let o=i.slice(r,r+1000);await this.deleteObjects(e,o)}}await this.deleteBucket(e)}async listAllObjects(e){let t=[],s;do{let i={"list-type":"2","max-keys":"1000"};if(e.prefix)i.prefix=e.prefix;if(s)i["continuation-token"]=s;let r=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`,queryParams:i}),o=r?.ListBucketResult??r,c=o?.Contents;if(c){let d=Array.isArray(c)?c:[c];for(let u of d)t.push({Key:u.Key,LastModified:u.LastModified||"",Size:Number.parseInt(u.Size||"0"),ETag:u.ETag})}let g=o?.IsTruncated;s=g==="true"||g===!0?o?.NextContinuationToken:void 0}while(s);return t}async list(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`}),s=[],r=(t?.ListBucketResult??t)?.Contents;if(r){let o=Array.isArray(r)?r:[r];for(let c of o){if(e.prefix&&!c.Key?.startsWith(e.prefix))continue;if(s.push({Key:c.Key||"",LastModified:c.LastModified||"",Size:Number.parseInt(c.Size||"0"),ETag:c.ETag}),e.maxKeys&&s.length>=e.maxKeys)break}}return s}async putObject(e){let t={};if(e.acl)t["x-amz-acl"]=e.acl;if(e.cacheControl)t["Cache-Control"]=e.cacheControl;if(e.contentType)t["Content-Type"]=e.contentType;if(e.metadata)for(let[r,o]of Object.entries(e.metadata))t[`x-amz-meta-${r}`]=o;let s=e.key.split("/").map((r)=>encodeURIComponent(r)).join("/"),i=e.body instanceof Uint8Array&&!Buffer.isBuffer(e.body)?Buffer.from(e.body):e.body;if(Buffer.isBuffer(i)||i instanceof Uint8Array){let r=Buffer.isBuffer(i)?i:Buffer.from(i),{accessKeyId:o,secretAccessKey:c,sessionToken:g}=this.getCredentials(),d=this.s3VirtualHost(e.bucket),u=this.objectPath(e.bucket,s),y=this.objectUrl(e.bucket,s),h=new Date,m=h.toISOString().replace(/[:-]|\.\d{3}/g,""),p=h.toISOString().slice(0,10).replace(/-/g,""),b=l.createHash("sha256").update(r).digest("hex"),S={host:d,"x-amz-date":m,"x-amz-content-sha256":b,...t};if(g)S["x-amz-security-token"]=g;let f=Object.keys(S).sort().map((P)=>`${P.toLowerCase()}:${S[P].trim()}
@@ -89,4 +89,4 @@ host:${c}
89
89
  ${t.map((r)=>`<Object><Key>${r.Key}</Key>${r.VersionId?`<VersionId>${r.VersionId}</VersionId>`:""}</Object>`).join(`
90
90
  `)}
91
91
  </Delete>`,i=l.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":i}})}}
92
- export{Nt,a};
92
+ export{kt,a};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-crpjqnjb.js";class y{client;constructor(e,i){this.client=i??new n(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let r=t[i]??t.Item;if(r===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(r)?r:[r]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([r,o])=>!/^[A-Za-z0-9-]{1,64}$/.test(r)||!o||o.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),o=r.headers?.etag||r.headers?.ETag||r.ETag||"",s=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!s||s.Enabled===void 0||!o)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(s.Origins,"Origin"),c=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),g=a.find((p)=>String(p.Id)===t.id),u=c.find((p)=>String(p.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${g.DomainName}; pass replaceExisting only after reviewing the live config`);if(u&&String(u.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${u.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let d={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([p,T])=>({HeaderName:p,HeaderValue:T}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},h=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],l={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:h.length,Items:{Method:h},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},f=g?a.map((p)=>String(p.Id)===t.id?d:p):[...a,d],m=u?c.map((p)=>String(p.PathPattern)===t.pathPattern?l:p):[...c,l],C=JSON.stringify(a)!==JSON.stringify(f)||JSON.stringify(c)!==JSON.stringify(m);if(!C||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:C,applied:!1,etag:o};s.Origins={Quantity:f.length,Items:{Origin:f}},s.CacheBehaviors={Quantity:m.length,...m.length?{Items:{CacheBehavior:m}}:{}};let I=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":o}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:I.ETag||I.headers?.etag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),o=r.headers?.etag||r.headers?.ETag||r.ETag||"",s=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!s||s.Enabled===void 0||!o)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(s.Origins,"Origin"),c=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),g=a.find((m)=>String(m.Id)===t.id),u=c.find((m)=>String(m.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(u&&String(u.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!u)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:o};let d=c.filter((m)=>String(m.PathPattern)!==t.pathPattern),h=String(s.DefaultCacheBehavior?.TargetOriginId)===t.id||d.some((m)=>String(m.TargetOriginId)===t.id),l=h?a:a.filter((m)=>String(m.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!h&&!!g,etag:o};s.Origins={Quantity:l.length,Items:{Origin:l}},s.CacheBehaviors={Quantity:d.length,...d.length?{Items:{CacheBehavior:d}}:{}};let f=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":o}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!h&&!!g,etag:f.ETag||f.headers?.etag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{n}from"./chunk-2s65yj3g.js";class y{client;constructor(e,i){this.client=i??new n(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let r=t[i]??t.Item;if(r===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(r)?r:[r]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([r,o])=>!/^[A-Za-z0-9-]{1,64}$/.test(r)||!o||o.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),o=r.headers?.etag||r.headers?.ETag||r.ETag||"",s=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!s||s.Enabled===void 0||!o)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(s.Origins,"Origin"),c=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),g=a.find((p)=>String(p.Id)===t.id),u=c.find((p)=>String(p.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${g.DomainName}; pass replaceExisting only after reviewing the live config`);if(u&&String(u.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${u.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let d={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([p,T])=>({HeaderName:p,HeaderValue:T}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},h=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],l={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:h.length,Items:{Method:h},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},f=g?a.map((p)=>String(p.Id)===t.id?d:p):[...a,d],m=u?c.map((p)=>String(p.PathPattern)===t.pathPattern?l:p):[...c,l],C=JSON.stringify(a)!==JSON.stringify(f)||JSON.stringify(c)!==JSON.stringify(m);if(!C||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:C,applied:!1,etag:o};s.Origins={Quantity:f.length,Items:{Origin:f}},s.CacheBehaviors={Quantity:m.length,...m.length?{Items:{CacheBehavior:m}}:{}};let I=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":o}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:I.ETag||I.headers?.etag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),o=r.headers?.etag||r.headers?.ETag||r.ETag||"",s=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!s||s.Enabled===void 0||!o)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(s.Origins,"Origin"),c=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),g=a.find((m)=>String(m.Id)===t.id),u=c.find((m)=>String(m.PathPattern)===t.pathPattern);if(g&&String(g.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(u&&String(u.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!u)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:o};let d=c.filter((m)=>String(m.PathPattern)!==t.pathPattern),h=String(s.DefaultCacheBehavior?.TargetOriginId)===t.id||d.some((m)=>String(m.TargetOriginId)===t.id),l=h?a:a.filter((m)=>String(m.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!h&&!!g,etag:o};s.Origins={Quantity:l.length,Items:{Origin:l}},s.CacheBehaviors={Quantity:d.length,...d.length?{Items:{CacheBehavior:d}}:{}};let f=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":o}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!h&&!!g,etag:f.ETag||f.headers?.etag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <InvalidationBatch>
3
3
  <Paths>
4
4
  <Quantity>${e.paths.length}</Quantity>
@@ -0,0 +1,2 @@
1
+ import{n}from"./chunk-2s65yj3g.js";import{h}from"./chunk-65ajja2a.js";var tt=new Set(["A","AAAA","CNAME"]);function S(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 P(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((i)=>setTimeout(i,o))}class ie{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 s=1;s<=8;s+=1){let o,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=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:i.signal})}catch(d){if(r=d,s===8)throw d;await P(s);continue}finally{clearTimeout(a)}if(!o.ok){if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}`),!S(o.status)||s===8)throw r;await P(s,o);continue}let c=await o.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!S(0,c.message)||s===8)throw r;await P(s,o);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.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(!ie.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let i=[];for(let a of o.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)i.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return i}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((i)=>i.type===t.type&&this.getSubdomain(i.name,r)===s&&i.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)o.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let i=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,o);if(ie.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${i.length>0?` (${i.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.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),s=this.getSubdomain(t.name,r),o=await this.listRecords(e,t.type);if(o.success){let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(i?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${i.id}`,a),{success:!0,id:i.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 s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!i?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${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 r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.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 ke{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 s=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let a=await fetch(s,i);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.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),s=this.getSubdomain(e.name,r),o={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{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),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),i=o.filter((a)=>a.data!==t.content);if(i.length===o.length)return{success:!1,message:"Record not found"};if(i.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,i);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),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((i)=>this.fromGoDaddyRecord(i,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 x="https://api.cloudflare.com/client/v4",ts="[ts-cloud]";class Be{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 s=`${x}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let c=await(await fetch(s,i)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}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 a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.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 i=o.result[0].id;return this.zoneCache.set(r,i),{id:i,name:o.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 s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&tt.has(e.type)){if(s.proxied=o,o)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let i=k(e);if(i)s.data=i,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}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),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).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),s=this.getFullRecordName(t.name,r.name),i=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??i?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(i)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${i.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return{success:!1,message:"Record not found"};let a=i.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.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 s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let o=[],i=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${i}`);if(o.push(...c.result||[]),c.result_info)a=i<c.result_info.total_pages,i++;else a=!1}return{success:!0,records:o.map((c)=>this.fromCloudflareRecord(c))}}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 s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(i){let a=i instanceof Error?i.message:String(i);if(!/already exists|1061/i.test(a))throw i;let c=await this.getZoneDetails(r);if(!c)throw i;return{...c,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`),s=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let i of o.hosts||[])s.add(i.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(i.result&&i.result.length>0)return i.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),o=s.id,i=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${c.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`),s={};for(let o of r.result||[])s[o.id]=o.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),o=[],i=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&N(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),o.push({id:a,from:d,to:c})}catch(u){i.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:o,failed:i}}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 s=await this.getZoneId(e),i=(await this.getPhaseRules(e,t)).filter((d)=>!(d.description||"").startsWith(ts)),a=r.map((d)=>({...d,description:d.description?.startsWith(ts)?d.description:`${ts} ${d.description||t}`})),c=[...i,...a].map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}function N(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((o,i)=>N(o,t[i]))}let r=e,s=t;return Object.keys(s).every((o)=>N(r[o],s[o]))}function k(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:b(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,o,i]=r.slice(0,3).map(Number);if(![s,o,i].every(Number.isFinite))return null;return{priority:s,weight:o,port:i,target:b(r.slice(3).join(" "))}}function b(e){return e.replace(/\.$/,"")}var V=new Set(["A","AAAA","CNAME","ALIAS"]);function Tt(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 R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function D(e){return e.replace(/\.$/,"").toLowerCase()}function hn(e,t){let r=D(t),s=(e??"@").trim();if(!s||s==="@")return r;let o=D(s);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function rs(e,t){return e.map((r)=>({...r,name:hn(r.name,t),proxied:r.proxied??!1}))}function _(e,t){if(e.type!==t.type)return!1;if(D(e.name)!==D(t.name))return!1;if(V.has(t.type))return!0;if(t.type==="TXT"){let r=Tt(t.content);if(r)return Tt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Z(e,t){if(R(e.content)!==R(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 ns(e){let{provider:t,zone:r,records:s}=e,o={outcomes:[],warnings:[]};if(s.length===0)return o;let i=await t.listRecords(r);if(!i.success)return o.warnings.push(`could not list ${r}: ${i.message||"unknown provider error"} — records not reconciled`),o;let a=i.records;for(let c of s){let d=a.filter((l)=>_(l,c));if(d.length>0&&d.every((l)=>Z(l,c))){o.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},p=c.type==="TXT"&&Tt(c.content)!==void 0;if(p)for(let l of d){let A=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!A.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${A.message||"unknown error"}`)}let m=p||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)o.outcomes.push({record:c,action:d.length>0?"updated":"created"});else o.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>D(u.name)));for(let u of d){let p=new Set(s.filter((l)=>l.type===c&&D(l.name)===u).map((l)=>R(l.content).toLowerCase())),m=a.filter((l)=>l.type===c&&D(l.name)===u&&!p.has(R(l.content).toLowerCase()));for(let l of m)o.warnings.push(`${u} has an undeclared ${c} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}function nr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function ir(e){return Boolean(e&&typeof e.createZone==="function")}var M=new Set(["NS"]);function v(e){return e.replace(/\.$/,"").toLowerCase()}function fn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(v)),s=new Set(t.map(v));if(r.size!==s.size)return!1;for(let o of r)if(!s.has(o))return!1;return!0}function I(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:v(r)}function O(e,t){return e.type===t.type&&v(e.name)===v(t.name)&&I(e)===I(t)}async function sr(e){let{domain:t,registrar:r,host:s,dryRun:o=!1}=e,i=new Set([...e.proxiedHosts??[]].map(v)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(fn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let p=await r.listRecords(t);if(!p.success)return a.push(`Could not read ${t} from ${r.name}: ${p.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let g of p.records){if(M.has(g.type)){u.records.push({record:g,status:"skipped",reason:`${g.type} describes the delegation itself; ${s.name} owns it`});continue}let y=tt.has(g.type)&&i.has(v(g.name));m.push({name:g.name,type:g.type,content:g.content,ttl:g.ttl,priority:g.priority,...tt.has(g.type)?{proxied:y}:{}})}if(o){for(let g of m)u.records.push({record:g,status:"copied",reason:"dry run"});return u}for(let g of m){let y;try{y=await s.upsertRecord(t,g)}catch(C){y={success:!1,message:C instanceof Error?C.message:String(C)}}u.records.push(y.success?{record:g,status:"copied"}:{record:g,status:"failed",reason:y.message})}let l=await s.listRecords(t);if(!l.success)return a.push(`Could not read back ${t} from ${s.name}: ${l.message??"unknown error"}`),u.status="blocked",u;for(let g of m)if(!l.records.some((y)=>O(g,y)))u.missing.push(g);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function L(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new ie(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new ke(t.godaddyApiKey,t.godaddyApiSecret);if(!nr(r))return"the GoDaddy provider cannot change nameservers";return r}async function is(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=L(r.provider,s);if(typeof o==="string")return{status:"skipped",reason:o};let i=new Be(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!ir(i))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return sr({domain:e.domain,registrar:o,host:i,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function ss(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}class he{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new h(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 s=await this.client.findHostedZoneForDomain(e);if(s){let o=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${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 s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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 s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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 s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}}),{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 s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let i of s.ResourceRecordSets){if(t&&i.Type!==t)continue;if(i.AliasTarget)continue;for(let a of i.ResourceRecords||[]){let c=a.Value,d;if(i.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(i.Type==="TXT"&&c.startsWith('"')&&c.endsWith('"'))c=c.slice(1,-1);o.push({name:i.Name.replace(/\.$/,""),type:i.Type,content:c,ttl:i.TTL,priority:d})}}return{success:!0,records:o}}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:h.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=h.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 os(e,t){let r=[],s,o;for(;;){let i=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:o,MaxItems:"100"});if(r.push(...i.ResourceRecordSets),!i.IsTruncated)break;if(s=i.NextRecordName,o=i.NextRecordType,!s)break}return r}function f(e){return e.replace(/\.$/,"").toLowerCase()}function E(e){return e.replace(/\.$/,"")}function w(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${E(e.content)}`;return E(e.content)}function U(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function as(e,t){let r=f(t),s=[],o=[],i=[],a=new Set;for(let c of e){let d=f(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){o.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){o.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),i.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let p=f(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:p,ttl:300,translatedFrom:`${u} ALIAS → ${p}`}),c.AliasTarget.EvaluateTargetHealth)i.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let p of c.ResourceRecords||[]){let m=q(d,u,p.Value,c.TTL);if("reason"in m){o.push({name:d,type:u,reason:m.reason}),i.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:o,warnings:i}}function q(e,t,r,s){let o={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:f(r)};case"TXT":return{...o,type:"TXT",content:U(r)};case"MX":{let[i,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:f(a.join(" ")),priority:Number(i)}}case"SRV":{let i=r.trim().split(/\s+/);if(i.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=i.slice(0,3).map(Number);return{...o,type:"SRV",content:f(i.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...o,type:"NS",content:f(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var j=new Set(["TXT","MX","SRV","NS","CAA"]);async function cs(e,t){let r=[],s=[],o=new Set;try{let i=await e.listRecords(t.zone);for(let a of i.records||[])o.add(`${f(a.name)}|${a.type}|${w(a)}`)}catch{}for(let i of t.records){let a={...i,proxied:!1},c=`${f(i.name)}|${i.type}|${w(i)}`;if(!j.has(i.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(i);else s.push({record:i,message:u.message||"unknown provider error"});continue}if(o.has(c)){r.push(i);continue}let d=await e.createRecord(t.zone,a);if(d.success)o.add(c),r.push(i);else s.push({record:i,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function ds(e,t){let r=await e.listRecords(t.zone),s=[],o=[],i=new Map;for(let a of r.records||[]){let c=`${f(a.name)}|${a.type}`,d=i.get(c)??[];d.push(w(a)),i.set(c,d)}for(let a of t.records){let c=i.get(`${f(a.name)}|${a.type}`),d=w(a);if(c?.some((u)=>u===d))s.push(a);else o.push({record:a,found:c?.join(", ")})}return{matched:s,missing:o,ok:o.length===0}}class oe{client;region;constructor(e="us-east-1"){this.client=new n,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((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.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((s)=>({CertificateArn:s.CertificateArn,DomainName:s.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((s)=>s.DomainName===e||s.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 s=0;s<t;s++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((i)=>setTimeout(i,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 s=r.DomainName.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let o=s.slice(2),i=t.split("."),a=o.split(".");if(i.slice(-a.length).join(".")===o)return!0}}return!1}}class or{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new oe(e),this.route53=new h,t&&t.provider!=="route53")this.dnsProvider=T(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:o=!1,maxWaitMinutes:i=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(a,i*2,30000))throw Error(`Certificate validation timed out after ${i} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),i=[];if(this.dnsProvider){let a=s||o[0]?.domainName;for(let c of o){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});i.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of o){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});i.push({...a,changeId:c.ChangeInfo?.Id})}return i}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let i=s||o[0]?.domainName;for(let a of o)try{await this.dnsProvider.deleteRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let i of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${i.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED")return{certificateArn:i.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class se{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new oe(t),"provider"in e)this.dnsProvider=T(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e,{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(i,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:i,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.upsertRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,records:o.map((i)=>({domainName:i.domainName,recordName:i.recordName,recordType:i.recordType,recordValue:i.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.deleteRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue});if(!a.success)s.push(`Failed to delete record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:o}=e,i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED"){let a=i.SubjectAlternativeNames||[i.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:i.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:s,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:o=[],waitForValidation:i=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:i})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,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 ls(e,t,r){return new se({provider:"porkbun",apiKey:e,secretKey:t},r)}function us(e,t,r,s){return new se({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function ps(e,t,r){return new se({provider:"route53",region:e,hostedZoneId:t},r||e)}function T(e){switch(e.provider){case"route53":return new he(e.region,e.hostedZoneId);case"porkbun":return new ie(e.apiKey,e.secretKey);case"godaddy":return new ke(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new Be(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Oa(e,t){for(let r of t){let s=T(r);if(await s.canManageDomain(e))return s}return null}class An{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,s=process.env.GODADDY_API_SECRET;if(r&&s){let i=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,i)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{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((o)=>o.provider===e);if(!r)return null;let s=T(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=T(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>T(e))}}var La=new An;
2
+ export{tt,ie,ke,ts,Be,Tt,hn,rs,ns,nr,ir,fn,sr,is,ss,he,os,as,cs,ds,se,ls,us,ps,T,Oa,An,La,oe,or};