@stacksjs/ts-cloud 0.11.7 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-0rtn6q5x.js +3 -0
  3. package/dist/bin/chunk-258ehp9s.js +1 -0
  4. package/dist/bin/chunk-2yctv06c.js +1 -0
  5. package/dist/bin/chunk-3276rveh.js +37 -0
  6. package/dist/bin/chunk-3m665jwp.js +70 -0
  7. package/dist/bin/chunk-3s2p9vxj.js +1 -0
  8. package/dist/bin/chunk-4esma5m9.js +1 -0
  9. package/dist/bin/chunk-4n0j3n3b.js +2 -0
  10. package/dist/bin/chunk-54bqchag.js +92 -0
  11. package/dist/bin/{chunk-4q6tad44.js → chunk-5bhx3bsa.js} +121 -121
  12. package/dist/bin/chunk-5zagqd20.js +1 -0
  13. package/dist/bin/chunk-7hw2js5h.js +512 -0
  14. package/dist/bin/chunk-8h1qr6x4.js +50 -0
  15. package/dist/bin/{chunk-w32xv8n4.js → chunk-9vdc7adf.js} +6 -6
  16. package/dist/bin/chunk-a1dd6sby.js +1 -0
  17. package/dist/bin/chunk-a4dw35gs.js +1 -0
  18. package/dist/bin/chunk-a9d55ker.js +1 -0
  19. package/dist/bin/chunk-awa1qade.js +9 -0
  20. package/dist/bin/chunk-b6by94pk.js +2 -0
  21. package/dist/bin/chunk-c8sypnbe.js +2 -0
  22. package/dist/bin/chunk-cx4e3d4w.js +1 -0
  23. package/dist/bin/chunk-d5a3vheh.js +2 -0
  24. package/dist/bin/chunk-e1fym2bd.js +1 -0
  25. package/dist/bin/chunk-ej4h0q2y.js +1 -0
  26. package/dist/bin/chunk-ett305ym.js +4 -0
  27. package/dist/bin/chunk-f11xf3n6.js +2 -0
  28. package/dist/bin/chunk-fq7ktvgy.js +3 -0
  29. package/dist/bin/chunk-fyq4th2m.js +1 -0
  30. package/dist/bin/chunk-g67qr8yf.js +1 -0
  31. package/dist/bin/chunk-gc82cx4h.js +1 -0
  32. package/dist/bin/chunk-hchtvpr9.js +1 -0
  33. package/dist/bin/chunk-hpe4jjce.js +1 -0
  34. package/dist/bin/chunk-k5vprsef.js +6 -0
  35. package/dist/bin/chunk-m22krd4z.js +3 -0
  36. package/dist/bin/chunk-mkppcwz8.js +1 -0
  37. package/dist/bin/chunk-mpjg0kc7.js +2 -0
  38. package/dist/bin/chunk-mrm4m4dk.js +2 -0
  39. package/dist/bin/chunk-nff46rxd.js +1 -0
  40. package/dist/bin/chunk-np1z3bgt.js +1 -0
  41. package/dist/bin/chunk-nskxkk6r.js +1 -0
  42. package/dist/bin/chunk-pez932b1.js +111 -0
  43. package/dist/bin/chunk-qsdf5kzk.js +2 -0
  44. package/dist/bin/chunk-r61qmhv1.js +2 -0
  45. package/dist/bin/chunk-r6gdcz5c.js +1 -0
  46. package/dist/bin/chunk-satwnr42.js +2 -0
  47. package/dist/bin/{chunk-dz1ec589.js → chunk-scqmd4qv.js} +30 -30
  48. package/dist/bin/chunk-smbycpt5.js +44 -0
  49. package/dist/bin/chunk-sn7e0sn7.js +2 -0
  50. package/dist/bin/chunk-ss574pka.js +1 -0
  51. package/dist/bin/chunk-tj0xb2d8.js +585 -0
  52. package/dist/bin/chunk-v3rzf9d0.js +141 -0
  53. package/dist/bin/chunk-wnpma6t3.js +34 -0
  54. package/dist/bin/chunk-xan0e052.js +5 -0
  55. package/dist/bin/chunk-xbk2y43r.js +60 -0
  56. package/dist/bin/chunk-xjp3v95e.js +6 -0
  57. package/dist/bin/chunk-xyt490vp.js +6 -0
  58. package/dist/bin/chunk-yn9r02gy.js +1 -0
  59. package/dist/bin/chunk-zhkhn9cc.js +1 -0
  60. package/dist/bin/cli.js +445 -430
  61. package/dist/bin/dashboard-server.js +1 -1
  62. package/dist/chunk-0zf72ngj.js +1 -0
  63. package/dist/chunk-2hpjte1d.js +704 -0
  64. package/dist/chunk-4m6gwhwr.js +5 -0
  65. package/dist/chunk-5m29dhke.js +34 -0
  66. package/dist/chunk-6fzeemcs.js +114 -0
  67. package/dist/{chunk-zz52xje8.js → chunk-6xcbfs2r.js} +111 -111
  68. package/dist/chunk-bpnhqb70.js +6 -0
  69. package/dist/chunk-ead1nkbr.js +60 -0
  70. package/dist/chunk-fea461tj.js +141 -0
  71. package/dist/chunk-fvjczc73.js +1 -0
  72. package/dist/chunk-gearw6rk.js +4 -0
  73. package/dist/chunk-j60hesb3.js +2 -0
  74. package/dist/chunk-pmgtmt3d.js +1 -0
  75. package/dist/chunk-prf2pkvq.js +5 -0
  76. package/dist/chunk-q0wffgw5.js +37 -0
  77. package/dist/chunk-qcemnt35.js +50 -0
  78. package/dist/chunk-qvbwsaay.js +1 -0
  79. package/dist/chunk-r2pbqcnz.js +2 -0
  80. package/dist/chunk-r6110zv2.js +1 -0
  81. package/dist/chunk-rr1yaj55.js +2 -0
  82. package/dist/chunk-wcrj06cg.js +44 -0
  83. package/dist/chunk-wte9mh18.js +92 -0
  84. package/dist/{chunk-aw0cgv5w.js → chunk-y1dh3znq.js} +52 -52
  85. package/dist/chunk-y6e86wjs.js +445 -0
  86. package/dist/chunk-y8b7ht4v.js +1 -0
  87. package/dist/chunk-yf487g6e.js +2 -0
  88. package/dist/chunk-zmmc9j5f.js +2 -0
  89. package/dist/deploy/index.js +1 -1
  90. package/dist/dns/index.js +1 -1
  91. package/dist/drivers/index.js +1 -1
  92. package/dist/index.d.ts +1 -0
  93. package/dist/index.js +91 -91
  94. package/dist/operations/drained-sites.d.ts +56 -0
  95. package/dist/operations/drained-sites.test.d.ts +1 -0
  96. package/dist/pages/cloudflare-pages.d.ts +240 -0
  97. package/dist/pages/cloudflare-pages.test.d.ts +1 -0
  98. package/dist/pages/index.d.ts +2 -0
  99. package/dist/protection/index.js +1 -1
  100. package/dist/push/index.js +1 -1
  101. package/dist/spend/index.js +1 -1
  102. package/dist/ui/404.html +1 -1
  103. package/dist/ui/accept-invitation.html +1 -1
  104. package/dist/ui/access-denied.html +1 -1
  105. package/dist/ui/account/automation.html +6 -6
  106. package/dist/ui/account/security.html +2 -2
  107. package/dist/ui/applications/compose.html +6 -6
  108. package/dist/ui/applications/new.html +2 -2
  109. package/dist/ui/data/backups.html +80 -80
  110. package/dist/ui/data/services.html +78 -78
  111. package/dist/ui/data/volumes.html +50 -50
  112. package/dist/ui/index.html +50 -50
  113. package/dist/ui/infrastructure/topology.html +118 -118
  114. package/dist/ui/integrations.html +2 -2
  115. package/dist/ui/operations/alerts.html +48 -48
  116. package/dist/ui/operations/configuration.html +6 -6
  117. package/dist/ui/operations/jobs.html +75 -75
  118. package/dist/ui/operations/maintenance.html +6 -6
  119. package/dist/ui/operations/observability.html +82 -82
  120. package/dist/ui/operations/previews.html +6 -6
  121. package/dist/ui/operations/queue.html +6 -6
  122. package/dist/ui/operations/regions.html +6 -6
  123. package/dist/ui/operations/releases.html +6 -6
  124. package/dist/ui/operations/spend.html +54 -54
  125. package/dist/ui/operations/workloads.html +104 -104
  126. package/dist/ui/security.html +2 -2
  127. package/dist/ui/server/actions.html +56 -56
  128. package/dist/ui/server/activity.html +2 -2
  129. package/dist/ui/server/capacity.html +6 -6
  130. package/dist/ui/server/database.html +105 -105
  131. package/dist/ui/server/deployments.html +50 -50
  132. package/dist/ui/server/diagnostics.html +2 -2
  133. package/dist/ui/server/firewall.html +76 -76
  134. package/dist/ui/server/fleet.html +34 -34
  135. package/dist/ui/server/logs.html +24 -24
  136. package/dist/ui/server/metrics.html +112 -112
  137. package/dist/ui/server/security.html +1 -1
  138. package/dist/ui/server/services.html +26 -26
  139. package/dist/ui/server/sites.html +120 -120
  140. package/dist/ui/server/ssh-keys.html +52 -52
  141. package/dist/ui/server/team.html +144 -144
  142. package/dist/ui/server/terminal.html +15 -15
  143. package/dist/ui/serverless/alarms.html +52 -52
  144. package/dist/ui/serverless/assets.html +27 -27
  145. package/dist/ui/serverless/cost.html +2 -2
  146. package/dist/ui/serverless/data.html +35 -35
  147. package/dist/ui/serverless/deployments.html +27 -27
  148. package/dist/ui/serverless/firewall.html +2 -2
  149. package/dist/ui/serverless/functions.html +40 -40
  150. package/dist/ui/serverless/logs.html +24 -24
  151. package/dist/ui/serverless/metrics.html +2 -2
  152. package/dist/ui/serverless/queues.html +48 -48
  153. package/dist/ui/serverless/secrets.html +52 -52
  154. package/dist/ui/serverless/traces.html +6 -6
  155. package/dist/ui/serverless.html +53 -53
  156. package/dist/ui-src/src/charts.ts +8721 -13558
  157. package/dist/ui-src/src/topology.ts +2 -2
  158. package/package.json +4 -3
  159. package/dist/bin/chunk-0zwknfwp.js +0 -1
  160. package/dist/bin/chunk-3aph4c1w.js +0 -2
  161. package/dist/bin/chunk-4xhj37nj.js +0 -37
  162. package/dist/bin/chunk-5nkqza92.js +0 -1
  163. package/dist/bin/chunk-5nsqz5n3.js +0 -585
  164. package/dist/bin/chunk-64vczwwt.js +0 -1
  165. package/dist/bin/chunk-6tfwm33r.js +0 -6
  166. package/dist/bin/chunk-7g2ahkse.js +0 -1
  167. package/dist/bin/chunk-7zhgmp1s.js +0 -3
  168. package/dist/bin/chunk-82mj52xr.js +0 -141
  169. package/dist/bin/chunk-8khgprf6.js +0 -44
  170. package/dist/bin/chunk-9a88fp00.js +0 -2
  171. package/dist/bin/chunk-a7w13qfm.js +0 -2
  172. package/dist/bin/chunk-b4wt9jcg.js +0 -60
  173. package/dist/bin/chunk-btsyjhk7.js +0 -92
  174. package/dist/bin/chunk-c0bdafbx.js +0 -2
  175. package/dist/bin/chunk-cbsys5v8.js +0 -111
  176. package/dist/bin/chunk-cd0ps58j.js +0 -1
  177. package/dist/bin/chunk-d7ke90zt.js +0 -2
  178. package/dist/bin/chunk-djg4zyqk.js +0 -1
  179. package/dist/bin/chunk-dkaz333b.js +0 -1
  180. package/dist/bin/chunk-dkf4qsp2.js +0 -1
  181. package/dist/bin/chunk-e2bybahr.js +0 -3
  182. package/dist/bin/chunk-e5ab5twy.js +0 -50
  183. package/dist/bin/chunk-edvvx3hg.js +0 -1
  184. package/dist/bin/chunk-ehc63fvs.js +0 -2
  185. package/dist/bin/chunk-f06c5np9.js +0 -1
  186. package/dist/bin/chunk-g0fm1xcs.js +0 -1
  187. package/dist/bin/chunk-gq8794k6.js +0 -1
  188. package/dist/bin/chunk-hq9x489e.js +0 -70
  189. package/dist/bin/chunk-j447p8t4.js +0 -512
  190. package/dist/bin/chunk-ja1vjdn1.js +0 -6
  191. package/dist/bin/chunk-k3120rx6.js +0 -1
  192. package/dist/bin/chunk-kg61p5hw.js +0 -3
  193. package/dist/bin/chunk-mcr0r4at.js +0 -2
  194. package/dist/bin/chunk-mfrf9q4b.js +0 -2
  195. package/dist/bin/chunk-my3ewh3a.js +0 -34
  196. package/dist/bin/chunk-nw3d4k52.js +0 -1
  197. package/dist/bin/chunk-p70bc9yr.js +0 -1
  198. package/dist/bin/chunk-r6b3pq31.js +0 -4
  199. package/dist/bin/chunk-s4yzes15.js +0 -2
  200. package/dist/bin/chunk-sj5csg49.js +0 -2
  201. package/dist/bin/chunk-tvz9c388.js +0 -1
  202. package/dist/bin/chunk-wkx799z2.js +0 -1
  203. package/dist/bin/chunk-x6f61g36.js +0 -9
  204. package/dist/bin/chunk-xhwqpgwq.js +0 -2
  205. package/dist/bin/chunk-xk08030d.js +0 -6
  206. package/dist/bin/chunk-y1h63vpm.js +0 -1
  207. package/dist/bin/chunk-yw6f160x.js +0 -1
  208. package/dist/bin/chunk-zdt2rjk6.js +0 -1
  209. package/dist/bin/chunk-zh2d4704.js +0 -1
  210. package/dist/bin/chunk-znnawt0k.js +0 -1
  211. package/dist/bin/chunk-zpe64t4r.js +0 -1
  212. package/dist/bin/chunk-zsf6pccz.js +0 -1
  213. package/dist/chunk-1qdne0bf.js +0 -1
  214. package/dist/chunk-5vt93kxx.js +0 -1
  215. package/dist/chunk-73ztr55z.js +0 -2
  216. package/dist/chunk-95e6aeqz.js +0 -1
  217. package/dist/chunk-aj025v2s.js +0 -4
  218. package/dist/chunk-aw0spg20.js +0 -445
  219. package/dist/chunk-by2bwzk6.js +0 -141
  220. package/dist/chunk-dr4pj8hp.js +0 -5
  221. package/dist/chunk-hn40z11p.js +0 -37
  222. package/dist/chunk-kasdm9tx.js +0 -34
  223. package/dist/chunk-mz0dk78z.js +0 -6
  224. package/dist/chunk-nk7sav4r.js +0 -92
  225. package/dist/chunk-p10xt3jb.js +0 -1
  226. package/dist/chunk-q0rc1ax9.js +0 -114
  227. package/dist/chunk-q9q6cmt0.js +0 -1
  228. package/dist/chunk-rd38qdnf.js +0 -1
  229. package/dist/chunk-tz9myq9a.js +0 -2
  230. package/dist/chunk-wavjkdb8.js +0 -2
  231. package/dist/chunk-x3hay61c.js +0 -44
  232. package/dist/chunk-xcj8zfmg.js +0 -2
  233. package/dist/chunk-y4xkj2f1.js +0 -50
  234. package/dist/chunk-ywjkyg8p.js +0 -704
  235. package/dist/chunk-z2qqwy7e.js +0 -2
  236. package/dist/chunk-zam6ecam.js +0 -60
