@stacksjs/ts-cloud 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-1a1m00zc.js +2 -0
  3. package/dist/bin/{chunk-y671cgz5.js → chunk-ajfvpq8r.js} +1 -1
  4. package/dist/bin/{chunk-jee6msvx.js → chunk-jgtdz9ac.js} +2 -2
  5. package/dist/bin/{chunk-88ysj8n5.js → chunk-zk1z04ng.js} +1 -1
  6. package/dist/bin/cli.js +5 -5
  7. package/dist/bin/dashboard-server.js +1 -1
  8. package/dist/{chunk-mcfdtg5w.js → chunk-1bxqrj7m.js} +1 -1
  9. package/dist/{chunk-t5tvt2r3.js → chunk-2k1tc16d.js} +94 -94
  10. package/dist/chunk-2ke75pzn.js +1 -0
  11. package/dist/{chunk-2s65yj3g.js → chunk-4w8d2mf0.js} +2 -2
  12. package/dist/{chunk-r4dpn715.js → chunk-9s5sm0wt.js} +6 -6
  13. package/dist/{chunk-asmv4fw1.js → chunk-a0d0h33y.js} +19 -19
  14. package/dist/chunk-a6jazwvy.js +1 -0
  15. package/dist/{chunk-vk513ge7.js → chunk-b2b79jtk.js} +60 -60
  16. package/dist/{chunk-y13zcbnp.js → chunk-b9pm7mbd.js} +84 -84
  17. package/dist/{chunk-hyj2ymp1.js → chunk-bkv2p4hp.js} +6 -6
  18. package/dist/{chunk-z7v4evbh.js → chunk-cwjskpj4.js} +2 -2
  19. package/dist/{chunk-xqx5szta.js → chunk-dky93h4d.js} +17 -17
  20. package/dist/{chunk-dzqz1sm0.js → chunk-etmbw4er.js} +3 -3
  21. package/dist/{chunk-p9fqsz06.js → chunk-gdbtz492.js} +2 -2
  22. package/dist/chunk-h1anhx3y.js +1 -0
  23. package/dist/{chunk-42kv07cs.js → chunk-jghkvdgt.js} +1 -1
  24. package/dist/{chunk-w5fmaaxa.js → chunk-jnt7ab86.js} +4 -4
  25. package/dist/chunk-kfwg1c6q.js +2 -0
  26. package/dist/chunk-kgw1dd9b.js +1 -0
  27. package/dist/chunk-phr1cqgf.js +1 -0
  28. package/dist/{chunk-nhtz2k8d.js → chunk-q4bk0htq.js} +5 -5
  29. package/dist/{chunk-ngdhqwf3.js → chunk-srh0ctd4.js} +3 -3
  30. package/dist/{chunk-8s9m8pyb.js → chunk-sxtgx8fj.js} +1 -1
  31. package/dist/{chunk-65ajja2a.js → chunk-t054j0zn.js} +1 -1
  32. package/dist/{chunk-6gtqjsg9.js → chunk-t5e5phth.js} +1 -1
  33. package/dist/{chunk-ds92qg3g.js → chunk-tg6yasej.js} +3 -3
  34. package/dist/{chunk-0g2jkhy5.js → chunk-trsaqsgv.js} +1 -1
  35. package/dist/{chunk-m5r0dt28.js → chunk-xacvkpf8.js} +2 -2
  36. package/dist/{chunk-nw0tvrrr.js → chunk-xv3w9q1a.js} +1 -1
  37. package/dist/{chunk-j7vsrx9g.js → chunk-zhg1kvw3.js} +5 -5
  38. package/dist/deploy/index.js +1 -1
  39. package/dist/dns/cloudflare-managed-headers.test.d.ts +1 -0
  40. package/dist/dns/cloudflare.d.ts +52 -0
  41. package/dist/dns/delegate-from-config.d.ts +40 -0
  42. package/dist/dns/index.d.ts +2 -2
  43. package/dist/dns/index.js +1 -1
  44. package/dist/drivers/index.js +1 -1
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.js +36 -36
  47. package/dist/operations/index.js +1 -1
  48. package/dist/protection/index.js +1 -1
  49. package/dist/spend/index.js +1 -1
  50. package/dist/ui/404.html +1 -1
  51. package/dist/ui/accept-invitation.html +1 -1
  52. package/dist/ui/access-denied.html +1 -1
  53. package/dist/ui/account/automation.html +6 -6
  54. package/dist/ui/account/security.html +2 -2
  55. package/dist/ui/applications/compose.html +6 -6
  56. package/dist/ui/applications/new.html +2 -2
  57. package/dist/ui/data/backups.html +6 -6
  58. package/dist/ui/data/services.html +6 -6
  59. package/dist/ui/data/volumes.html +6 -6
  60. package/dist/ui/index.html +6 -6
  61. package/dist/ui/infrastructure/topology.html +6 -6
  62. package/dist/ui/integrations.html +2 -2
  63. package/dist/ui/operations/alerts.html +6 -6
  64. package/dist/ui/operations/configuration.html +6 -6
  65. package/dist/ui/operations/jobs.html +6 -6
  66. package/dist/ui/operations/maintenance.html +6 -6
  67. package/dist/ui/operations/observability.html +6 -6
  68. package/dist/ui/operations/previews.html +6 -6
  69. package/dist/ui/operations/queue.html +6 -6
  70. package/dist/ui/operations/regions.html +6 -6
  71. package/dist/ui/operations/releases.html +6 -6
  72. package/dist/ui/operations/spend.html +6 -6
  73. package/dist/ui/operations/workloads.html +5 -5
  74. package/dist/ui/security.html +2 -2
  75. package/dist/ui/server/actions.html +6 -6
  76. package/dist/ui/server/activity.html +2 -2
  77. package/dist/ui/server/capacity.html +6 -6
  78. package/dist/ui/server/database.html +6 -6
  79. package/dist/ui/server/deployments.html +5 -5
  80. package/dist/ui/server/diagnostics.html +2 -2
  81. package/dist/ui/server/firewall.html +6 -6
  82. package/dist/ui/server/fleet.html +6 -6
  83. package/dist/ui/server/logs.html +6 -6
  84. package/dist/ui/server/metrics.html +5 -5
  85. package/dist/ui/server/security.html +2 -2
  86. package/dist/ui/server/services.html +2 -2
  87. package/dist/ui/server/sites.html +6 -6
  88. package/dist/ui/server/ssh-keys.html +6 -6
  89. package/dist/ui/server/team.html +6 -6
  90. package/dist/ui/server/terminal.html +2 -2
  91. package/dist/ui/serverless/alarms.html +5 -5
  92. package/dist/ui/serverless/assets.html +2 -2
  93. package/dist/ui/serverless/cost.html +2 -2
  94. package/dist/ui/serverless/data.html +6 -6
  95. package/dist/ui/serverless/deployments.html +2 -2
  96. package/dist/ui/serverless/firewall.html +1 -1
  97. package/dist/ui/serverless/functions.html +6 -6
  98. package/dist/ui/serverless/logs.html +6 -6
  99. package/dist/ui/serverless/metrics.html +2 -2
  100. package/dist/ui/serverless/queues.html +6 -6
  101. package/dist/ui/serverless/secrets.html +6 -6
  102. package/dist/ui/serverless/traces.html +6 -6
  103. package/dist/ui/serverless.html +6 -6
  104. package/package.json +3 -3
  105. package/dist/bin/chunk-2ahgpy3j.js +0 -2
  106. package/dist/chunk-05qawkra.js +0 -1
  107. package/dist/chunk-3qtce4mm.js +0 -1
  108. package/dist/chunk-3tt5em2c.js +0 -1
  109. package/dist/chunk-a1p70h5d.js +0 -2
  110. package/dist/chunk-jdq95b4h.js +0 -1
  111. package/dist/chunk-wr7tn9j5.js +0 -1
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-2s65yj3g.js";class Ar{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
1
+ import{n}from"./chunk-4w8d2mf0.js";class Ar{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
2
2
  `).slice(-t.tailLines).join(`
3
- `);return r}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(a.instanceStatusSet?.item).map((r)=>({InstanceId:r.instanceId,InstanceState:r.instanceState?{Code:Number.parseInt(r.instanceState.code),Name:r.instanceState.name}:void 0,InstanceStatus:r.instanceStatus?{Status:r.instanceStatus.status,Details:this.parseArray(r.instanceStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0,SystemStatus:r.systemStatus?{Status:r.systemStatus.status,Details:this.parseArray(r.systemStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async stopInstances(e,t){let a={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((s,i)=>{a[`InstanceId.${i+1}`]=s}),t)a.Force="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()});return{StoppingInstances:this.parseArray(r.instancesSet?.item).map((s)=>({InstanceId:s.instanceId,CurrentState:s.currentState?{Name:s.currentState.name}:void 0,PreviousState:s.previousState?{Name:s.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((a,r)=>{t[`InstanceId.${r+1}`]=a}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(a.CreateImageResponse||a).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((r,s)=>{t[`VpcId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(a.vpcSet?.item).map((r)=>({VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((r,s)=>{t[`SubnetId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(a.subnetSet?.item).map((r)=>({SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:Number.parseInt(r.availableIpAddressCount),State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((r,s)=>{t[`GroupId.${s+1}`]=r});if(e?.GroupNames)e.GroupNames.forEach((r,s)=>{t[`GroupName.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(a.securityGroupInfo?.item).map((r)=>({GroupId:r.groupId,GroupName:r.groupName,Description:r.groupDescription,VpcId:r.vpcId,IpPermissions:this.parseIpPermissions(r.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(r.ipPermissionsEgress?.item),Tags:this.parseTags(r.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((r,s)=>{t[`InternetGatewayId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(a.internetGatewaySet?.item).map((r)=>({InternetGatewayId:r.internetGatewayId,Attachments:this.parseArray(r.attachmentSet?.item).map((s)=>({VpcId:s.vpcId,State:s.state})),Tags:this.parseTags(r.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((r,s)=>{t[`AllocationId.${s+1}`]=r});if(e?.PublicIps)e.PublicIps.forEach((r,s)=>{t[`PublicIp.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(a.addressesSet?.item).map((r)=>({PublicIp:r.publicIp,AllocationId:r.allocationId,AssociationId:r.associationId,InstanceId:r.instanceId,NetworkInterfaceId:r.networkInterfaceId,PrivateIpAddress:r.privateIpAddress,Domain:r.domain,Tags:this.parseTags(r.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((r,s)=>{t[`TagSpecification.${s+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,o)=>{t[`TagSpecification.${s+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${s+1}.Tag.${o+1}.Value`]=i.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:a.allocationId,PublicIp:a.publicIp,Domain:a.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((a,r)=>{t[`ResourceId.${r+1}`]=a}),e.Tags.forEach((a,r)=>{t[`Tag.${r+1}.Key`]=a.Key,t[`Tag.${r+1}.Value`]=a.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,a){let r=a?.maxWaitMs||300000,s=a?.pollIntervalMs||5000,i=Date.now();while(Date.now()-i<r){let o;try{o=await this.getInstance(e)}catch{o=void 0}if(o?.State?.Name===t)return o;await new Promise((c)=>setTimeout(c,s))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateVpcResponse||a).vpc;return{Vpc:s?{VpcId:s.vpcId,CidrBlock:s.cidrBlock,State:s.state,DhcpOptionsId:s.dhcpOptionsId,InstanceTenancy:s.instanceTenancy,IsDefault:s.isDefault==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateSubnetResponse||a).subnet;return{Subnet:s?{SubnetId:s.subnetId,VpcId:s.vpcId,CidrBlock:s.cidrBlock,AvailabilityZone:s.availabilityZone,AvailableIpAddressCount:s.availableIpAddressCount?Number.parseInt(s.availableIpAddressCount):void 0,State:s.state,MapPublicIpOnLaunch:s.mapPublicIpOnLaunch==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(a.CreateSecurityGroupResponse||a).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((s,i)=>{t[`RouteTableId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeRouteTablesResponse||a;return{RouteTables:this.parseArray(r.routeTableSet?.item).map((s)=>({RouteTableId:s.routeTableId,VpcId:s.vpcId,Routes:this.parseArray(s.routeSet?.item).map((i)=>({DestinationCidrBlock:i.destinationCidrBlock,GatewayId:i.gatewayId,NatGatewayId:i.natGatewayId,State:i.state})),Associations:this.parseArray(s.associationSet?.item).map((i)=>({RouteTableAssociationId:i.routeTableAssociationId,SubnetId:i.subnetId,Main:i.main==="true"||i.main===!0})),Tags:this.parseTags(s.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((s,i)=>{t[`NetworkInterfaceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeNetworkInterfacesResponse||a;return{NetworkInterfaces:this.parseArray(r.networkInterfaceSet?.item).map((s)=>({NetworkInterfaceId:s.networkInterfaceId,SubnetId:s.subnetId,VpcId:s.vpcId,Status:s.status,Attachment:s.attachment?{AttachmentId:s.attachment.attachmentId,InstanceId:s.attachment.instanceId,Status:s.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let a={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)a.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),a=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(a.regionInfo?.item).map((r)=>({RegionName:r.regionName,Endpoint:r.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((s,i)=>{t[`SecurityGroupId.${i+1}`]=s});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.RunInstancesResponse||a;return{Instances:this.parseInstances(r.instancesSet?.item||r.instancesSet)}}encodeIpPermissions(e,t){t.forEach((a,r)=>{let s=`IpPermissions.${r+1}`;if(a.IpProtocol!==void 0)e[`${s}.IpProtocol`]=a.IpProtocol;if(a.FromPort!==void 0)e[`${s}.FromPort`]=String(a.FromPort);if(a.ToPort!==void 0)e[`${s}.ToPort`]=String(a.ToPort);if(a.IpRanges)a.IpRanges.forEach((i,o)=>{if(i.CidrIp)e[`${s}.IpRanges.${o+1}.CidrIp`]=i.CidrIp;if(i.Description)e[`${s}.IpRanges.${o+1}.Description`]=i.Description});if(a.Ipv6Ranges)a.Ipv6Ranges.forEach((i,o)=>{if(i.CidrIpv6)e[`${s}.Ipv6Ranges.${o+1}.CidrIpv6`]=i.CidrIpv6;if(i.Description)e[`${s}.Ipv6Ranges.${o+1}.Description`]=i.Description});if(a.UserIdGroupPairs)a.UserIdGroupPairs.forEach((i,o)=>{if(i.GroupId)e[`${s}.Groups.${o+1}.GroupId`]=i.GroupId;if(i.UserId)e[`${s}.Groups.${o+1}.UserId`]=i.UserId;if(i.Description)e[`${s}.Groups.${o+1}.Description`]=i.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let a of this.parseArray(t?.ipv6AddressesSet?.item))if(a?.ipv6Address)return a.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((a)=>({GroupId:a.groupId,GroupName:a.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((a)=>({DeviceName:a.deviceName,Ebs:a.ebs?{VolumeId:a.ebs.volumeId,Status:a.ebs.status,AttachTime:a.ebs.attachTime,DeleteOnTermination:a.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((a)=>({CidrIp:a.cidrIp,Description:a.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((a)=>({CidrIpv6:a.cidrIpv6,Description:a.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((a)=>({GroupId:a.groupId,UserId:a.userId,Description:a.description}))}))}}class Se{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:a.Version,Tier:a.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:a.Parameter?this.parseParameter(a.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),InvalidParameters:a.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:a.DeletedParameters,InvalidParameters:a.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>({Name:r.Name,Type:r.Type,KeyId:r.KeyId,LastModifiedDate:r.LastModifiedDate,LastModifiedUser:r.LastModifiedUser,Description:r.Description,Value:r.Value,Version:r.Version,Labels:r.Labels,Tier:r.Tier})),NextToken:a.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:a.InvalidLabels,ParameterVersion:a.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"String",Description:a?.description,Overwrite:a?.overwrite??!0,Tags:a?.tags})}async setSecureString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:a?.description,Overwrite:a?.overwrite??!0,KeyId:a?.kmsKeyId,Tags:a?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let a=[],r;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:r});if(s.Parameters)a.push(...s.Parameters);r=s.NextToken}while(r);return a}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:a.Command?.CommandId,Status:a.Command?.Status,StatusDetails:a.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:a.Status,StatusDetails:a.StatusDetails,StandardOutputContent:a.StandardOutputContent,StandardErrorContent:a.StandardErrorContent,ResponseCode:a.ResponseCode}}async runShellCommand(e,t,a){let r=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:a?.timeoutSeconds||600});if(!r.CommandId)return{success:!1,error:"Failed to send command"};if(a?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=a?.pollIntervalMs||2000,i=a?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((c)=>setTimeout(c,s));try{let c=await this.getCommandInvocation({CommandId:r.CommandId,InstanceId:e});if(c.Status==="Success")return{success:!0,output:c.StandardOutputContent,error:c.StandardErrorContent,status:c.Status};if(c.Status==="Failed"||c.Status==="Cancelled"||c.Status==="TimedOut")return{success:!1,output:c.StandardOutputContent,error:c.StandardErrorContent||c.StatusDetails,status:c.Status}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,error:c.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([d,g])=>({Key:`tag:${d}`,Values:[g]})),a=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!a.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let r=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<s){await new Promise((d)=>setTimeout(d,r));try{if(c=await this.listCommandInvocations({CommandId:a.CommandId,Details:!0}),c.length===0)continue;if(c.every((g)=>o.has(g.Status||""))){let g=c.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent||u.StatusDetails})),m=c.every((u)=>u.Status==="Success");return{success:m,instanceCount:c.length,perInstance:g,error:m?void 0:"One or more instances reported a non-success status"}}}catch(d){if(!d.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:d.message}}}return{success:!1,instanceCount:c.length,perInstance:c.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}
4
- export{Ar,Se};
3
+ `);return r}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(a.instanceStatusSet?.item).map((r)=>({InstanceId:r.instanceId,InstanceState:r.instanceState?{Code:Number.parseInt(r.instanceState.code),Name:r.instanceState.name}:void 0,InstanceStatus:r.instanceStatus?{Status:r.instanceStatus.status,Details:this.parseArray(r.instanceStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0,SystemStatus:r.systemStatus?{Status:r.systemStatus.status,Details:this.parseArray(r.systemStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async stopInstances(e,t){let a={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((s,i)=>{a[`InstanceId.${i+1}`]=s}),t)a.Force="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()});return{StoppingInstances:this.parseArray(r.instancesSet?.item).map((s)=>({InstanceId:s.instanceId,CurrentState:s.currentState?{Name:s.currentState.name}:void 0,PreviousState:s.previousState?{Name:s.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((a,r)=>{t[`InstanceId.${r+1}`]=a}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(a.CreateImageResponse||a).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((r,s)=>{t[`VpcId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(a.vpcSet?.item).map((r)=>({VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((r,s)=>{t[`SubnetId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(a.subnetSet?.item).map((r)=>({SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:Number.parseInt(r.availableIpAddressCount),State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((r,s)=>{t[`GroupId.${s+1}`]=r});if(e?.GroupNames)e.GroupNames.forEach((r,s)=>{t[`GroupName.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(a.securityGroupInfo?.item).map((r)=>({GroupId:r.groupId,GroupName:r.groupName,Description:r.groupDescription,VpcId:r.vpcId,IpPermissions:this.parseIpPermissions(r.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(r.ipPermissionsEgress?.item),Tags:this.parseTags(r.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((r,s)=>{t[`InternetGatewayId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(a.internetGatewaySet?.item).map((r)=>({InternetGatewayId:r.internetGatewayId,Attachments:this.parseArray(r.attachmentSet?.item).map((s)=>({VpcId:s.vpcId,State:s.state})),Tags:this.parseTags(r.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((r,s)=>{t[`AllocationId.${s+1}`]=r});if(e?.PublicIps)e.PublicIps.forEach((r,s)=>{t[`PublicIp.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(a.addressesSet?.item).map((r)=>({PublicIp:r.publicIp,AllocationId:r.allocationId,AssociationId:r.associationId,InstanceId:r.instanceId,NetworkInterfaceId:r.networkInterfaceId,PrivateIpAddress:r.privateIpAddress,Domain:r.domain,Tags:this.parseTags(r.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((r,s)=>{t[`TagSpecification.${s+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,o)=>{t[`TagSpecification.${s+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${s+1}.Tag.${o+1}.Value`]=i.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:a.allocationId,PublicIp:a.publicIp,Domain:a.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((a,r)=>{t[`ResourceId.${r+1}`]=a}),e.Tags.forEach((a,r)=>{t[`Tag.${r+1}.Key`]=a.Key,t[`Tag.${r+1}.Value`]=a.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,a){let r=a?.maxWaitMs||300000,s=a?.pollIntervalMs||5000,i=Date.now();while(Date.now()-i<r){let o;try{o=await this.getInstance(e)}catch{o=void 0}if(o?.State?.Name===t)return o;await new Promise((c)=>setTimeout(c,s))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateVpcResponse||a).vpc;return{Vpc:s?{VpcId:s.vpcId,CidrBlock:s.cidrBlock,State:s.state,DhcpOptionsId:s.dhcpOptionsId,InstanceTenancy:s.instanceTenancy,IsDefault:s.isDefault==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateSubnetResponse||a).subnet;return{Subnet:s?{SubnetId:s.subnetId,VpcId:s.vpcId,CidrBlock:s.cidrBlock,AvailabilityZone:s.availabilityZone,AvailableIpAddressCount:s.availableIpAddressCount?Number.parseInt(s.availableIpAddressCount):void 0,State:s.state,MapPublicIpOnLaunch:s.mapPublicIpOnLaunch==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(a.CreateSecurityGroupResponse||a).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((s,i)=>{t[`RouteTableId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeRouteTablesResponse||a;return{RouteTables:this.parseArray(r.routeTableSet?.item).map((s)=>({RouteTableId:s.routeTableId,VpcId:s.vpcId,Routes:this.parseArray(s.routeSet?.item).map((i)=>({DestinationCidrBlock:i.destinationCidrBlock,GatewayId:i.gatewayId,NatGatewayId:i.natGatewayId,State:i.state})),Associations:this.parseArray(s.associationSet?.item).map((i)=>({RouteTableAssociationId:i.routeTableAssociationId,SubnetId:i.subnetId,Main:i.main==="true"||i.main===!0})),Tags:this.parseTags(s.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((s,i)=>{t[`NetworkInterfaceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeNetworkInterfacesResponse||a;return{NetworkInterfaces:this.parseArray(r.networkInterfaceSet?.item).map((s)=>({NetworkInterfaceId:s.networkInterfaceId,SubnetId:s.subnetId,VpcId:s.vpcId,Status:s.status,Attachment:s.attachment?{AttachmentId:s.attachment.attachmentId,InstanceId:s.attachment.instanceId,Status:s.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let a={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)a.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),a=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(a.regionInfo?.item).map((r)=>({RegionName:r.regionName,Endpoint:r.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((s,i)=>{t[`SecurityGroupId.${i+1}`]=s});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.RunInstancesResponse||a;return{Instances:this.parseInstances(r.instancesSet?.item||r.instancesSet)}}encodeIpPermissions(e,t){t.forEach((a,r)=>{let s=`IpPermissions.${r+1}`;if(a.IpProtocol!==void 0)e[`${s}.IpProtocol`]=a.IpProtocol;if(a.FromPort!==void 0)e[`${s}.FromPort`]=String(a.FromPort);if(a.ToPort!==void 0)e[`${s}.ToPort`]=String(a.ToPort);if(a.IpRanges)a.IpRanges.forEach((i,o)=>{if(i.CidrIp)e[`${s}.IpRanges.${o+1}.CidrIp`]=i.CidrIp;if(i.Description)e[`${s}.IpRanges.${o+1}.Description`]=i.Description});if(a.Ipv6Ranges)a.Ipv6Ranges.forEach((i,o)=>{if(i.CidrIpv6)e[`${s}.Ipv6Ranges.${o+1}.CidrIpv6`]=i.CidrIpv6;if(i.Description)e[`${s}.Ipv6Ranges.${o+1}.Description`]=i.Description});if(a.UserIdGroupPairs)a.UserIdGroupPairs.forEach((i,o)=>{if(i.GroupId)e[`${s}.Groups.${o+1}.GroupId`]=i.GroupId;if(i.UserId)e[`${s}.Groups.${o+1}.UserId`]=i.UserId;if(i.Description)e[`${s}.Groups.${o+1}.Description`]=i.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let a of this.parseArray(t?.ipv6AddressesSet?.item))if(a?.ipv6Address)return a.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((a)=>({GroupId:a.groupId,GroupName:a.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((a)=>({DeviceName:a.deviceName,Ebs:a.ebs?{VolumeId:a.ebs.volumeId,Status:a.ebs.status,AttachTime:a.ebs.attachTime,DeleteOnTermination:a.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((a)=>({CidrIp:a.cidrIp,Description:a.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((a)=>({CidrIpv6:a.cidrIpv6,Description:a.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((a)=>({GroupId:a.groupId,UserId:a.userId,Description:a.description}))}))}}class Ce{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:a.Version,Tier:a.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:a.Parameter?this.parseParameter(a.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),InvalidParameters:a.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:a.DeletedParameters,InvalidParameters:a.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>({Name:r.Name,Type:r.Type,KeyId:r.KeyId,LastModifiedDate:r.LastModifiedDate,LastModifiedUser:r.LastModifiedUser,Description:r.Description,Value:r.Value,Version:r.Version,Labels:r.Labels,Tier:r.Tier})),NextToken:a.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:a.InvalidLabels,ParameterVersion:a.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"String",Description:a?.description,Overwrite:a?.overwrite??!0,Tags:a?.tags})}async setSecureString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:a?.description,Overwrite:a?.overwrite??!0,KeyId:a?.kmsKeyId,Tags:a?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let a=[],r;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:r});if(s.Parameters)a.push(...s.Parameters);r=s.NextToken}while(r);return a}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:a.Command?.CommandId,Status:a.Command?.Status,StatusDetails:a.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:a.Status,StatusDetails:a.StatusDetails,StandardOutputContent:a.StandardOutputContent,StandardErrorContent:a.StandardErrorContent,ResponseCode:a.ResponseCode}}async runShellCommand(e,t,a){let r=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:a?.timeoutSeconds||600});if(!r.CommandId)return{success:!1,error:"Failed to send command"};if(a?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=a?.pollIntervalMs||2000,i=a?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((c)=>setTimeout(c,s));try{let c=await this.getCommandInvocation({CommandId:r.CommandId,InstanceId:e});if(c.Status==="Success")return{success:!0,output:c.StandardOutputContent,error:c.StandardErrorContent,status:c.Status};if(c.Status==="Failed"||c.Status==="Cancelled"||c.Status==="TimedOut")return{success:!1,output:c.StandardOutputContent,error:c.StandardErrorContent||c.StatusDetails,status:c.Status}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,error:c.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([d,g])=>({Key:`tag:${d}`,Values:[g]})),a=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!a.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let r=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<s){await new Promise((d)=>setTimeout(d,r));try{if(c=await this.listCommandInvocations({CommandId:a.CommandId,Details:!0}),c.length===0)continue;if(c.every((g)=>o.has(g.Status||""))){let g=c.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent||u.StatusDetails})),m=c.every((u)=>u.Status==="Success");return{success:m,instanceCount:c.length,perInstance:g,error:m?void 0:"One or more instances reported a non-success status"}}}catch(d){if(!d.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:d.message}}}return{success:!1,instanceCount:c.length,perInstance:c.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}
4
+ export{Ar,Ce};
@@ -1,2 +1,2 @@
1
- import{createRequire as q}from"node:module";var k=Object.create;var{getPrototypeOf:l,defineProperty:i,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,sh=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?k(l(a)):{};let c=b||!a||!a.__esModule||!j.call(a,"default")?i(d,"default",{value:a,enumerable:!0}):d;if(a&&typeof a==="object"||typeof a==="function"){for(let e of m(a))if(!j.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0})}if(f)g.set(a,c);return c};var oh=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var Me=q(import.meta.url);
2
- export{sh,oh,Me};
1
+ import{createRequire as q}from"node:module";var k=Object.create;var{getPrototypeOf:l,defineProperty:i,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,ah=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?k(l(a)):{};let c=b||!a||!a.__esModule||!j.call(a,"default")?i(d,"default",{value:a,enumerable:!0}):d;if(a&&typeof a==="object"||typeof a==="function"){for(let e of m(a))if(!j.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0})}if(f)g.set(a,c);return c};var ch=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var Me=q(import.meta.url);
2
+ export{ah,ch,Me};
@@ -0,0 +1 @@
1
+ import{Ta}from"./chunk-jnt7ab86.js";import"./chunk-cwjskpj4.js";import"./chunk-4w8d2mf0.js";import"./chunk-b9pm7mbd.js";export{Ta as buildAndPushServerlessImage};
@@ -1 +1 @@
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
+ import{Br}from"./chunk-9s5sm0wt.js";var Dd="\x00";function po(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&&!po(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 go{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 Pd(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 Nd(){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 kd="protection.controls",vi=24,mo=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 ho{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(kd);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(kd,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,mo)*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 Bd(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 xd(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 fo(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 IA(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:fo(o,i)}}}}export{Dd,po,bi,Ei,go,Pd,Nd,kd,vi,mo,ho,Bd,xd,fo,IA};
@@ -1,5 +1,5 @@
1
- import{to,Mr,yd,Ci,ao,co}from"./chunk-y13zcbnp.js";import{Ne}from"./chunk-z7v4evbh.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as S,mkdtempSync as U,rmSync as L,writeFileSync as d}from"node:fs";import{tmpdir as O}from"node:os";import{dirname as j,join as s}from"node:path";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function I(t,e){return`${r[e]}${t}${r.reset}`}function on(t){console.log(`${r.green}✓${r.reset} ${t}`)}function jl(t){console.error(`${r.red}✗${r.reset} ${t}`)}function Wi(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function P(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function v(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function Ji(t){console.log(`
1
+ import{no,Mr,Sd,Ci,lo,uo}from"./chunk-b9pm7mbd.js";import{ke}from"./chunk-cwjskpj4.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as S,mkdtempSync as U,rmSync as L,writeFileSync as d}from"node:fs";import{tmpdir as O}from"node:os";import{dirname as j,join as s}from"node:path";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function I(t,e){return`${r[e]}${t}${r.reset}`}function on(t){console.log(`${r.green}✓${r.reset} ${t}`)}function Kl(t){console.error(`${r.red}✗${r.reset} ${t}`)}function Wi(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function P(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function v(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function Ji(t){console.log(`
2
2
  ${r.bright}${r.cyan}${t}${r.reset}
3
- `)}var F=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function zl(t,e="cyan"){let n=t.split(`
4
- `),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(I(`┌${a}┐`,e)),n.forEach((l)=>{console.log(I(`│ ${l.padEnd(i)} │`,e))}),console.log(I(`└${a}┘`,e))}function A(t,e){for(let n of e){let i=s(t,n.name);S(j(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function Ea(t){let{app:e,projectRoot:n,region:i,repository:a}=t,l=e.architecture??"x86_64",R=l==="arm64"?"linux/arm64":"linux/amd64",E=e.kind==="php",c=t.onStep??(()=>{}),p=U(s(O(),"tscloud-img-"));try{let f=s(p,"app");S(f,{recursive:!0});let y,w;if(E){ao({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c}),c("staging application tree");let o=co(n);A(f,o),A(s(p,"runtime"),Ci().map((g)=>({name:g.path,data:g.contents,mode:g.mode})));let b=e.handlers?.http??"public/index.php";y={http:b,queue:e.handlers?.queue??b,cli:e.handlers?.cli??b},w=to(o.map((g)=>`${g.name}:${g.data.length}`).join("|"))}else{c("bundling application");let o=await Mr({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c});d(s(f,"index.mjs"),o.bundle),y=o.handlers,w=o.sha256}let k=w.slice(0,16);d(s(p,"Dockerfile"),yd({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:l}));let x=new Ne(i),u;try{u=(await x.describeRepositories({repositoryNames:[a]})).repositories?.[0]?.repositoryUri??""}catch{u=""}if(!u)c(`creating ECR repository ${a}`),u=(await x.createRepository({repositoryName:a,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!u)throw Error(`could not resolve ECR repository URI for ${a}`);let m=`${u}:${k}`;c("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",m,p],{stdio:"inherit"}),c("ecr auth + push");let h=(await x.getAuthorizationToken()).authorizationData?.[0];if(!h?.authorizationToken||!h.proxyEndpoint)throw Error("failed to get an ECR authorization token");let T=h.proxyEndpoint.replace(/^https?:\/\//,""),B=s(p,".docker");return S(B,{recursive:!0}),d(s(B,"config.json"),JSON.stringify({auths:{[T]:{auth:h.authorizationToken}}})),C("docker",["push",m],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:B}}),P(`Image: ${m}`),{imageUri:m,tag:k,handlers:y}}finally{L(p,{recursive:!0,force:!0})}}
5
- export{on,jl,Wi,P,v,Ji,zl,Ea};
3
+ `)}var F=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function Wl(t,e="cyan"){let n=t.split(`
4
+ `),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(I(`┌${a}┐`,e)),n.forEach((l)=>{console.log(I(`│ ${l.padEnd(i)} │`,e))}),console.log(I(`└${a}┘`,e))}function A(t,e){for(let n of e){let i=s(t,n.name);S(j(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function Ta(t){let{app:e,projectRoot:n,region:i,repository:a}=t,l=e.architecture??"x86_64",R=l==="arm64"?"linux/arm64":"linux/amd64",E=e.kind==="php",c=t.onStep??(()=>{}),p=U(s(O(),"tscloud-img-"));try{let f=s(p,"app");S(f,{recursive:!0});let y,w;if(E){lo({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c}),c("staging application tree");let o=uo(n);A(f,o),A(s(p,"runtime"),Ci().map((g)=>({name:g.path,data:g.contents,mode:g.mode})));let b=e.handlers?.http??"public/index.php";y={http:b,queue:e.handlers?.queue??b,cli:e.handlers?.cli??b},w=no(o.map((g)=>`${g.name}:${g.data.length}`).join("|"))}else{c("bundling application");let o=await Mr({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c});d(s(f,"index.mjs"),o.bundle),y=o.handlers,w=o.sha256}let k=w.slice(0,16);d(s(p,"Dockerfile"),Sd({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:l}));let x=new ke(i),u;try{u=(await x.describeRepositories({repositoryNames:[a]})).repositories?.[0]?.repositoryUri??""}catch{u=""}if(!u)c(`creating ECR repository ${a}`),u=(await x.createRepository({repositoryName:a,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!u)throw Error(`could not resolve ECR repository URI for ${a}`);let m=`${u}:${k}`;c("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",m,p],{stdio:"inherit"}),c("ecr auth + push");let h=(await x.getAuthorizationToken()).authorizationData?.[0];if(!h?.authorizationToken||!h.proxyEndpoint)throw Error("failed to get an ECR authorization token");let T=h.proxyEndpoint.replace(/^https?:\/\//,""),B=s(p,".docker");return S(B,{recursive:!0}),d(s(B,"config.json"),JSON.stringify({auths:{[T]:{auth:h.authorizationToken}}})),C("docker",["push",m],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:B}}),P(`Image: ${m}`),{imageUri:m,tag:k,handlers:y}}finally{L(p,{recursive:!0,force:!0})}}
5
+ export{on,Kl,Wi,P,v,Ji,Wl,Ta};
@@ -0,0 +1,2 @@
1
+ import{n}from"./chunk-4w8d2mf0.js";import{h}from"./chunk-t054j0zn.js";var tt=new Set(["A","AAAA","CNAME"]);function N(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}`),!N(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"}`),!N(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 Be{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 k="https://api.cloudflare.com/client/v4",ts="[ts-cloud]";class he{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=`${k}${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=_(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&&S(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 getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let o of r.result?.managed_request_headers||[])s[o.id]=o.enabled===!0;return s}async applyManagedRequestHeaders(e,t){let r=[],s=[],o=Object.entries(t).filter(([,d])=>d!==void 0);if(o.length===0)return{changed:r,failed:s};let i=await this.getZoneId(e),a=await this.getManagedRequestHeaders(e).catch(()=>({})),c=o.filter(([d,u])=>a[d]!==u);if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${i}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[m]of c)s.push({id:m,error:u})}return{changed:r,failed:s}}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 S(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)=>S(o,t[i]))}let r=e,s=t;return Object.keys(s).every((o)=>S(r[o],s[o]))}function _(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 Z=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 V(e,t){if(e.type!==t.type)return!1;if(D(e.name)!==D(t.name))return!1;if(Z.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 M(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)=>V(l,c));if(d.length>0&&d.every((l)=>M(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}:{}},m=c.type==="TXT"&&Tt(c.content)!==void 0;if(m)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 p=m||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(p.success)o.outcomes.push({record:c,action:d.length>0?"updated":"created"});else o.outcomes.push({record:c,action:"failed",message:p.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 m=new Set(s.filter((l)=>l.type===c&&D(l.name)===u).map((l)=>R(l.content).toLowerCase())),p=a.filter((l)=>l.type===c&&D(l.name)===u&&!m.has(R(l.content).toLowerCase()));for(let l of p)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 O=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 z(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 m=await r.listRecords(t);if(!m.success)return a.push(`Could not read ${t} from ${r.name}: ${m.message??"unknown error"}`),u.status="blocked",u;let p=[];for(let g of m.records){if(O.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));p.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 p)u.records.push({record:g,status:"copied",reason:"dry run"});return u}for(let g of p){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 p)if(!l.records.some((y)=>z(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}var L={add_visitor_location_headers:"visitorLocationHeaders"};function E(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 U(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 Be(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??E(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=U(r.provider,s);if(typeof o==="string")return{status:"skipped",reason:o};let i=new he(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}function q(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function j(e){let t={};for(let[r,s]of Object.entries(L)){let o=e[s];if(typeof o==="boolean")t[r]=o}return t}async function os(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=q(e.zone),s=j(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0)return{status:"skipped",reason:"dns.zone declares no settings"};let o=t.credentials??E(t.env??process.env);if(!o.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=new he(o.cloudflareApiToken,{accountId:o.cloudflareAccountId}),a=await i.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await i.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=[...a.changed,...c.changed],u=[...a.failed,...c.failed];return{status:d.length>0?"applied":"unchanged",domain:e.domain,changed:d,failed:u}}function as(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class fe{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 cs(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 x(e){return e.replace(/\.$/,"")}function w(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${x(e.content)}`;return x(e.content)}function H(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function ds(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 m=f(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:m,ttl:300,translatedFrom:`${u} ALIAS → ${m}`}),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 m of c.ResourceRecords||[]){let p=F(d,u,m.Value,c.TTL);if("reason"in p){o.push({name:d,type:u,reason:p.reason}),i.push(`${u} ${d}: ${p.reason}`);continue}s.push(p)}}return{zone:r,records:s,skipped:o,warnings:i}}function F(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:H(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 K=new Set(["TXT","MX","SRV","NS","CAA"]);async function ls(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(!K.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 us(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 ps(e,t,r){return new se({provider:"porkbun",apiKey:e,secretKey:t},r)}function gs(e,t,r,s){return new se({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function ms(e,t,r){return new se({provider:"route53",region:e,hostedZoneId:t},r||e)}function T(e){switch(e.provider){case"route53":return new fe(e.region,e.hostedZoneId);case"porkbun":return new ie(e.apiKey,e.secretKey);case"godaddy":return new Be(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new he(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function $a(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 Ma=new An;
2
+ export{tt,ie,Be,ts,he,Tt,hn,rs,ns,nr,ir,fn,sr,is,ss,os,as,fe,cs,ds,ls,us,se,ps,gs,ms,T,$a,An,Ma,oe,or};
@@ -0,0 +1 @@
1
+ import{yr,n,l,dh}from"./chunk-4w8d2mf0.js";export{n as AWSClient,l as buildQueryParams,dh as detectCredentialSource,yr as resolveS3Endpoint};
@@ -0,0 +1 @@
1
+ import{mn,qm}from"./chunk-srh0ctd4.js";import"./chunk-t054j0zn.js";import"./chunk-t5e5phth.js";import"./chunk-4w8d2mf0.js";export{mn as EmailClient,qm as email};
@@ -1,8 +1,8 @@
1
- var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function W(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function Wn(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?Cs(n.path):".*";if(!Wn(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${W(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${W(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${W(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function Cs(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function pc(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
1
+ var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function W(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function Wn(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?Es(n.path):".*";if(!Wn(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${W(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${W(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${W(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function Es(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function mc(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
2
2
  `)}
3
- `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${W(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=Cs(a);if(!Wn(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${W(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${W(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${W(a.reason)}`),a.pathPattern){if(!Wn(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${W(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
3
+ `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${W(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=Es(a);if(!Wn(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${W(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${W(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${W(a.reason)}`),a.pathPattern){if(!Wn(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${W(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
4
4
  `)}
5
- `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function Jn(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=pc(e,r);return`#!/usr/bin/env bash
5
+ `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function Jn(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=mc(e,r);return`#!/usr/bin/env bash
6
6
  # Managed by ts-cloud. Installs the zig-waf ruleset.
7
7
  set -euo pipefail
8
8
 
@@ -33,5 +33,5 @@ fi
33
33
 
34
34
  mv "${s}.new" "${s}"
35
35
  echo "ts-cloud: WAF config installed (mode: ${n.mode})"
36
- `}function xu(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
- export{W,Wn,Cs,pc,Jn,xu};
36
+ `}function Ou(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
+ export{W,Wn,Es,mc,Jn,Ou};