@@ -1,141 +0,0 @@
1
- import{$h as T}from"./chunk-mz0dk78z.js";class A{client;constructor(e,i){this.client=i??new T(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let n=t[i]??t.Item;if(n===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(n)?n:[n]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([n,s])=>!/^[A-Za-z0-9-]{1,64}$/.test(n)||!s||s.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),u=o.find((f)=>String(f.Id)===t.id),c=a.find((f)=>String(f.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${u.DomainName}; pass replaceExisting only after reviewing the live config`);if(c&&String(c.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${c.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let g={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([f,I])=>({HeaderName:f,HeaderValue:I}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},m=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],d={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:m.length,Items:{Method:m},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},h=u?o.map((f)=>String(f.Id)===t.id?g:f):[...o,g],l=c?a.map((f)=>String(f.PathPattern)===t.pathPattern?d:f):[...a,d],y=JSON.stringify(o)!==JSON.stringify(h)||JSON.stringify(a)!==JSON.stringify(l);if(!y||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:y,applied:!1,etag:s};r.Origins={Quantity:h.length,Items:{Origin:h}},r.CacheBehaviors={Quantity:l.length,...l.length?{Items:{CacheBehavior:l}}:{}};let C=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:C.ETag||C.headers?.etag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),u=o.find((l)=>String(l.Id)===t.id),c=a.find((l)=>String(l.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(c&&String(c.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!c)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:s};let g=a.filter((l)=>String(l.PathPattern)!==t.pathPattern),m=String(r.DefaultCacheBehavior?.TargetOriginId)===t.id||g.some((l)=>String(l.TargetOriginId)===t.id),d=m?o:o.filter((l)=>String(l.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!m&&!!u,etag:s};r.Origins={Quantity:d.length,Items:{Origin:d}},r.CacheBehaviors={Quantity:g.length,...g.length?{Items:{CacheBehavior:g}}:{}};let h=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!m&&!!u,etag:h.ETag||h.headers?.etag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
2
- <InvalidationBatch>
3
- <Paths>
4
- <Quantity>${e.paths.length}</Quantity>
5
- <Items>
6
- ${e.paths.map((s)=>`<Path>${s}</Path>`).join(`
7
- `)}
8
- </Items>
9
- </Paths>
10
- <CallerReference>${i}</CallerReference>
11
- </InvalidationBatch>`,n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${e.distributionId}/invalidation`,body:t,headers:{"Content-Type":"application/xml"}});return{Id:n.Id||n.Invalidation?.Id,Status:n.Status||n.Invalidation?.Status||"InProgress",CreateTime:n.CreateTime||n.Invalidation?.CreateTime||new Date().toISOString()}}async getInvalidation(e,i){let t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/invalidation/${i}`});return{Id:t.Id||t.Invalidation?.Id,Status:t.Status||t.Invalidation?.Status,CreateTime:t.CreateTime||t.Invalidation?.CreateTime}}async listInvalidations(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/invalidation`}),t=[];if(i.InvalidationSummary){let n=Array.isArray(i.InvalidationSummary)?i.InvalidationSummary:[i.InvalidationSummary];t.push(...n.map((s)=>({Id:s.Id,Status:s.Status,CreateTime:s.CreateTime})))}return t}async waitForInvalidation(e,i){let n=0;while(n<60){if((await this.getInvalidation(e,i)).Status==="Completed")return;await new Promise((r)=>setTimeout(r,5000)),n++}throw Error(`Timeout waiting for invalidation ${i} to complete`)}async listDistributions(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/distribution"}),i=[],n=(e.DistributionList||e).Items,s=[];if(Array.isArray(n))s=n;else if(n?.DistributionSummary)s=Array.isArray(n.DistributionSummary)?n.DistributionSummary:[n.DistributionSummary];return i.push(...s.map((r)=>({Id:r.Id,ARN:r.ARN,Status:r.Status,DomainName:r.DomainName,Aliases:r.Aliases||void 0,Enabled:r.Enabled==="true"||r.Enabled===!0}))),i}async getDistribution(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}`}),t=i.Distribution||i;return{Id:t.Id,ARN:t.ARN,Status:t.Status,DomainName:t.DomainName,Aliases:t.DistributionConfig?.Aliases?.Items||t.Aliases?.Items||[],Enabled:t.DistributionConfig?.Enabled==="true"||t.DistributionConfig?.Enabled===!0}}async getDistributionConfig(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`});return{ETag:i.ETag||"",DistributionConfig:i.DistributionConfig||i}}async invalidateAll(e){return this.createInvalidation({distributionId:e,paths:["/*"]})}async invalidatePaths(e,i){let t=i.map((n)=>n.startsWith("/")?n:`/${n}`);return this.createInvalidation({distributionId:e,paths:t})}async invalidatePattern(e,i){let t=i.startsWith("/")?i:`/${i}`;return this.createInvalidation({distributionId:e,paths:[t]})}async invalidateAfterDeployment(e){let{distributionId:i,changedPaths:t,invalidateAll:n=!1,wait:s=!1}=e,r;if(n||!t||t.length===0)r=await this.invalidateAll(i);else r=await this.invalidatePaths(i,t);if(s)await this.waitForInvalidation(i,r.Id);return{invalidationId:r.Id,status:r.Status}}async findDistributionByDomain(e){return(await this.listDistributions()).find((n)=>{if(n.DomainName===e)return!0;if(n.Aliases?.Items&&n.Aliases.Items.includes(e))return!0;return!1})||null}async batchInvalidate(e,i=["/*"]){return await Promise.all(e.map(async(n)=>{let s=await this.createInvalidation({distributionId:n,paths:i});return{distributionId:n,invalidationId:s.Id,status:s.Status}}))}async updateCustomErrorResponses(e){let{distributionId:i,customErrorResponses:t}=e,n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${i}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||"",r=n.body?.DistributionConfig||(n.body?.Enabled!==void 0?n.body:void 0)||n.DistributionConfig;if(!r||r.Enabled===void 0)throw Error("Failed to get current distribution config");if(t.length===0)r.CustomErrorResponses={Quantity:0};else r.CustomErrorResponses={Quantity:t.length,Items:{CustomErrorResponse:t.map((c)=>({ErrorCode:c.errorCode,...c.responsePagePath&&{ResponsePagePath:c.responsePagePath},...c.responseCode&&{ResponseCode:c.responseCode},...c.errorCachingMinTTL!==void 0&&{ErrorCachingMinTTL:c.errorCachingMinTTL}}))}};let o=this.buildDistributionConfigXml(r),a=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${i}/config`,body:o,headers:{"Content-Type":"application/xml","If-Match":s}}),u=a.Distribution||a;return{Distribution:{Id:u.Id,ARN:u.ARN,Status:u.Status,DomainName:u.DomainName,Aliases:u.DistributionConfig?.Aliases?.Items||[],Enabled:u.DistributionConfig?.Enabled==="true"||u.DistributionConfig?.Enabled===!0},ETag:a.ETag||""}}async removeCustomErrorResponses(e){return this.updateCustomErrorResponses({distributionId:e,customErrorResponses:[]})}async updateDistribution(e){let{distributionId:i,aliases:t,certificateArn:n,comment:s}=e,r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${i}/config`,returnHeaders:!0}),o=r.headers?.etag||r.headers?.ETag||"",a=r.body?.DistributionConfig||(r.body?.Enabled!==void 0?r.body:void 0)||r.DistributionConfig;if(!a||a.Enabled===void 0)throw Error("Failed to get current distribution config");if(t&&t.length>0)a.Aliases={Quantity:t.length,Items:{Item:t}};if(n)a.ViewerCertificate={ACMCertificateArn:n,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CertificateSource:"acm"};if(s)a.Comment=s;let u=this.buildDistributionConfigXml(a),c=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${i}/config`,body:u,headers:{"Content-Type":"application/xml","If-Match":o}}),g=c.Distribution||c;return{Distribution:{Id:g.Id,ARN:g.ARN,Status:g.Status,DomainName:g.DomainName,Aliases:t?{Quantity:t.length,Items:t}:{Quantity:0,Items:[]},Enabled:g.DistributionConfig?.Enabled==="true"||g.DistributionConfig?.Enabled===!0},ETag:c.ETag||""}}buildDistributionConfigXml(e){let i=(r)=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),t={Items:"",Methods:"Method",Headers:"Name",Cookies:"Name",QueryStringCacheKeys:"Name",TrustedKeyGroups:"KeyGroup",TrustedSigners:"AwsAccountNumber",LambdaFunctionAssociations:"LambdaFunctionAssociation",FunctionAssociations:"FunctionAssociation",CacheBehaviors:"CacheBehavior",CustomErrorResponses:"CustomErrorResponse",GeoRestriction:"Location"},n={Origins:"Origin",Aliases:"CNAME",AllowedMethods:"Method",CachedMethods:"Method",CustomErrorResponses:"CustomErrorResponse",CacheBehaviors:"CacheBehavior"},s=(r,o,a="",u="")=>{if(o===null||o===void 0)return"";if(r.startsWith("@_")||r==="?xml")return"";if(typeof o==="boolean")return`${a}<${r}>${o}</${r}>
12
- `;if(typeof o==="number"||typeof o==="string")return`${a}<${r}>${i(String(o))}</${r}>
13
- `;if(Array.isArray(o)){let c=t[r]||r.replace(/s$/,"");return o.map((g)=>s(c,g,a,r)).join("")}if(typeof o==="object"){if(r==="Items"){let g=n[u]||"",m=Object.keys(o).filter((d)=>!d.startsWith("@_"));if(m.length===1&&!Array.isArray(o[m[0]])){let d=m[0],h=o[d];if(typeof h==="string")return`${a}<Items>
14
- ${a} <${d}>${i(h)}</${d}>
15
- ${a}</Items>
16
- `;else if(typeof h==="object"&&!Array.isArray(h))return`${a}<Items>
17
- ${s(d,h,a+" ",r)}${a}</Items>
18
- `}if(m.length===1&&Array.isArray(o[m[0]])){let d=m[0],h=o[d],l="";for(let y of h)if(typeof y==="string")l+=`${a} <${d}>${i(y)}</${d}>
19
- `;else l+=s(d,y,a+" ",r);return`${a}<Items>
20
- ${l}${a}</Items>
21
- `}if(Array.isArray(o)){let d="",h=g||"Item";for(let l of o)if(typeof l==="string")d+=`${a} <${h}>${i(l)}</${h}>
22
- `;else d+=s(h,l,a+" ",r);return`${a}<Items>
23
- ${d}${a}</Items>
24
- `}}let c="";for(let[g,m]of Object.entries(o))if(!g.startsWith("@_"))c+=s(g,m,a+" ",r);if(c==="")return`${a}<${r}/>
25
- `;return`${a}<${r}>
26
- ${c}${a}</${r}>
27
- `}return""};return`<?xml version="1.0" encoding="UTF-8"?>
28
- <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
29
- ${Object.entries(e).filter(([r])=>!r.startsWith("@_")).map(([r,o])=>s(r,o," ","DistributionConfig")).join("")}</DistributionConfig>`}async ensureDynamicHttpMethods(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),t=i.headers?.etag||i.headers?.ETag||"",n=i.body?.DistributionConfig||i.DistributionConfig||i.body;if(!n)throw Error("Failed to get current distribution config");let s=!1,r=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],o=(c)=>{if(!c)return[];let g=c.Items;if(!g)return[];if(Array.isArray(g))return g.map(String);if(typeof g==="object"&&g.Method){let m=g.Method;return Array.isArray(m)?m.map(String):[String(m)]}if(g.Item)return Array.isArray(g.Item)?g.Item.map(String):[String(g.Item)];return[]},a=n.DefaultCacheBehavior;if(a){if(!o(a.AllowedMethods).includes("POST"))a.AllowedMethods={Quantity:r.length,Items:{Method:r},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},s=!0}if(!s)return!1;let u=this.buildDistributionConfigXml(n);return await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:u,headers:{"Content-Type":"application/xml","If-Match":t}}),!0}async addAliases(e,i,t){return this.updateDistribution({distributionId:e,aliases:i,certificateArn:t})}async createFunction(e){let{name:i,code:t,comment:n="",runtime:s="cloudfront-js-2.0"}=e,r=`<?xml version="1.0" encoding="UTF-8"?>
30
- <CreateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
31
- <Name>${i}</Name>
32
- <FunctionConfig>
33
- <Comment>${n}</Comment>
34
- <Runtime>${s}</Runtime>
35
- </FunctionConfig>
36
- <FunctionCode>${Buffer.from(t).toString("base64")}</FunctionCode>
37
- </CreateFunctionRequest>`,o=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/function",body:r,headers:{"Content-Type":"application/xml"}}),a=o.FunctionSummary||o;return{FunctionARN:a.FunctionMetadata?.FunctionARN||a.FunctionARN,Name:a.Name||i,Stage:a.FunctionMetadata?.Stage||"DEVELOPMENT",ETag:o.ETag||""}}async listFunctions(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/function"}),i=[],t=e.FunctionList?.Items?.FunctionSummary;if(t){let n=Array.isArray(t)?t:[t];for(let s of n)i.push({Name:s.Name,FunctionARN:s.FunctionMetadata?.FunctionARN,Stage:s.FunctionMetadata?.Stage,CreatedTime:s.FunctionMetadata?.CreatedTime,LastModifiedTime:s.FunctionMetadata?.LastModifiedTime})}return i}async getFunction(e,i="LIVE"){try{let t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${e}`,queryParams:{Stage:i},returnHeaders:!0}),n=t.body?.FunctionSummary||t.FunctionSummary||t.body||t;return{FunctionARN:n.FunctionMetadata?.FunctionARN,Name:n.Name||e,Stage:n.FunctionMetadata?.Stage||i,ETag:t.headers?.etag||t.ETag||"",FunctionCode:n.FunctionCode}}catch(t){if(t.message?.includes("404")||t.message?.includes("NoSuchFunctionExists"))return null;throw t}}async publishFunction(e,i){let t,n;if(typeof e==="object")t=e.Name,n=e.IfMatch;else t=e,n=i;if(!n){let o=await this.getFunction(t,"DEVELOPMENT");if(!o)throw Error(`Function ${t} not found`);n=o.ETag}let s=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/function/${t}/publish`,headers:{"If-Match":n}}),r=s.FunctionSummary||s;return{FunctionARN:r.FunctionMetadata?.FunctionARN,Stage:r.FunctionMetadata?.Stage||"LIVE",FunctionSummary:r}}async describeFunction(e){let{Name:i,Stage:t="DEVELOPMENT"}=e,n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${i}/describe`,queryParams:{Stage:t},returnHeaders:!0});return{ETag:n.headers?.etag||n.ETag||"",FunctionSummary:n.body?.FunctionSummary||n.FunctionSummary||n.body||n}}async updateFunction(e){let{Name:i,FunctionCode:t,FunctionConfig:n,IfMatch:s}=e,r=`<?xml version="1.0" encoding="UTF-8"?>
38
- <UpdateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
39
- <FunctionConfig>
40
- <Comment>${n.Comment}</Comment>
41
- <Runtime>${n.Runtime}</Runtime>
42
- </FunctionConfig>
43
- <FunctionCode>${Buffer.from(t).toString("base64")}</FunctionCode>
44
- </UpdateFunctionRequest>`,o=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/function/${i}`,body:r,headers:{"Content-Type":"application/xml","If-Match":s},returnHeaders:!0});return{ETag:o.headers?.etag||o.ETag||"",FunctionSummary:o.body?.FunctionSummary||o.FunctionSummary||o.body||o}}async deleteFunction(e,i){let t=i;if(!t){let n=await this.getFunction(e,"DEVELOPMENT");if(!n)return;t=n.ETag}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/function/${e}`,headers:{"If-Match":t}})}async createIndexRewriteFunction(e){return this.createFunction({name:e,code:`function handler(event) {
45
- const request = event.request;
46
- var uri = request.uri;
47
-
48
- // Check if the request is for a directory (ends with /)
49
- if (uri.endsWith('/')) {
50
- request.uri += 'index.html';
51
- }
52
- // Check if the request doesn't have a file extension
53
- else if (!uri.includes('.')) {
54
- // Add trailing slash to redirect to directory
55
- request.uri += '/index.html';
56
- }
57
-
58
- return request;
59
- }`,comment:"Rewrite directory requests to index.html for S3 static sites",runtime:"cloudfront-js-2.0"})}async listOriginAccessControls(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/origin-access-control"}),i=[];if(e.OriginAccessControlList?.Items?.OriginAccessControlSummary){let t=Array.isArray(e.OriginAccessControlList.Items.OriginAccessControlSummary)?e.OriginAccessControlList.Items.OriginAccessControlSummary:[e.OriginAccessControlList.Items.OriginAccessControlSummary];i.push(...t.map((n)=>({Id:n.Id,Name:n.Name,Description:n.Description,SigningProtocol:n.SigningProtocol,SigningBehavior:n.SigningBehavior,OriginAccessControlOriginType:n.OriginAccessControlOriginType})))}return i}async createOriginAccessControl(e){let{name:i,description:t=`OAC for ${i}`,signingProtocol:n="sigv4",signingBehavior:s="always",originType:r="s3"}=e,o=`<?xml version="1.0" encoding="UTF-8"?>
60
- <OriginAccessControlConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
61
- <Name>${i}</Name>
62
- <Description>${t}</Description>
63
- <SigningProtocol>${n}</SigningProtocol>
64
- <SigningBehavior>${s}</SigningBehavior>
65
- <OriginAccessControlOriginType>${r}</OriginAccessControlOriginType>
66
- </OriginAccessControlConfig>`,a=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/origin-access-control",body:o,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),u=a.body?.OriginAccessControl||a.OriginAccessControl||a.body||a;return{Id:u.Id,Name:u.OriginAccessControlConfig?.Name||i,Description:u.OriginAccessControlConfig?.Description||t,SigningProtocol:u.OriginAccessControlConfig?.SigningProtocol||n,SigningBehavior:u.OriginAccessControlConfig?.SigningBehavior||s,OriginAccessControlOriginType:u.OriginAccessControlConfig?.OriginAccessControlOriginType||r,ETag:a.headers?.etag||a.ETag||""}}async findOrCreateOriginAccessControl(e,i="s3"){let n=(await this.listOriginAccessControls()).find((r)=>r.Name===e&&r.OriginAccessControlOriginType===i);if(n)return{Id:n.Id,Name:n.Name,isNew:!1};let s=await this.createOriginAccessControl({name:e,originType:i});return{Id:s.Id,Name:s.Name,isNew:!0}}async createDistributionForS3(e){let{bucketName:i,bucketRegion:t,originAccessControlId:n,aliases:s=[],certificateArn:r,defaultRootObject:o="index.html",comment:a=`Distribution for ${i}`,priceClass:u="PriceClass_100",enabled:c=!0,trustedKeyGroupIds:g=[],mediaDelivery:m=!1}=e,d=`S3-${i}`,h=`${i}.s3.${t}.amazonaws.com`,l=`${Date.now()}-${Math.random().toString(36).slice(2)}`,y=g.length>0?`<TrustedKeyGroups>
67
- <Enabled>true</Enabled>
68
- <Quantity>${g.length}</Quantity>
69
- <Items>${g.map((E)=>`<KeyGroup>${E}</KeyGroup>`).join("")}</Items>
70
- </TrustedKeyGroups>`:"<TrustedKeyGroups><Enabled>false</Enabled><Quantity>0</Quantity></TrustedKeyGroups>",C="<Aliases><Quantity>0</Quantity></Aliases>";if(s.length>0)C=`<Aliases>
71
- <Quantity>${s.length}</Quantity>
72
- <Items>
73
- ${s.map((E)=>`<CNAME>${E}</CNAME>`).join(`
74
- `)}
75
- </Items>
76
- </Aliases>`;let f=`<ViewerCertificate>
77
- <CloudFrontDefaultCertificate>true</CloudFrontDefaultCertificate>
78
- </ViewerCertificate>`;if(r&&s.length>0)f=`<ViewerCertificate>
79
- <ACMCertificateArn>${r}</ACMCertificateArn>
80
- <SSLSupportMethod>sni-only</SSLSupportMethod>
81
- <MinimumProtocolVersion>TLSv1.2_2021</MinimumProtocolVersion>
82
- <CertificateSource>acm</CertificateSource>
83
- </ViewerCertificate>`;let I=`<?xml version="1.0" encoding="UTF-8"?>
84
- <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
85
- <CallerReference>${l}</CallerReference>
86
- <Comment>${a}</Comment>
87
- <DefaultRootObject>${o}</DefaultRootObject>
88
- <Origins>
89
- <Quantity>1</Quantity>
90
- <Items>
91
- <Origin>
92
- <Id>${d}</Id>
93
- <DomainName>${h}</DomainName>
94
- <OriginPath></OriginPath>
95
- <S3OriginConfig>
96
- <OriginAccessIdentity></OriginAccessIdentity>
97
- </S3OriginConfig>
98
- <OriginAccessControlId>${n}</OriginAccessControlId>
99
- </Origin>
100
- </Items>
101
- </Origins>
102
- <DefaultCacheBehavior>
103
- <TargetOriginId>${d}</TargetOriginId>
104
- <ViewerProtocolPolicy>redirect-to-https</ViewerProtocolPolicy>
105
- <AllowedMethods>
106
- <Quantity>2</Quantity>
107
- <Items>
108
- <Method>GET</Method>
109
- <Method>HEAD</Method>
110
- </Items>
111
- <CachedMethods>
112
- <Quantity>2</Quantity>
113
- <Items>
114
- <Method>GET</Method>
115
- <Method>HEAD</Method>
116
- </Items>
117
- </CachedMethods>
118
- </AllowedMethods>
119
- <Compress>true</Compress>
120
- <CachePolicyId>658327ea-f89d-4fab-a63d-7e88639e58f6</CachePolicyId>
121
- ${y}
122
- </DefaultCacheBehavior>
123
- ${C}
124
- ${f}
125
- <PriceClass>${u}</PriceClass>
126
- <Enabled>${c}</Enabled>
127
- <HttpVersion>http2and3</HttpVersion>
128
- <IsIPV6Enabled>true</IsIPV6Enabled>
129
- ${m?"<CustomErrorResponses><Quantity>0</Quantity></CustomErrorResponses>":`<CustomErrorResponses>
130
- <Quantity>1</Quantity>
131
- <Items>
132
- <CustomErrorResponse>
133
- <ErrorCode>403</ErrorCode>
134
- <ResponsePagePath>/index.html</ResponsePagePath>
135
- <ResponseCode>200</ResponseCode>
136
- <ErrorCachingMinTTL>300</ErrorCachingMinTTL>
137
- </CustomErrorResponse>
138
- </Items>
139
- </CustomErrorResponses>`}
140
- </DistributionConfig>`,p=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/distribution",body:I,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),b=p.body?.Distribution||p.Distribution||p.body||p;return{Id:b.Id,ARN:b.ARN,DomainName:b.DomainName,Status:b.Status,ETag:p.headers?.etag||p.ETag||""}}async createMediaDistributionForS3(e){return this.createDistributionForS3({...e,defaultRootObject:"",mediaDelivery:!0,comment:e.comment??`Media distribution for ${e.bucketName}`})}async listPublicKeys(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/public-key"});return this.collectionItems(e.PublicKeyList??e,"PublicKeySummary").map((t)=>({Id:String(t.Id),Name:String(t.Name),Comment:t.Comment?String(t.Comment):void 0}))}async createPublicKey(e){if(!/^[A-Za-z0-9_-]{1,128}$/.test(e.name))throw TypeError("CloudFront public key name is invalid");if(!e.encodedKey.includes("BEGIN PUBLIC KEY"))throw TypeError("CloudFront public key must be PEM encoded");let i=(s)=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/public-key",headers:{"Content-Type":"application/xml"},body:`<PublicKeyConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><CallerReference>${i(e.callerReference??`${Date.now()}-${e.name}`)}</CallerReference><Name>${i(e.name)}</Name><EncodedKey>${i(e.encodedKey)}</EncodedKey><Comment>${i(e.comment??"")}</Comment></PublicKeyConfig>`}),n=t.PublicKey??t;return{Id:String(n.Id),Name:String(n.PublicKeyConfig?.Name??e.name),EncodedKey:String(n.PublicKeyConfig?.EncodedKey??e.encodedKey),Comment:String(n.PublicKeyConfig?.Comment??e.comment??"")}}async listKeyGroups(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/key-group"});return this.collectionItems(e.KeyGroupList??e,"KeyGroupSummary").map((t)=>({Id:String(t.KeyGroup?.Id??t.Id),Name:String(t.KeyGroup?.KeyGroupConfig?.Name??t.KeyGroupConfig?.Name??t.Name),Items:this.collectionItems(t.KeyGroup?.KeyGroupConfig?.Items??t.KeyGroupConfig?.Items??t.Items,"Item").map(String),Comment:t.KeyGroup?.KeyGroupConfig?.Comment??t.KeyGroupConfig?.Comment??t.Comment}))}async createKeyGroup(e){if(!/^[A-Za-z0-9_-]{1,128}$/.test(e.name))throw TypeError("CloudFront key group name is invalid");let i=[...new Set(e.publicKeyIds)];if(i.length===0)throw TypeError("CloudFront key group requires at least one public key");let t=(o)=>o.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),n=i.map((o)=>`<Item>${t(o)}</Item>`).join(""),s=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/key-group",headers:{"Content-Type":"application/xml"},body:`<KeyGroupConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><Name>${t(e.name)}</Name><Items>${n}</Items><Comment>${t(e.comment??"")}</Comment></KeyGroupConfig>`}),r=s.KeyGroup??s;return{Id:String(r.Id),Name:String(r.KeyGroupConfig?.Name??e.name),Items:i,Comment:String(r.KeyGroupConfig?.Comment??e.comment??"")}}static getS3BucketPolicyForCloudFront(e,i){return{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${e}/*`,Condition:{StringEquals:{"AWS:SourceArn":i}}}]}}async waitForDistributionDeployed(e,i=60){for(let t=0;t<i;t++){if((await this.getDistribution(e)).Status==="Deployed")return!0;await new Promise((s)=>setTimeout(s,30000))}return!1}async disableDistribution(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),t=i.headers?.etag||i.headers?.ETag||"",n=i.body?.DistributionConfig||(i.body?.Enabled!==void 0?i.body:void 0)||i.DistributionConfig;if(!n||n.Enabled===void 0)throw Error("Failed to get current distribution config");n.Enabled=!1;let s=this.buildDistributionConfigXml(n),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:s,headers:{"Content-Type":"application/xml","If-Match":t},returnHeaders:!0});return{ETag:r.headers?.etag||r.headers?.ETag||r.ETag||""}}async deleteDistribution(e,i){let t=i||"";if(!t){let n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}`,returnHeaders:!0});t=n.headers?.etag||n.headers?.ETag||""}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/distribution/${e}`,headers:{"If-Match":t}})}async waitForDistributionDisabled(e,i=60){for(let t=0;t<i;t++){let n=await this.getDistribution(e);if(n.Status==="Deployed"&&!n.Enabled)return!0;await new Promise((s)=>setTimeout(s,30000))}return!1}async removeAlias(e,i){let t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),n=t.headers?.etag||t.headers?.ETag||"",s=t.body?.DistributionConfig||(t.body?.Enabled!==void 0?t.body:void 0)||t.DistributionConfig;if(!s||s.Enabled===void 0)throw Error("Failed to get current distribution config");let r=[];if(s.Aliases?.Items){if(Array.isArray(s.Aliases.Items))r=s.Aliases.Items;else if(typeof s.Aliases.Items==="object"){let c=s.Aliases.Items.CNAME;if(typeof c==="string")r=[c];else if(Array.isArray(c))r=c}}if(r.length===0)throw Error("Distribution has no aliases to remove");let o=r.filter((c)=>c!==i);if(o.length===r.length)throw Error(`Alias ${i} not found in distribution`);if(s.Aliases.Quantity=o.length,s.Aliases.Items=o.length>0?o:void 0,o.length===0)s.ViewerCertificate={CloudFrontDefaultCertificate:!0,MinimumProtocolVersion:"TLSv1.2_2021"};let a=this.buildDistributionConfigXml(s),u=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:a,headers:{"Content-Type":"application/xml","If-Match":n},returnHeaders:!0});return{ETag:u.headers?.etag||u.headers?.ETag||u.ETag||""}}}
141
- export{A as sf};
@@ -1,5 +0,0 @@
1
- import{tf as L}from"./chunk-73ztr55z.js";import{Js as E,kt as T,pt as M,qt as U,xs as R,zs as P}from"./chunk-zz52xje8.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as I,mkdtempSync as q,rmSync as N,writeFileSync as d}from"node:fs";import{tmpdir as z}from"node:os";import{dirname as G,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 b(t,e){return`${r[e]}${t}${r.reset}`}function _(t){console.log(`${r.green}✓${r.reset} ${t}`)}function H(t){console.error(`${r.red}✗${r.reset} ${t}`)}function K(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function k(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function V(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function J(t){console.log(`
2
- ${r.bright}${r.cyan}${t}${r.reset}
3
- `)}var Q=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function X(t,e="cyan"){let n=t.split(`
4
- `),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(b(`┌${a}┐`,e)),n.forEach((l)=>{console.log(b(`│ ${l.padEnd(i)} │`,e))}),console.log(b(`└${a}┘`,e))}function A(t,e){for(let n of e){let i=s(t,n.name);I(G(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function ot(t){let{app:e,projectRoot:n,region:i,repository:a}=t,l=e.architecture??"x86_64",O=l==="arm64"?"linux/arm64":"linux/amd64",j=e.kind==="php",c=t.onStep??(()=>{}),p=q(s(z(),"tscloud-img-"));try{let f=s(p,"app");I(f,{recursive:!0});let y,w;if(j){M({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c}),c("staging application tree");let o=U(n);A(f,o),A(s(p,"runtime"),T().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=R(o.map((g)=>`${g.name}:${g.data.length}`).join("|"))}else{c("bundling application");let o=await P({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c});d(s(f,"index.mjs"),o.bundle),y=o.handlers,w=o.sha256}let S=w.slice(0,16);d(s(p,"Dockerfile"),E({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:l}));let v=new L(i),u;try{u=(await v.describeRepositories({repositoryNames:[a]})).repositories?.[0]?.repositoryUri??""}catch{u=""}if(!u)c(`creating ECR repository ${a}`),u=(await v.createRepository({repositoryName:a,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!u)throw Error(`could not resolve ECR repository URI for ${a}`);let m=`${u}:${S}`;c("docker build"),C("docker",["build","--platform",O,"--provenance=false","--sbom=false","-t",m,p],{stdio:"inherit"}),c("ecr auth + push");let h=(await v.getAuthorizationToken()).authorizationData?.[0];if(!h?.authorizationToken||!h.proxyEndpoint)throw Error("failed to get an ECR authorization token");let D=h.proxyEndpoint.replace(/^https?:\/\//,""),x=s(p,".docker");return I(x,{recursive:!0}),d(s(x,"config.json"),JSON.stringify({auths:{[D]:{auth:h.authorizationToken}}})),C("docker",["push",m],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:x}}),k(`Image: ${m}`),{imageUri:m,tag:S,handlers:y}}finally{N(p,{recursive:!0,force:!0})}}
5
- export{_ as Bd,H as Cd,K as Dd,k as Ed,V as Fd,J as Gd,X as Hd,ot as Id};
@@ -1,37 +0,0 @@
1
- var u={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},p={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function l(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function g(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 S(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 d=n.path?R(n.path):".*";if(!g(d)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let c=[`SecRule REQUEST_URI "@rx ${l(d)}"`];if(n.methods?.length)c.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${l(n.id)}'"`);else c.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${l(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${l(n.id)}".`),t.push(c.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${l(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function R(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function v(e={},r=[]){let t=e.mode??u.mode,o=[],s=e.paranoiaLevel??u.paranoiaLevel,n=e.inboundThreshold??u.inboundThreshold,d=e.outboundThreshold??u.outboundThreshold,c=e.maxBodyBytes??u.maxBodyBytes,m=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(!m)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
- `)}
3
- `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${c}`,`SecRequestBodyNoFilesLimit ${Math.min(c,131072)}`,`SecRequestBodyLimitAction ${m?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${l(e.auditLogPath??u.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??u.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=${d}"`,'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 f=p.bypassBase;for(let a of e.bypassPaths??[]){let x=R(a);if(!g(x)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${l(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${l(x)}" "id:${f},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),f++}let y=p.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(`# ${l(a.reason)}`),a.pathPattern){if(!g(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${l(a.pathPattern)}" "id:${y},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),y++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let h=S(r,p.rateLimitBase);if(h.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.",...h.lines);let b=p.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${b}.`,a.trim(),""),b++;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??u.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
4
- `)}
5
- `,unmappedRateLimits:h.unmapped,warnings:o,mode:t}}function I(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=v(e,r);return`#!/usr/bin/env bash
6
- # Managed by ts-cloud. Installs the zig-waf ruleset.
7
- set -euo pipefail
8
-
9
- if [ ! -x "${o}" ]; then
10
- echo "ts-cloud: ${o} is not installed; skipping WAF configuration" >&2
11
- exit 0
12
- fi
13
-
14
- install -d -m 0755 "$(dirname "${s}")"
15
- install -d -m 0750 /var/log/ts-cloud
16
-
17
- cat > "${s}.new" <<'WAF_EOF'
18
- ${n.config}WAF_EOF
19
-
20
- # Compile the config before it goes live. A config that does not validate
21
- # would leave the engine with no rules while still reporting itself enabled.
22
- if ! "${o}" validate "${s}.new"; then
23
- echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
24
- rm -f "${s}.new"
25
- exit 1
26
- fi
27
-
28
- if [ -f "${s}" ] && cmp -s "${s}.new" "${s}"; then
29
- rm -f "${s}.new"
30
- echo "ts-cloud: WAF config unchanged"
31
- exit 0
32
- fi
33
-
34
- mv "${s}.new" "${s}"
35
- echo "ts-cloud: WAF config installed (mode: ${n.mode})"
36
- `}function _(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{l as nl,g as ol,R as pl,v as ql,I as rl,_ as sl};
@@ -1,34 +0,0 @@
1
- import{Tf as P}from"./chunk-y4xkj2f1.js";import{Zh as A}from"./chunk-nk7sav4r.js";import{$h as d}from"./chunk-mz0dk78z.js";import{Ct as y}from"./chunk-z2qqwy7e.js";function I(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,c)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))s.push(`${a}.member.${c+1}.${u}=${encodeURIComponent(String(l))}`);else s.push(`${a}.member.${c+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,c]of Object.entries(i))if(c!==void 0&&c!==null)s.push(`${a}.${n}=${encodeURIComponent(String(c))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function o(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let n=[],c=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),u;while((u=c.exec(i[1]))!==null)n.push(u[1]);return n}class g{client;region;constructor(e="us-east-1",t){this.client=new d(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=I(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return o(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",n=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return o(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return o(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return o(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return o(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return o(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return o(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return o(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return o(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=o(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),n=r(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=o(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=o(e,"EvaluationResults","member").map((n)=>{let u=o(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:r(l,"SourcePolicyId"),SourcePolicyType:r(l,"SourcePolicyType")}));return{EvalActionName:r(n,"EvalActionName")||"",EvalResourceName:r(n,"EvalResourceName"),EvalDecision:r(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}class p{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new d(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,c)=>{s[`Destinations.member.${c+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class h{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new p(this.region),this.s3=new A(this.region),this.iam=new g(this.region),this.route53=new P(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-5vt93kxx.js"),a=new s,i=(m,S)=>{let f={Action:m,Version:"2010-05-08",...S};return Object.entries(f).map(([b,T])=>`${encodeURIComponent(b)}=${encodeURIComponent(T)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},c=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:c,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let R=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:R,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=y("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
- `,i+=`To: ${s.join(", ")}\r
3
- `,e.cc){let n=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${n.join(", ")}\r
4
- `}if(i+=`Subject: ${e.subject}\r
5
- `,i+=`MIME-Version: 1.0\r
6
- `,i+=`Content-Type: multipart/mixed; boundary="${a}"\r
7
- `,i+=`\r
8
- `,e.text||e.html)if(i+=`--${a}\r
9
- `,e.html&&e.text){let n=`----=_Alt_${Date.now()}`;i+=`Content-Type: multipart/alternative; boundary="${n}"\r
10
- `,i+=`\r
11
- `,i+=`--${n}\r
12
- `,i+=`Content-Type: text/plain; charset="UTF-8"\r
13
- `,i+=`\r
14
- `,i+=`${e.text}\r
15
- `,i+=`--${n}\r
16
- `,i+=`Content-Type: text/html; charset="UTF-8"\r
17
- `,i+=`\r
18
- `,i+=`${e.html}\r
19
- `,i+=`--${n}--\r
20
- `}else if(e.html)i+=`Content-Type: text/html; charset="UTF-8"\r
21
- `,i+=`\r
22
- `,i+=`${e.html}\r
23
- `;else i+=`Content-Type: text/plain; charset="UTF-8"\r
24
- `,i+=`\r
25
- `,i+=`${e.text}\r
26
- `;if(e.attachments)for(let n of e.attachments)i+=`--${a}\r
27
- `,i+=`Content-Type: ${n.contentType||"application/octet-stream"}; name="${n.filename}"\r
28
- `,i+=`Content-Transfer-Encoding: base64\r
29
- `,i+=`Content-Disposition: attachment; filename="${n.filename}"\r
30
- `,i+=`\r
31
- `,i+=`${n.content}\r
32
- `;return i+=`--${a}--\r
33
- `,i}}var M=new h;
34
- export{g as of,p as pf,h as qf,M as rf};
@@ -1,6 +0,0 @@
1
- import*as _ from"node:crypto";import{existsSync as V,readFileSync as Y}from"node:fs";import{homedir as W}from"node:os";import{join as B}from"node:path";var j={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},z={nbsp:" ",copy:"©",reg:"®",trade:"™",euro:"€",pound:"£",yen:"¥",cent:"¢",deg:"°",micro:"µ",middot:"·",bull:"•",hellip:"…",prime:"′",Prime:"″",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",ndash:"–",mdash:"—",iexcl:"¡",iquest:"¿",sect:"§",para:"¶",dagger:"†",Dagger:"‡",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",times:"×",divide:"÷",plusmn:"±",ne:"≠",le:"≤",ge:"≥",infin:"∞",fnof:"ƒ",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",equiv:"≡",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜"};class D{customEntities={};useHtmlEntities;constructor(t=!1){this.useHtmlEntities=t}addEntity(t,e){this.customEntities[t]=e}decodeEntities(t){let e=t.indexOf("&");if(e===-1)return t;let r=t.length,i="",s=0;while(e!==-1&&e<r){if(e>s)i+=t.substring(s,e);let n=t.indexOf(";",e+1);if(n===-1||n-e>32){i+="&",s=e+1,e=t.indexOf("&",s);continue}let a=t.substring(e+1,n);if(a.charCodeAt(0)===35){let o=a.length,d=0,p=!1;if(o>2&&(a.charCodeAt(1)===120||a.charCodeAt(1)===88)){p=!0;for(let g=2;g<o;g++){let h=a.charCodeAt(g);if(h>=48&&h<=57)d=d<<4|h-48;else if(h>=65&&h<=70)d=d<<4|h-55;else if(h>=97&&h<=102)d=d<<4|h-87;else{p=!1;break}}}else if(o>1){p=!0;for(let g=1;g<o;g++){let h=a.charCodeAt(g);if(h>=48&&h<=57)d=d*10+(h-48);else{p=!1;break}}}if(p)i+=String.fromCodePoint(d);else i+=t.substring(e,n+1)}else{let o=this.customEntities[a];if(o===void 0){let d=a.length;if(d>=2&&d<=4){let p=a.charCodeAt(0);if(p===108&&d===2&&a.charCodeAt(1)===116)o="<";else if(p===103&&d===2&&a.charCodeAt(1)===116)o=">";else if(p===97&&d===3&&a.charCodeAt(1)===109&&a.charCodeAt(2)===112)o="&";else if(p===113&&d===4)o=a==="quot"?'"':void 0;else if(p===97&&d===4)o=a==="apos"?"'":void 0}if(o===void 0)o=j[a]??(this.useHtmlEntities?z[a]:void 0)}if(o!==void 0)i+=o;else i+=t.substring(e,n+1)}s=n+1,e=t.indexOf("&",s)}if(s<r)i+=t.substring(s);return i}}var w=[];w[38]="&amp;";w[60]="&lt;";w[62]="&gt;";w[34]="&quot;";w[39]="&apos;";var H={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,alwaysCreateTextNode:!1,trimValues:!0,parseTagValue:!0,parseAttributeValue:!1,processEntities:!0,htmlEntities:!1,commentPropName:!1,cdataPropName:!1,piPropName:!1,preserveOrder:!1,stopNodes:[],unpairedTags:[],isArray:void 0,tagValueProcessor:void 0,attributeValueProcessor:void 0,updateTag:void 0,numberParseOptions:{hex:!0,leadingZeros:!0,scientific:!0},ignorePiTags:!1,transformAttributeName:void 0,transformTagName:void 0,ignoreDeclaration:!1};function N(t){return t===32||t===9||t===10||t===13}function P(t){return t>=65&&t<=90||t>=97&&t<=122||t===95||t===58||t>=192&&t<=214||t>=216&&t<=246||t>=248&&t<=767||t>=880&&t<=893||t>=895&&t<=8191||t>=8204&&t<=8205||t>=8304&&t<=8591||t>=11264&&t<=12271||t>=12289&&t<=55295||t>=63744&&t<=64975||t>=65008&&t<=65533}function k(t){return P(t)||t===45||t===46||t>=48&&t<=57||t===183||t>=768&&t<=879||t>=8255&&t<=8256}var L=/^0x[\da-fA-F]+$/,X=/^[+-]?\d+(\.\d+)?[eE][+-]?\d+$/,M=/^[+-]?(\d+\.?\d*|\.\d+)$/;function v(t,e){return t.charCodeAt(e)===91&&t.charCodeAt(e+1)===67&&t.charCodeAt(e+2)===68&&t.charCodeAt(e+3)===65&&t.charCodeAt(e+4)===84&&t.charCodeAt(e+5)===65&&t.charCodeAt(e+6)===91}function I(t,e){let r=t.charCodeAt(e),i=t.charCodeAt(e+1),s=t.charCodeAt(e+2),n=t.charCodeAt(e+3),a=t.charCodeAt(e+4),o=t.charCodeAt(e+5),d=t.charCodeAt(e+6);return(r===68||r===100)&&(i===79||i===111)&&(s===67||s===99)&&(n===84||n===116)&&(a===89||a===121)&&(o===80||o===112)&&(d===69||d===101)}function G(t,e,r){if(e>=r||!P(t.charCodeAt(e)))return e;e++;while(e<r&&k(t.charCodeAt(e)))e++;return e}class O{options;entityDecoder;unpairedSet;exactStopNodes;wildcardStopSuffixes;needsJPath;_ignoreAttributes=!0;_textNodeName="#text";_commentPropName=!1;_cdataPropName=!1;_piPropName=!1;_alwaysCreateTextNode=!1;_trimValues=!0;_processEntities=!0;_parseTagValue=!0;_parseAttributeValue=!1;_removeNSPrefix=!1;_attrPrefix="@_";_attrsGroupName=!1;_ignorePiTags=!1;_ignoreDeclaration=!1;constructor(t){this.options={...H,...t},this.entityDecoder=new D(this.options.htmlEntities),this.unpairedSet=new Set(this.options.unpairedTags),this.exactStopNodes=new Set,this.wildcardStopSuffixes=[];for(let e of this.options.stopNodes)if(e.startsWith("*."))this.wildcardStopSuffixes.push(e.substring(2));else this.exactStopNodes.add(e);this._ignoreAttributes=this.options.ignoreAttributes,this._textNodeName=this.options.textNodeName,this._commentPropName=this.options.commentPropName,this._cdataPropName=this.options.cdataPropName,this._piPropName=this.options.piPropName,this._alwaysCreateTextNode=this.options.alwaysCreateTextNode,this._trimValues=this.options.trimValues,this._processEntities=this.options.processEntities,this._parseTagValue=this.options.parseTagValue,this._parseAttributeValue=this.options.parseAttributeValue,this._removeNSPrefix=this.options.removeNSPrefix,this._attrPrefix=this.options.attributeNamePrefix,this._attrsGroupName=this.options.attributesGroupName,this._ignorePiTags=this.options.ignorePiTags,this._ignoreDeclaration=this.options.ignoreDeclaration,this.needsJPath=this.options.stopNodes.length>0||this.options.isArray!==void 0||this.options.updateTag!==void 0||this.options.tagValueProcessor!==void 0||this.options.attributeValueProcessor!==void 0}addEntity(t,e){this.entityDecoder.addEntity(t,e)}parse(t){if(t instanceof Uint8Array)t=new TextDecoder().decode(t);let e=t;if(this.options.preserveOrder)return this.parseOrdered(e);return this.parseUnordered(e)}parseUnordered(t){let e={},r=t.length,i=0;if(r>0&&t.charCodeAt(0)===65279)i=1;return i=this.parseChildren(t,i,r,e,"",[]),e}parseOrdered(t){let e=t.length,r=0;if(e>0&&t.charCodeAt(0)===65279)r=1;let i=[];return this.parseChildrenOrdered(t,r,e,i,""),i}readTagName(t,e,r){return G(t,e,r)}extractTagName(t,e,r){let i=t.substring(e,r);if(this._removeNSPrefix){let s=i.indexOf(":");if(s!==-1)i=i.substring(s+1)}if(this.options.transformTagName)i=this.options.transformTagName(i);return i}parseAttributes(t,e,r,i,s){let n=0,a=this._removeNSPrefix,o=this.options.transformAttributeName,d=this._trimValues,p=this._processEntities,g=this.options.attributeValueProcessor;while(e<r){let h=t.charCodeAt(e);while(h===32||h===9||h===10||h===13){if(e++,e>=r)break;h=t.charCodeAt(e)}if(e>=r)break;if(h===62||h===47)break;let m=e;if(!P(h))break;e++;while(e<r&&k(t.charCodeAt(e)))e++;let f=t.substring(m,e);if(a){let A=f.indexOf(":");if(A!==-1)f=f.substring(A+1)}if(o)f=o(f);while(e<r&&N(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===61){e++;while(e<r&&N(t.charCodeAt(e)))e++;if(e>=r)break;let A=t.charCodeAt(e);if(A===34||A===39){e++;let b=e;while(e<r&&t.charCodeAt(e)!==A)e++;let u=t.substring(b,e);if(d&&u.length>0){let c=u.charCodeAt(0),l=u.charCodeAt(u.length-1);if(c<=32||l<=32)u=u.trim()}if(p)u=this.entityDecoder.decodeEntities(u);if(g)u=g(f,u,i)??u;if(s[f]=u,n++,e<r)e++}}else s[f]="true",n++}return n>0?-e-1:e}processTagValue(t,e,r,i,s){if(this._trimValues){let n=t.length;if(n>0){let a=t.charCodeAt(0),o=t.charCodeAt(n-1);if(a<=32||o<=32)t=t.trim()}}if(this._processEntities)t=this.entityDecoder.decodeEntities(t);if(this.options.tagValueProcessor){let n=this.options.tagValueProcessor(e,t,r,i,s);if(n!==void 0)t=n}if(!t)return t;if(this._parseTagValue)return this.parseValue(t);return t}parseValue(t){if(t==="true")return!0;if(t==="false")return!1;if(!t)return t;let e=t.charCodeAt(0);if(!(e>=48&&e<=57||e===43||e===45||e===46))return t;let i=this.options.numberParseOptions;if(i.skipLike?.test(t))return t;if(i.hex&&e===48&&L.test(t))return Number.parseInt(t,16);if(t.length>1&&e===48&&t.charCodeAt(1)!==46){if(i.leadingZeros)return t}if(i.scientific&&X.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}if(M.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}return t}parseAttributeValue(t){if(!this._parseAttributeValue)return t;return this.parseValue(t)}isStopNode(t){if(this.exactStopNodes.has(t))return!0;for(let e of this.wildcardStopSuffixes)if(t.endsWith(`.${e}`)||t===e)return!0;return!1}readStopNodeContent(t,e,r,i){let s=`</${i}`,n=t.indexOf(s,e);if(n===-1)return{content:t.substring(e),pos:r};let a=t.substring(e,n),o=n+s.length;while(o<r&&t.charCodeAt(o)!==62)o++;if(o<r)o++;return{content:a,pos:o}}addToObj(t,e,r,i,s,n){let a=t[e];if(a!==void 0)if(!Array.isArray(a))t[e]=[a,r];else a.push(r);else if(this.options.isArray?.(e,i,s,n))t[e]=[r];else t[e]=r}flushText(t,e,r,i){if(!t&&!e)return;let s=this._textNodeName;if(e){let n=t;if(n&&this._processEntities)n=this.entityDecoder.decodeEntities(n);let a=e+n;if(this._trimValues&&a.length>0){let o=a.charCodeAt(0),d=a.charCodeAt(a.length-1);if(o<=32||d<=32)a=a.trim()}if(this.options.tagValueProcessor){let o=this.options.tagValueProcessor(s,a,r,!1,!0);if(o!==void 0)a=o}if(a){let o=this._parseTagValue?this.parseValue(a):a;if(o!==void 0&&o!=="")this.addToObj(i,s,o,r,!0,!1)}}else{let n=this.processTagValue(t,s,r,!1,!0);if(n!==void 0&&n!=="")this.addToObj(i,s,n,r,!0,!1)}}parseChildren(t,e,r,i,s,n){let a="",o="",d=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let c=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!a)a=t.substring(c,e);else a+=t.substring(c,e);continue}if(e+1>=r)break;let g=t.charCodeAt(e+1);if(g===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(a||o)this.flushText(a,o,s,i),a="",o="";e+=4;let c=t.indexOf("-->",e);if(c===-1){e=r;break}if(this._commentPropName){let l=t.substring(e,c);this.addToObj(i,this._commentPropName,l,s,!0,!1)}e=c+3;continue}if(g===33&&e+8<r&&v(t,e+2)){e+=9;let c=t.indexOf("]]>",e);if(c===-1){e=r;break}let l=t.substring(e,c);if(this._cdataPropName)this.flushText(a,o,s,i),a="",o="",this.addToObj(i,this._cdataPropName,l,s,!0,!1);else{if(a){let C=a;if(this._processEntities)C=this.entityDecoder.decodeEntities(C);o+=C,a=""}o+=l}e=c+3;continue}if(g===33&&e+9<r&&I(t,e+2)){e+=9;let c=1;while(e<r&&c>0){let l=t.charCodeAt(e);if(l===60)c++;else if(l===62)c--;e++}continue}if(g===63){e+=2;let c=e;while(e<r&&!N(t.charCodeAt(e))&&t.charCodeAt(e)!==63)e++;let l=t.substring(c,e),C=t.indexOf("?>",e);if(C===-1){e=r;break}let y=t.substring(e,C).trim();if(l==="xml"){if(!this._ignoreDeclaration&&this._piPropName){let S=this.parsePiAttributes(y);this.addToObj(i,this._piPropName,{[l]:S},s,!0,!1)}}else if(!this._ignorePiTags&&this._piPropName)this.addToObj(i,this._piPropName,{[l]:y},s,!0,!1);e=C+2;continue}if(g===47){if(a||o)this.flushText(a,o,s,i),a="",o="";e+=2;let c=e,l=this.readTagName(t,e,r),C=this.extractTagName(t,c,l);e=l;while(e<r&&N(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;if(n.length>0&&n[n.length-1]===C){n.pop();continue}return e}if(a||o)this.flushText(a,o,s,i),a="",o="";e++;let h=e,m=this.readTagName(t,e,r),f=this.extractTagName(t,h,m);if(!f){e=m+1;continue}e=m;let A=d?s?`${s}.${f}`:f:"",b={},u=!1;if(!this._ignoreAttributes){let c=this.parseAttributes(t,e,r,A,b);if(c<0)e=-c-1,u=!0;else e=c}else while(e<r){let c=t.charCodeAt(e);if(c===62||c===47)break;if(c===34||c===39){e++;while(e<r&&t.charCodeAt(e)!==c)e++}e++}if(this.options.updateTag){if(this.options.updateTag(f,A,b)===!1){while(e<r&&N(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47)e+=2;else if(e<r&&t.charCodeAt(e)===62){e++;let l=`</${f}>`,C=t.indexOf(l,e);if(C!==-1)e=C+l.length}continue}}while(e<r&&N(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47){if(e+=2,u||this._alwaysCreateTextNode){let c={};if(u)this.applyAttributes(c,b,A);if(this._alwaysCreateTextNode)c[this._textNodeName]="";this.addToObj(i,f,c,A,!0,!1)}else this.addToObj(i,f,"",A,!0,!1);continue}if(e<r&&t.charCodeAt(e)===62){if(e++,this.unpairedSet.has(f)){if(u){let y={};this.applyAttributes(y,b,A),this.addToObj(i,f,y,A,!0,!1)}else this.addToObj(i,f,"",A,!0,!1);n.push(f);continue}if(this.exactStopNodes.size>0||this.wildcardStopSuffixes.length>0){if(this.isStopNode(A)){let y=this.readStopNodeContent(t,e,r,f),S={};if(u)this.applyAttributes(S,b,A);if(y.content)S[this._textNodeName]=y.content;this.addToObj(i,f,S,A,!0,!1),e=y.pos;continue}}let c={};if(u)this.applyAttributes(c,b,A);e=this.parseChildren(t,e,r,c,A,n);let l=this._textNodeName,C=c[l];if(!u&&!this._alwaysCreateTextNode){let y=!0;for(let S in c)if(S!==l){y=!1;break}if(y){this.addToObj(i,f,C!==void 0?C:"",A,!0,!1);continue}}this.addToObj(i,f,c,A,!1,!1)}}if(a||o)this.flushText(a,o,s,i);return e}parseChildrenOrdered(t,e,r,i,s){let n="",a=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let u=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!n)n=t.substring(u,e);else n+=t.substring(u,e);continue}if(e+1>=r)break;let d=t.charCodeAt(e+1);if(d===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(n){let c=this.processTagValue(n,this._textNodeName,s,!1,!0);if(c!==void 0&&c!=="")i.push({[this._textNodeName]:c});n=""}e+=4;let u=t.indexOf("-->",e);if(u===-1){e=r;break}if(this._commentPropName)i.push({[this._commentPropName]:[{[this._textNodeName]:t.substring(e,u)}]});e=u+3;continue}if(d===33&&e+8<r&&v(t,e+2)){e+=9;let u=t.indexOf("]]>",e);if(u===-1){e=r;break}let c=t.substring(e,u);if(this._cdataPropName){if(n){let l=this.processTagValue(n,this._textNodeName,s,!1,!0);if(l!==void 0&&l!=="")i.push({[this._textNodeName]:l});n=""}i.push({[this._cdataPropName]:[{[this._textNodeName]:c}]})}else n+=c;e=u+3;continue}if(d===33&&e+9<r&&I(t,e+2)){e+=9;let u=1;while(e<r&&u>0){let c=t.charCodeAt(e);if(c===60)u++;else if(c===62)u--;e++}continue}if(d===63){e+=2;let u=t.indexOf("?>",e);if(u===-1){e=r;break}e=u+2;continue}if(d===47){if(n){let c=this.processTagValue(n,this._textNodeName,s,!1,!0);if(c!==void 0&&c!=="")i.push({[this._textNodeName]:c});n=""}e+=2,e=this.readTagName(t,e,r);while(e<r&&N(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;return e}if(n){let u=this.processTagValue(n,this._textNodeName,s,!1,!0);if(u!==void 0&&u!=="")i.push({[this._textNodeName]:u});n=""}e++;let p=e,g=this.readTagName(t,e,r),h=this.extractTagName(t,p,g);if(!h){e=g+1;continue}e=g;let m=a?s?`${s}.${h}`:h:"",f={},A=!1;if(!this._ignoreAttributes){let u=this.parseAttributes(t,e,r,m,f);if(u<0)e=-u-1,A=!0;else e=u}else while(e<r){let u=t.charCodeAt(e);if(u===62||u===47)break;if(u===34||u===39){e++;while(e<r&&t.charCodeAt(e)!==u)e++}e++}while(e<r&&N(t.charCodeAt(e)))e++;let b={[h]:[]};if(A){b[":@"]={};for(let c in f)b[":@"][this._attrPrefix+c]=this.parseAttributeValue(f[c])}if(e<r&&t.charCodeAt(e)===47){e+=2,i.push(b);continue}if(e<r&&t.charCodeAt(e)===62)e++,e=this.parseChildrenOrdered(t,e,r,b[h],m),i.push(b)}if(n){let o=this.processTagValue(n,this._textNodeName,s,!1,!0);if(o!==void 0&&o!=="")i.push({[this._textNodeName]:o})}return e}applyAttributes(t,e,r){let i=this._attrPrefix;if(this._attrsGroupName){let s={};for(let n in e)s[i+n]=this.parseAttributeValue(e[n]);t[this._attrsGroupName]=s}else for(let s in e)t[i+s]=this.parseAttributeValue(e[s])}parsePiAttributes(t){let e={},r=0,i=t.length;while(r<i){while(r<i&&N(t.charCodeAt(r)))r++;if(r>=i)break;let s=r;while(r<i&&!N(t.charCodeAt(r))&&t.charCodeAt(r)!==61)r++;let n=t.substring(s,r);if(!n)break;while(r<i&&N(t.charCodeAt(r)))r++;if(r<i&&t.charCodeAt(r)===61){r++;while(r<i&&N(t.charCodeAt(r)))r++;if(r<i){let a=t.charCodeAt(r);if(a===34||a===39){r++;let o=r;while(r<i&&t.charCodeAt(r)!==a)r++;if(e[n]=t.substring(o,r),r<i)r++}}}}return e}}function R(t){let e=t.endpoint||`s3.${t.region}.amazonaws.com`,r=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.pathname!=="/"&&r.pathname!==""||r.search||r.hash||r.username||r.password)throw Error("S3 endpoint must be an HTTP(S) origin without a path");let i=r.protocol.slice(0,-1),s=r.host;if(!t.bucket)return{protocol:i,host:s,path:t.path};if(t.forcePathStyle){let n=t.path==="/"?`/${t.bucket}`:`/${t.bucket}${t.path}`;return{protocol:i,host:s,path:n}}return{protocol:i,host:`${t.bucket}.${s}`,path:t.path}}class J{credentials;config;cache;xmlParser;constructor(t,e){this.config={maxRetries:3,retryDelay:1000,cacheEnabled:!0,defaultCacheTTL:60000,...e},this.credentials=t||this.loadCredentials(),this.cache=new Map,this.xmlParser=new O({ignoreAttributes:!1,attributeNamePrefix:"@_",textNodeName:"#text",parseAttributeValue:!0,trimValues:!0})}loadCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=process.env.AWS_SESSION_TOKEN;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:r};let i=this.loadCredentialsFromFile();if(i)return i;return{accessKeyId:"",secretAccessKey:""}}loadCredentialsFromFile(){let t=this.config?.profile||process.env.AWS_PROFILE||"default",e=process.env.AWS_SHARED_CREDENTIALS_FILE||B(W(),".aws","credentials");if(!V(e))return null;try{let r=Y(e,"utf-8"),i=this.parseCredentialsFile(r,t);if(i.accessKeyId&&i.secretAccessKey)return i}catch{}return null}parseCredentialsFile(t,e){let r=t.split(`
2
- `),i="",s="",n="",a;for(let o of r){let d=o.trim();if(!d||d.startsWith("#"))continue;let p=d.match(/^\[([^\]]+)\]$/);if(p){i=p[1];continue}if(i===e){let[g,...h]=d.split("="),m=h.join("=").trim();if(g.trim()==="aws_access_key_id")s=m;else if(g.trim()==="aws_secret_access_key")n=m;else if(g.trim()==="aws_session_token")a=m}}return{accessKeyId:s,secretAccessKey:n,sessionToken:a}}ec2CredentialsCache;async getCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:process.env.AWS_SESSION_TOKEN};let r=this.loadCredentialsFromFile();if(r)return r;if(this.ec2CredentialsCache){let i=Date.now();if(this.ec2CredentialsCache.expiration>i+300000)return this.ec2CredentialsCache.credentials}try{let s=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),a=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}})).text(),d=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${a}`,{headers:{"X-aws-ec2-metadata-token":s}})).json(),p={accessKeyId:d.AccessKeyId,secretAccessKey:d.SecretAccessKey,sessionToken:d.Token};return this.ec2CredentialsCache={credentials:p,expiration:new Date(d.Expiration).getTime()},p}catch(i){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request(t){if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey){let i=this.getFromCache(t.cacheKey);if(i!==null)return i}let e=t.retries??this.config.maxRetries??3,r=null;for(let i=0;i<=e;i++)try{let s=await this.makeRequest(t);if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey)this.setInCache(t.cacheKey,s,t.cacheTTL??this.config.defaultCacheTTL??60000);return s}catch(s){if(r=s,!this.shouldRetry(s))throw s;if(i===e)throw s;let a=this.calculateRetryDelay(i);await this.sleep(a)}throw r||Error("Request failed after retries")}async makeRequest(t){let e=t.credentials||(this.credentials?.accessKeyId?this.credentials:await this.getCredentials());if(!e||!e.accessKeyId||!e.secretAccessKey)throw Error("AWS credentials not provided");let r=this.buildUrl(t),i=this.signRequest(t,e),s=await fetch(r,{method:t.method,headers:i,body:t.body}),n=await s.text();if(!s.ok)throw this.parseError(n,s.status,s.headers);if(!n||n.trim()===""){if(t.returnHeaders)return{body:null,headers:this.headersToObject(s.headers)};return null}if(t.rawResponse){if(t.returnHeaders)return{body:n,headers:this.headersToObject(s.headers)};return n}let a;if(n.startsWith("<"))a=this.parseXmlResponse(n);else try{a=JSON.parse(n)}catch{a=n}if(t.returnHeaders)return{body:a,headers:this.headersToObject(s.headers)};return a}headersToObject(t){let e={};return t.forEach((r,i)=>{e[i]=r}),e}buildUrl(t){let{service:e,region:r,queryParams:i}=t,{path:s}=t,n,a="https";if(e==="s3"){let d=R({region:r,path:s,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});a=d.protocol,n=d.host,s=d.path}else if(e==="cloudfront")n="cloudfront.amazonaws.com";else if(e==="iam")n="iam.amazonaws.com";else if(e==="route53")n="route53.amazonaws.com";else if(e==="route53domains")n="route53domains.us-east-1.amazonaws.com";else if(e==="ecr")n=`api.ecr.${r}.amazonaws.com`;else if(e==="ses")n=`email.${r}.amazonaws.com`;else n=`${e}.${r}.amazonaws.com`;let o=`${a}://${n}${s}`;if(i&&Object.keys(i).length>0){let d=Object.keys(i).map((p)=>`${this.uriEncode(p)}=${this.uriEncode(i[p])}`).join("&");o+=`?${d}`}return o}signRequest(t,e){let{service:r,region:i,method:s,queryParams:n,body:a}=t,{path:o}=t,d=new Date,p=this.getAmzDate(d),g=this.getDateStamp(d),h;if(r==="s3"){let E=R({region:i,path:o,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});h=E.host,o=E.path}else if(r==="cloudfront")h="cloudfront.amazonaws.com";else if(r==="iam")h="iam.amazonaws.com";else if(r==="route53")h="route53.amazonaws.com";else if(r==="route53domains")h="route53domains.us-east-1.amazonaws.com";else if(r==="ecr")h=`api.ecr.${i}.amazonaws.com`;else if(r==="ses")h=`email.${i}.amazonaws.com`;else h=`${r}.${i}.amazonaws.com`;let m={host:h,"x-amz-date":p,...t.headers||{}};if(e.sessionToken)m["x-amz-security-token"]=e.sessionToken;if(a){if(!Object.keys(m).some((T)=>T.toLowerCase()==="content-type"))m["content-type"]="application/x-www-form-urlencoded";m["content-length"]=Buffer.byteLength(a).toString()}let f=this.sha256(a||"");m["x-amz-content-sha256"]=f;let A=o,b=n?Object.keys(n).sort().map((E)=>`${this.uriEncode(E)}=${this.uriEncode(n[E])}`).join("&"):"",u=Object.keys(m).sort((E,T)=>E.toLowerCase().localeCompare(T.toLowerCase())),c=u.map((E)=>`${E.toLowerCase()}:${m[E].trim()}
3
- `).join(""),l=u.map((E)=>E.toLowerCase()).join(";"),C=[s,A,b,c,l,f].join(`
4
- `),y="AWS4-HMAC-SHA256",S=r;if(r==="email")S="ses";let x=`${g}/${i}/${S}/aws4_request`,K=[y,p,x,this.sha256(C)].join(`
5
- `),F=this.getSignatureKey(e.secretAccessKey,g,i,S),q=this.hmac(F,K),U=`${y} Credential=${e.accessKeyId}/${x}, SignedHeaders=${l}, Signature=${q}`;return{...m,Authorization:U}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return _.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return _.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=_.createHmac("sha256",`AWS4${t}`).update(e).digest(),n=_.createHmac("sha256",s).update(r).digest(),a=_.createHmac("sha256",n).update(i).digest();return _.createHmac("sha256",a).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let n=s.ErrorResponse.Error;return i.code=n.Code,i.message=`AWS Error [${n.Code}]: ${n.Message||"Unknown error"}`,i.type=n.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function ie(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,n)=>{e[`${r}.${n+1}`]=String(s)});else if(typeof i==="object")for(let[s,n]of Object.entries(i))e[`${r}.${s}`]=String(n);else e[r]=String(i)}return e}function se(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",n=process.env.AWS_SHARED_CREDENTIALS_FILE||B(W(),".aws","credentials");if(V(n))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
- export{R as _h,J as $h,ie as ai,se as bi};