@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,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 ch,J as dh,ie as eh,se as fh};
@@ -1 +0,0 @@
1
- import{$h as V,$i as Wa,$j as Wb,$k as Wc,$l as Wd,$m as We,$n as Xf,$o as Xg,Ah as u,Ai as va,Aj as vb,Ak as vc,Al as vd,Am as ve,An as wf,Ao as wg,Bh as v,Bi as wa,Bj as wb,Bk as wc,Bl as wd,Bm as we,Bn as xf,Bo as xg,Ch as w,Ci as xa,Cj as xb,Ck as xc,Cl as xd,Cm as xe,Cn as yf,Co as yg,Dh as x,Di as ya,Dj as yb,Dk as yc,Dl as yd,Dm as ye,Dn as zf,Do as zg,Eh as y,Ei as za,Ej as zb,Ek as zc,El as zd,Em as ze,En as Af,Eo as Ag,Fh as z,Fi as Aa,Fj as Ab,Fk as Ac,Fl as Ad,Fm as Ae,Fn as Bf,Fo as Bg,Gh as A,Gi as Ba,Gj as Bb,Gk as Bc,Gl as Bd,Gm as Be,Gn as Cf,Go as Cg,Hh as B,Hi as Ca,Hj as Cb,Hk as Cc,Hl as Cd,Hm as Ce,Hn as Df,Ho as Dg,Ih as C,Ii as Da,Ij as Db,Ik as Dc,Il as Dd,Im as De,In as Ef,Io as Eg,Jh as D,Ji as Ea,Jj as Eb,Jk as Ec,Jl as Ed,Jm as Ee,Jn as Ff,Jo as Fg,Kh as E,Ki as Fa,Kj as Fb,Kk as Fc,Kl as Fd,Km as Fe,Kn as Gf,Ko as Gg,Lh as F,Li as Ga,Lj as Gb,Lk as Gc,Ll as Gd,Lm as Ge,Ln as Hf,Lo as Hg,Mh as G,Mi as Ha,Mj as Hb,Mk as Hc,Ml as Hd,Mm as He,Mn as If,Mo as Ig,Nh as H,Ni as Ia,Nj as Ib,Nk as Ic,Nl as Id,Nm as Ie,Nn as Jf,No as Jg,Oh as I,Oi as Ja,Oj as Jb,Ok as Jc,Ol as Jd,Om as Je,On as Kf,Oo as Kg,Ph as J,Pi as Ka,Pj as Kb,Pk as Kc,Pl as Kd,Pm as Ke,Pn as Lf,Po as Lg,Qh as K,Qi as La,Qj as Lb,Qk as Lc,Ql as Ld,Qm as Le,Qn as Mf,Qo as Mg,Rh as L,Ri as Ma,Rj as Mb,Rk as Mc,Rl as Md,Rm as Me,Rn as Nf,Ro as Ng,Sh as M,Si as Na,Sj as Nb,Sk as Nc,Sl as Nd,Sm as Ne,Sn as Of,So as Og,Th as N,Ti as Oa,Tj as Ob,Tk as Oc,Tl as Od,Tm as Oe,Tn as Pf,To as Pg,Uh as O,Ui as Pa,Uj as Pb,Uk as Pc,Ul as Pd,Um as Pe,Un as Qf,Uo as Qg,Vh as P,Vi as Qa,Vj as Qb,Vk as Qc,Vl as Qd,Vm as Qe,Vn as Rf,Vo as Rg,Wh as Q,Wi as Ra,Wj as Rb,Wk as Rc,Wl as Rd,Wm as Re,Wn as Sf,Wo as Sg,Xh as R,Xi as Sa,Xj as Sb,Xk as Sc,Xl as Sd,Xm as Se,Xn as Tf,Xo as Tg,Yh as S,Yi as Ta,Yj as Tb,Yk as Tc,Yl as Td,Ym as Te,Yn as Uf,Yo as Ug,Zh as T,Zi as Ua,Zj as Ub,Zk as Uc,Zl as Ud,Zm as Ue,Zn as Vf,Zo as Vg,_h as U,_i as Va,_j as Vb,_k as Vc,_l as Vd,_m as Ve,_n as Wf,_o as Wg,ai as W,aj as Xa,ak as Xb,al as Xc,am as Xd,an as Xe,ao as Yf,ap as Yg,bi as X,bj as Ya,bk as Yb,bl as Yc,bm as Yd,bn as Ye,bo as Zf,bp as Zg,ci as Y,cj as Za,ck as Zb,cl as Zc,cm as Zd,cn as Ze,co as _f,cp as _g,di as Z,dj as _a,dk as _b,dl as _c,dm as _d,dn as _e,do as $f,dp as $g,ei as _,ej as $a,ek as $b,el as $c,em as $d,en as $e,eo as ag,ep as ah,fi as aa,fj as ab,fk as ac,fl as ad,fm as ae,fn as af,fo as bg,fp as bh,gh as a,gi as ba,gj as bb,gk as bc,gl as bd,gm as be,gn as bf,go as cg,gp as ch,hh as b,hi as ca,hj as cb,hk as cc,hl as cd,hm as ce,hn as cf,ho as dg,hp as dh,ih as c,ii as da,ij as db,ik as dc,il as dd,im as de,in as df,io as eg,ip as eh,jh as d,ji as ea,jj as eb,jk as ec,jl as ed,jm as ee,jn as ef,jo as fg,jp as fh,kh as e,ki as fa,kj as fb,kk as fc,kl as fd,km as fe,kn as ff,ko as gg,kp as gh,lh as f,li as ga,lj as gb,lk as gc,ll as gd,lm as ge,ln as gf,lo as hg,lp as hh,mh as g,mi as ha,mj as hb,mk as hc,ml as hd,mm as he,mn as hf,mo as ig,mp as ih,nh as h,ni as ia,nj as ib,nk as ic,nl as id,nm as ie,nn as jf,no as jg,oh as i,oi as ja,oj as jb,ok as jc,ol as jd,om as je,on as kf,oo as kg,ph as j,pi as ka,pj as kb,pk as kc,pl as kd,pm as ke,pn as lf,po as lg,qh as k,qi as la,qj as lb,qk as lc,ql as ld,qm as le,qn as mf,qo as mg,rh as l,ri as ma,rj as mb,rk as mc,rl as md,rm as me,rn as nf,ro as ng,sh as m,si as na,sj as nb,sk as nc,sl as nd,sm as ne,sn as of,so as og,th as n,ti as oa,tj as ob,tk as oc,tl as od,tm as oe,tn as pf,to as pg,uh as o,ui as pa,uj as pb,uk as pc,ul as pd,um as pe,un as qf,uo as qg,vh as p,vi as qa,vj as qb,vk as qc,vl as qd,vm as qe,vn as rf,vo as rg,wh as q,wi as ra,wj as rb,wk as rc,wl as rd,wm as re,wn as sf,wo as sg,xh as r,xi as sa,xj as sb,xk as sc,xl as sd,xm as se,xn as tf,xo as tg,yh as s,yi as ta,yj as tb,yk as tc,yl as td,ym as te,yn as uf,yo as ug,zh as t,zi as ua,zj as ub,zk as uc,zl as ud,zm as ue,zn as vf,zo as vg}from"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{Ie as ABTestManager,ra as AI,Sb as AWSAPIError,we as AWSConfigManager,Ja as AWS_PSEUDO_PARAMETERS,Hd as AWS_REGIONS,va as ApiGateway,Ia as Arn,Ba as AssetHasher,za as Auth,se as BackupManager,Zf as BatchProcessingManager,Ee as BlueGreenManager,Jf as BounceComplaintHandler,lf as BuildOptimizationManager,ca as CDN,vg as CHAIN_HEADER,_d as COMMON_CROSS_ACCOUNT_ROLES,ta as Cache,Ge as CanaryManager,ef as CertificateManager,Nb as CloudError,Ka as CloudFormationBuilder,Ib as CloudFormationClient,Mb as CloudFrontClient,ye as CloudTrailManager,ud as CommandHistory,Ga as Communication,fa as Compute,Ob as ConfigurationError,nf as ContainerRegistryManager,Pb as CredentialError,zd as CrossRegionReferenceManager,cb as DASHBOARD_ENTRY,db as DASHBOARD_PORT_BASE,eb as DASHBOARD_PORT_SPAN,bb as DASHBOARD_STATE_DIR,yg as DEFAULT_RECURSION_LIMITS,bc as DEFAULT_SERVICE_LIMITS,q as DEFAULT_STATE_DIR,ug as DEPTH_HEADER,Xf as DLQMonitoringManager,da as DNS,Ff as DNSSECManager,sa as Database,_e as DatabaseUserManager,Wb as DebugLogger,Y as DependencyGraph,Aa as Deployment,Qb as DeploymentError,ue as DisasterRecoveryManager,ia as Email,Rf as EmailAdvanced,Lf as EmailAnalyticsManager,Sf as EmailHandlers,Pf as EmailTemplateManager,Tb as ErrorCodes,Vf as FIFOQueueManager,fc as FileCache,ha as FileSystem,Ha as Fn,Ad as GlobalResourceManager,Ae as GuardDutyManager,pc as HashCache,dh as HealthCheckManager,jf as ImageScanningManager,ma as JobLoader,Vg as LARAVEL_SERVERLESS_BUILD_STEPS,vf as LambdaConcurrencyManager,Bf as LambdaDLQManager,xf as LambdaDestinationsManager,rf as LambdaLayersManager,zf as LambdaVPCManager,tf as LambdaVersionsManager,Qe as LogsManager,hg as MANAGED_NODE_VERSIONS,jb as MANAGEMENT_DASHBOARD_SITE_PREFIX,wa as Messaging,Oe as MetricsManager,Ue as MigrationManager,Nc as MockCloudFormation,Pc as MockDynamoDB,Oc as MockS3,ya as Monitoring,Ud as MultiAccountManager,xd as MultiRegionManager,ed as MultiStepProgress,ga as Network,fh as NetworkSecurityManager,Vd as OrganizationManager,Xg as PHP_DEFAULT_EXCLUDES,mg as PHP_LAYER_EXTENSIONS,Da as ParameterStore,Ye as PerformanceManager,ua as Permissions,ka as Phone,Tf as PhoneAdvanced,ja as PhoneHandlers,Rc as PreviewEnvironmentManager,Wc as PreviewNotificationService,dd as ProgressBar,Ke as ProgressiveDeploymentManager,K as Pseudo,la as Queue,$f as QueueManagementManager,o as QueuePresets,Yd as RECOMMENDED_ACCOUNT_STRUCTURES,Zd as RECOMMENDED_SCPS,rd as REPL,td as REPLCommandBuilder,sd as REPLContext,wc as RateLimiter,p as RealtimePresets,Bg as RecursionGuard,Fa as Redirects,Bd as RegionPairManager,ba as Registry,We as ReplicaManager,hh as ResourceManagementManager,Hf as Route53ResolverManager,Df as Route53RoutingManager,Jb as S3Client,Kb as S3Error,pa as SMS,r as STATE_DIR_ENV_VAR,Ea as Search,Ca as Secrets,cf as SecretsManager,af as SecretsRotationManager,ea as Security,Ce as SecurityHubManager,gf as SecurityScanningManager,Nf as SenderReputationManager,pf as ServiceMeshManager,qa as Sftp,Uf as SmsAdvanced,oa as SmsHandlers,fd as Spinner,Cd as StackDependencyManager,na as StacksIntegration,$g as StaticSiteManager,aa as Storage,bh as StorageAdvancedManager,Se as SyntheticsManager,wg as TRACE_HEADER,gd as TaskList,G as TemplateBuilder,gc as TemplateCache,Rb as ValidationError,xa as Workflow,Me as XRayManager,Je as abTestManager,Z as analyzeStackDiff,fg as artifactKey,md as autocomplete,xe as awsConfigManager,te as backupManager,rc as batch,_f as batchProcessingManager,Fe as blueGreenManager,Kf as bounceComplaintHandler,tg as buildBunRuntimeLayerZip,La as buildCloudFormationTemplate,E as buildMailEnv,sg as buildNodeRuntimeLayerZip,mf as buildOptimizationManager,Wg as buildPhpRuntimeLayerZip,He as canaryManager,Cc as categorizeChanges,ff as certificateManager,_b as checkIAMPermissions,Jg as checkInvocation,cc as checkServiceQuotas,xc as chunk,k as clearSigningKeyCache,Fc as cloudConfigSchema,ze as cloudTrailManager,Zg as collectPhpAppEntries,pb as composePresets,lg as composeServerlessAppTemplate,of as containerRegistryManager,Sa as createApiBackendPreset,Qg as createCliHandler,Eb as createCredentialProvider,ab as createDashboardSite,Xa as createDataPipelinePreset,Vb as createError,Qa as createExistingStaticFullStackPreset,Ra as createFullStackAppPreset,Rg as createHandlers,Og as createHttpHandler,Ua as createJamstackPreset,_a as createLaravelPreset,Ya as createMLApiPreset,Va as createMicroservicesPreset,Qc as createMockAWS,Na as createNodeJsServerPreset,Oa as createNodeJsServerlessPreset,qb as createPreset,d as createPresignedUrl,e as createPresignedUrlAsync,Pg as createQueueHandler,Wa as createRealtimeAppPreset,Lb as createS3Client,$a as createServerlessLaravelPreset,Pa as createServerlessNodePreset,Ma as createStaticSitePreset,Za as createTraditionalWebAppPreset,Ta as createWordPressPreset,bg as createZip,Dd as crossRegionReferenceManager,$e as databaseUserManager,Hc as defaultLocalConfig,z as deploymentCoexistenceError,fb as deriveManagementDashboardPort,x as detectDeploymentTargets,Yb as detectMisconfigurations,a as detectServiceRegion,zc as diffTemplates,Yf as dlqMonitoringManager,Gf as dnssecManager,ve as drManager,Mf as emailAnalyticsManager,Qf as emailTemplateManager,Mg as eventToRequest,ob as extendPreset,Wf as fifoQueueManager,oc as findChangedFiles,ce as formatAccountStructure,$c as formatBytes,_ as formatDiff,ad as formatDuration,od as formatFlagSuggestions,vd as formatHistory,wd as formatHistoryStats,cd as formatKeyValue,bd as formatList,_c as formatProgressBar,Rd as formatRegion,Sd as formatRegionList,id as formatSuggestion,Yc as formatTable,Zc as formatTree,Ab as fromEC2Metadata,Bb as fromECSMetadata,yb as fromEnvironment,zb as fromSharedCredentials,Cb as fromWebIdentity,xg as functionFingerprint,qg as generateAppImageDockerfile,qe as generateApprovalConfig,cg as generateBootstrap,Uc as generateCleanupWorkflow,Vc as generateCostReportWorkflow,ae as generateCrossAccountRoleCF,ne as generateDeploymentConfig,ie as generateDeploymentPipeline,de as generateDeploymentWorkflow,M as generateLogicalId,me as generateManualPipeline,he as generateMatrixWorkflow,oe as generateMultiEnvConfig,je as generateMultiEnvPipeline,ee as generateMultiEnvWorkflow,fe as generatePRPreviewWorkflow,re as generateParallelConfig,Sg as generatePhpFpmConfig,pg as generatePhpLayerDockerfile,ke as generatePreviewPipeline,Tc as generatePreviewWorkflow,L as generateResourceName,pe as generateScheduledConfig,le as generateScheduledPipeline,ge as generateScheduledWorkflow,Hb as getAccountId,Jd as getAllRegions,Od as getClosestRegion,pd as getCommandUsage,kd as getContextualHelp,Db as getCredentials,Dc as getDeploymentStrategy,Ec as getDiffStats,Ac as getDiffSummary,Ub as getErrorDetails,Ic as getLocalConfig,Lc as getLocalCredentials,Kc as getLocalEndpoint,Mc as getLocalEnvVars,dc as getQuotaUsageSummary,$d as getRecommendedStructure,Id as getRegion,Td as getRegionStats,Ld as getRegionsByCompliance,Kd as getRegionsByLocation,Md as getRegionsByPricingTier,$b as getRequiredPermissions,l as getSigningKeyCacheSize,N as getTimestamp,Ed as globalResourceManager,Be as guardDutyManager,ib as hasManagementDashboardSite,kc as hashBuffer,lc as hashDirectory,ic as hashFile,mc as hashManifest,jc as hashString,eh as healthCheckManager,kf as imageScanningManager,Ag as inspectInvocation,Gg as installRecursionFetch,Eg as invocationContext,jd as isLikelyTypo,Jc as isLocalDevelopment,lb as isManagementDashboardSiteName,m as isNodeCryptoAvailable,w as isStatePath,Nd as isValidRegion,n as isWebCryptoAvailable,wf as lambdaConcurrencyManager,Cf as lambdaDLQManager,yf as lambdaDestinationsManager,sf as lambdaLayersManager,Af as lambdaVPCManager,uf as lambdaVersionsManager,Ug as laravelServerlessEnvDefaults,Re as logsManager,B as mailEnabled,D as mailFirewallPorts,f as makeAWSRequest,h as makeAWSRequestAsync,g as makeAWSRequestOnce,kb as managementDashboardSiteName,rb as mergeInfrastructure,Pe as metricsManager,Ve as migrationManager,Wd as multiAccountManager,yd as multiRegionManager,gh as networkSecurityManager,Xd as organizationManager,_g as packagePhpApp,gg as packageServerlessApp,qc as parallel,sc as parallelMap,tc as parallelWithRetry,zg as parseChain,j as parseJSONResponse,i as parseXMLResponse,Ze as performanceManager,og as phpLayerBuildStage,ng as phpLayerPackages,Tg as phpRuntimeLayerAssets,Sc as previewManager,Xc as previewNotifications,yc as processInChunks,Le as progressiveDeploymentManager,Cg as propagationHeaders,ag as queueManagementManager,nc as quickHash,Dg as recursionBlockedResponse,Fd as regionPairManager,Xe as replicaManager,Bc as requiresReplacement,Ig as resetRecursionRuntime,Lg as resolveApp,A as resolveAppDatabase,F as resolveCloudProvider,Fb as resolveCredentials,gb as resolveDashboardDomain,hb as resolveDashboardDomains,U as resolveDeployBucketName,y as resolveDeploymentMode,C as resolveMailService,nb as resolveManagementDashboardSite,mb as resolveManagementDashboardSites,P as resolveProjectStackName,kg as resolveQueueNames,jg as resolveQueues,Fg as resolveRecursionConfig,Gb as resolveRegion,V as resolveServerlessAppStackName,W as resolveServerlessArtifactBucketName,X as resolveServerlessAssetBucketName,ig as resolveServerlessRuntime,S as resolveSiteBucketName,R as resolveSiteResourceName,Q as resolveSiteStackName,v as resolveStatePath,T as resolveStorageBucketName,ih as resourceManagementManager,Ng as responseToResult,If as route53ResolverManager,Ef as route53RoutingManager,dg as runBuildHooks,Yg as runPhpBuildHooks,O as sanitizeName,ld as searchCommands,df as secretsManager,bf as secretsRotationManager,De as securityHubManager,hf as securityScanningManager,Of as senderReputationManager,uc as sequence,qf as serviceMeshManager,s as setStateDir,eg as sha256,Hg as sharedRecursionGuard,rg as sharedRuntimeLoop,b as signRequest,c as signRequestAsync,Gd as stackDependencyManager,t as stateDir,u as statePath,ah as staticSiteManager,ch as storageAdvancedManager,hd as suggestCommand,nd as suggestFlags,ac as suggestIAMPolicy,ec as suggestQuotaIncrease,Qd as suggestRegionPairs,Pd as suggestRegions,Te as syntheticsManager,hc as templateCache,be as validateAccountStructure,Gc as validateAgainstSchema,qd as validateCommand,Xb as validateConfiguration,Zb as validateCredentials,J as validateResourceLimits,H as validateTemplate,I as validateTemplateSize,wb as withCDN,vb as withCache,ub as withDatabase,Kg as withInvocation,sb as withMonitoring,xb as withQueue,tb as withSecurity,vc as withTimeout,Ne as xrayManager};
@@ -1,3 +0,0 @@
1
- import{_d as b}from"./chunk-c0bdafbx.js";import{jg as Z}from"./chunk-a7w13qfm.js";import{qg as P}from"./chunk-btsyjhk7.js";import{Lg as V,Mg as ne,Ng as U,Pg as R,Qg as m,Rg as M,Yg as ie}from"./chunk-6tfwm33r.js";import{dh as se}from"./chunk-ja1vjdn1.js";import{$h as ae,Yo as pe,ai as oe,bi as ce,cp as fe,jo as le,ko as ue,mo as ge,oo as de,po as me}from"./chunk-4q6tad44.js";import{op as Q}from"./chunk-ehc63fvs.js";import{existsSync as Ae,readdirSync as Te,readFileSync as be,statSync as ke}from"node:fs";import{join as Se,relative as Ee}from"node:path";class _{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new se}async createSecret(e){let t={Name:e.Name};if(e.Description)t.Description=e.Description;if(e.KmsKeyId)t.KmsKeyId=e.KmsKeyId;if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.AddReplicaRegions&&e.AddReplicaRegions.length>0)t.AddReplicaRegions=e.AddReplicaRegions;if(e.ForceOverwriteReplicaSecret!==void 0)t.ForceOverwriteReplicaSecret=e.ForceOverwriteReplicaSecret;t.ClientRequestToken=e.ClientRequestToken||crypto.randomUUID();let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,ReplicationStatus:r.ReplicationStatus}}async updateSecret(e){let t={SecretId:e.SecretId};if(e.Description)t.Description=e.Description;if(e.KmsKeyId)t.KmsKeyId=e.KmsKeyId;if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId}}async putSecretValue(e){let t={SecretId:e.SecretId};if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;if(e.VersionStages&&e.VersionStages.length>0)t.VersionStages=e.VersionStages;if(e.ClientRequestToken)t.ClientRequestToken=e.ClientRequestToken;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,VersionStages:r.VersionStages}}async getSecretValue(e){let t={SecretId:e.SecretId};if(e.VersionId)t.VersionId=e.VersionId;if(e.VersionStage)t.VersionStage=e.VersionStage;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,SecretBinary:r.SecretBinary,SecretString:r.SecretString,VersionStages:r.VersionStages,CreatedDate:r.CreatedDate}}async describeSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return this.parseSecret(r)}async listSecrets(e){let t={};if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.SortOrder)t.SortOrder=e.SortOrder;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{SecretList:r.SecretList?.map((s)=>this.parseSecret(s)),NextToken:r.NextToken}}async deleteSecret(e){let t={SecretId:e.SecretId};if(e.RecoveryWindowInDays!==void 0)t.RecoveryWindowInDays=e.RecoveryWindowInDays;if(e.ForceDeleteWithoutRecovery!==void 0)t.ForceDeleteWithoutRecovery=e.ForceDeleteWithoutRecovery;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,DeletionDate:r.DeletionDate}}async restoreSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async rotateSecret(e){let t={SecretId:e.SecretId};if(e.ClientRequestToken)t.ClientRequestToken=e.ClientRequestToken;if(e.RotationLambdaARN)t.RotationLambdaARN=e.RotationLambdaARN;if(e.RotationRules)t.RotationRules=e.RotationRules;if(e.RotateImmediately!==void 0)t.RotateImmediately=e.RotateImmediately;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId}}async cancelRotateSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async getResourcePolicy(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,ResourcePolicy:r.ResourcePolicy}}async putResourcePolicy(e){let t={SecretId:e.SecretId,ResourcePolicy:e.ResourcePolicy};if(e.BlockPublicPolicy!==void 0)t.BlockPublicPolicy=e.BlockPublicPolicy;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async deleteResourcePolicy(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async tagResource(e){let t={SecretId:e.SecretId,Tags:e.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async untagResource(e){let t={SecretId:e.SecretId,TagKeys:e.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async setString(e,t,r){try{let s=await this.putSecretValue({SecretId:e,SecretString:t});return{ARN:s.ARN,VersionId:s.VersionId}}catch(s){if(s.code==="ResourceNotFoundException"){let n=await this.createSecret({Name:e,SecretString:t,Description:r?.description,KmsKeyId:r?.kmsKeyId,Tags:r?.tags});return{ARN:n.ARN,VersionId:n.VersionId}}throw s}}async setJson(e,t,r){return this.setString(e,JSON.stringify(t),r)}async getString(e){return(await this.getSecretValue({SecretId:e})).SecretString}async getJson(e){let t=await this.getString(e);if(t)return JSON.parse(t);return}async listAll(){let e=[],t;do{let r=await this.listSecrets({NextToken:t});if(r.SecretList)e.push(...r.SecretList);t=r.NextToken}while(t);return e}parseSecret(e){return{ARN:e.ARN,Name:e.Name,Description:e.Description,KmsKeyId:e.KmsKeyId,RotationEnabled:e.RotationEnabled,RotationLambdaARN:e.RotationLambdaARN,RotationRules:e.RotationRules,LastRotatedDate:e.LastRotatedDate,LastChangedDate:e.LastChangedDate,LastAccessedDate:e.LastAccessedDate,DeletedDate:e.DeletedDate,NextRotationDate:e.NextRotationDate,Tags:e.Tags,SecretVersionsToStages:e.SecretVersionsToStages,CreatedDate:e.CreatedDate,PrimaryRegion:e.PrimaryRegion}}}function v(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let s=e.project.slug,n=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:s,region:n,stackName:ae(e,t),artifactBucket:oe(s,t),assetsBucket:ce(s,t)}}function He(e,t){let r=v(e,t),s=`${r.slug}-${t}`;return{region:r.region,slug:r.slug,stackName:r.stackName,functions:{http:`${s}-http`,queue:`${s}-queue`,cli:`${s}-cli`}}}async function D(e,t=8){let r;for(let s=0;s<t;s++)try{return await e()}catch(n){let i=n?.code||n?.name||"",a=String(n?.message||"");if(i==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(a)){r=n,await new Promise((o)=>setTimeout(o,3000));continue}throw n}throw r}var ye=(e,t)=>`releases/${e}/${t}/current.json`;async function J(e,t,r,s){try{return await e.getObjectJson(t,ye(r,s))}catch{return null}}async function Re(e,t,r,s,n){await e.putObjectJson(t,ye(r,s),n)}async function Ie(e,t){if(!e.secrets)return{};let r=new _(t),s={},n=Array.isArray(e.secrets)?e.secrets.map((i)=>({envName:i.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:i})):Object.entries(e.secrets).map(([i,a])=>({envName:i,secretId:a}));if(Array.isArray(e.secrets)){let i=new Map;for(let{envName:o,secretId:c}of n)i.set(o,[...i.get(o)??[],c]);let a=[...i.entries()].filter(([,o])=>o.length>1);if(a.length){let o=a.map(([c,u])=>`${c} ← ${u.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${o}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:i,secretId:a}of n){let c=(await r.getSecretValue({SecretId:a})).SecretString??"";try{let u=JSON.parse(c);if(u&&typeof u==="object"&&!Array.isArray(u)){for(let[p,d]of Object.entries(u))s[p]=String(d);continue}}catch{}s[i]=c}return s}function De(e,t){let r={},s=t.DbProxyEndpoint||t.DbEndpoint;if(s)r.DB_CONNECTION="mysql",r.DB_HOST=s,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function Y(e,t,r,s,n,i,a,o={}){let c=e.kind==="php"?pe({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:s,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...c,...o,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...a?{TSCLOUD_QUEUE:a,SQS_QUEUE:a}:{},...i?{ASSET_URL:i}:{},...e.env??{},...n}}function Pe(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*he(e){for(let t of Te(e)){let r=Se(e,t);if(ke(r).isDirectory())yield*he(r);else yield r}}async function $e(e,t,r,s,n=!1){let i=0;for(let a of he(r)){let o=Ee(r,a).replace(/\\/g,"/");if(!n&&o.split("/").some((c)=>c.startsWith(".")))continue;await e.putObject({bucket:t,key:`${s}/${o}`,body:be(a),contentType:Pe(a),cacheControl:"public, max-age=31536000, immutable"}),i++}return i}function Oe(e,t){let r=Object.entries(t).reduce((s,[n,i])=>s+Buffer.byteLength(`${n}=${i}`,"utf8"),0);if(r>4096){let s=Object.entries(t).map(([n,i])=>[n,Buffer.byteLength(`${n}=${i}`,"utf8")]).sort((n,i)=>i[1]-n[1]).slice(0,5).map(([n,i])=>`${n} (${i}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${s}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function F(e,t,r,s){Oe(t,r),await D(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let n=s.kind==="image"?{FunctionName:t,ImageUri:s.imageUri}:{FunctionName:t,S3Bucket:s.bucket,S3Key:s.key};await D(()=>e.updateFunctionCode(n)),await e.waitForFunctionActive(t,120)}async function z(e,t){let s=(await D(()=>e.publishVersion({FunctionName:t}))).Version;if(!s)throw Error(`publishVersion returned no version for ${t}`);return await D(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:s})),s}async function We(e,t,r={}){let s=v(e,t),{app:n,slug:i,region:a,stackName:o,artifactBucket:c}=s,u=r.projectRoot??process.cwd();M(`Deploying serverless app: ${i} (${t})`),R(`Stack: ${o}`),R(`Region: ${a}`);let p=new P(a),d=new Z(a),y=new b(a),C=n.kind==="php",A=n.packaging==="image",g=ge(n),k,N,h,H,L=[];if(A&&g.usesLayer&&g.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${g.kind}${g.kind==="node"?` ${g.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(A){m("Building + pushing container image");let{buildAndPushServerlessImage:l}=await import("./chunk-p70bc9yr.js"),f=await l({app:n,projectRoot:u,region:a,repository:`${i}-${t}`,skipBuild:r.skipBuild,onStep:(w)=>R(` ${w}`)});k=f.handlers,N={kind:"image",imageUri:f.imageUri},h=f.tag,L.push({ParameterKey:"ImageUri",ParameterValue:f.imageUri})}else{m("Packaging application");let l=C?fe({projectRoot:u,app:n,skipBuild:r.skipBuild,onStep:(T)=>R(` ${T}`)}):await ue({projectRoot:u,app:n,skipBuild:r.skipBuild,onStep:(T)=>R(` ${T}`)}),f=le(i,t,l.sha256);if(R(`Artifact: ${l.sha256.slice(0,12)} (${(l.zip.length/1024).toFixed(0)} KB)`),k=l.handlers,h=l.sha256,g.usesLayer){let T=g.layerEnvVar?process.env[g.layerEnvVar]:void 0;if(H=n.layers??(T?[T]:void 0),!H?.length){let Ce=g.layerKind==="php"?"serverless:build-php-layer":g.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${g.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${g.layerEnvVar} env var (build one with \`cloud ${Ce}\`)${g.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await p.bucketExists(c))m(`Creating artifact bucket ${c}`),await p.createBucket(c);if(await p.headObject(c,f).then((T)=>T!==null).catch(()=>!1))R("Artifact already uploaded — reusing");else m("Uploading artifact"),await p.putObject({bucket:c,key:f,body:l.zip,contentType:"application/zip"});N={kind:"zip",bucket:c,key:f},L.push({ParameterKey:"ArtifactBucket",ParameterValue:c},{ParameterKey:"ArtifactKey",ParameterValue:f})}let S=me({config:e,environment:t,app:n,handlers:k,runtimeLayers:H}),ee=JSON.stringify(S.template),te=["CAPABILITY_NAMED_IAM"],O=await d.describeStacks({stackName:o}).then((l)=>l.Stacks[0]?.StackStatus).catch(()=>{return}),q=O!==void 0;if(O&&/DELETE_IN_PROGRESS/.test(O))m("Waiting for an in-progress stack delete to finish"),await d.waitForStack(o,"stack-delete-complete").catch(()=>{}),q=!1;else if(O&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(O))m(`Deleting unusable stack (status ${O}) before recreate`),await d.deleteStack(o),await d.waitForStack(o,"stack-delete-complete").catch(()=>{}),q=!1;m(q?"Updating infrastructure stack":"Creating infrastructure stack");try{if(q)await d.updateStack({stackName:o,templateBody:ee,parameters:L,capabilities:te}),await d.waitForStack(o,"stack-update-complete");else await d.createStack({stackName:o,templateBody:ee,parameters:L,capabilities:te,onFailure:"DELETE"}),await d.waitForStack(o,"stack-create-complete")}catch(l){if(/No updates are to be performed/i.test(String(l?.message)))R("No infrastructure changes");else throw l}let W=await d.getStackOutputs(o).catch(()=>({})),E;if(n.assets){let l=Se(u,n.assets);if(Ae(l)){let f=n.assetDomain||W.AssetsCdnDomain;E=f?`https://${f}/${h}`:void 0,m(`Syncing assets from ${n.assets}`);let w=await $e(p,s.assetsBucket,l,h,n.dotFilesAsAssets);R(`Uploaded ${w} asset(s)${E?` → ${E}`:""}`)}else U(`Assets directory not found: ${l}`)}m("Resolving secrets");let B=await Ie(n,a);if(n.database?.connection==="aurora-serverless")try{let f=await new _(a).getSecretValue({SecretId:`${i}/${t}/db`}),w=JSON.parse(f.SecretString??"{}");if(w.username)B.DB_USERNAME=w.username;if(w.password)B.DB_PASSWORD=w.password}catch(l){U(`Could not resolve Aurora DB credentials: ${l.message}`)}if(!await p.bucketExists(c))await p.createBucket(c);let K=await J(p,c,i,t),I={},X=S.queueNames[0],G=De(n,W);if(m("Activating functions"),I.http=Y(n,s,t,"http",B,E,X,G),await F(y,S.functionNames.http,I.http,N),I.cli=Y(n,s,t,"cli",B,E,X,G),await F(y,S.functionNames.cli,I.cli,N),S.queueNames.length)I.queue=Y(n,s,t,"queue",B,E,X,G),await F(y,S.functionNames.queue,I.queue,N);let re=(n.provisionedConcurrency??0)>0,j={};if(re){if(m("Publishing versions + flipping live alias"),j.http=await z(y,S.functionNames.http),j.cli=await z(y,S.functionNames.cli),S.queueNames.length)j.queue=await z(y,S.functionNames.queue)}if(await Re(p,c,i,t,{sha:h,code:N,previousSha:K?.sha,previousCode:K?.code,previousFunctionEnv:K?.functionEnv,...re?{functionVersions:j,previousFunctionVersions:K?.functionVersions}:{},functionEnv:I,functionNames:{http:S.functionNames.http,cli:S.functionNames.cli,...S.queueNames.length?{queue:S.functionNames.queue}:{}},assetUrl:E,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&n.deploy?.length){m("Running deploy hooks");for(let l of n.deploy){R(` deploy: ${l}`);let f=await y.invoke({FunctionName:S.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:l},LogType:"Tail"});if(f.FunctionError)throw ne("Deploy hook failed — the new build is ALREADY LIVE."),R(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${l}): ${f.Payload}`)}}let x=W.HttpApiEndpoint;if(!r.skipHealthCheck&&x){m("Health check");try{let l=await fetch(x,{method:"GET"});R(`GET ${x} → ${l.status}`)}catch(l){U(`Health check could not reach ${x}: ${l.message}`)}}ie(["Serverless deploy complete","",x?`URL: ${x}`:"",`Stack: ${o}`,`Build: ${h.slice(0,12)}`].filter(Boolean).join(`
2
- `),"green")}async function Xe(e,t){let r=v(e,t),s=new P(r.region),n=new b(r.region),i=await J(s,r.artifactBucket,r.slug,t);if(!i)throw Error("No previous release to redeploy. Run a full deploy first.");M(`Redeploying ${r.slug} (${t}) — build ${i.sha.slice(0,12)}`);for(let[a,o]of Object.entries(i.functionNames)){if(!o)continue;m(`Re-activating ${a} (${o})`),await F(n,o,i.functionEnv[a]??{},i.code);let c=i.functionVersions?.[a];if(c)await D(()=>n.updateAlias({FunctionName:o,Name:"live",FunctionVersion:c}))}V("Redeploy complete")}async function Ge(e,t){let r=v(e,t),s=new P(r.region),n=new b(r.region),i=await J(s,r.artifactBucket,r.slug,t);if(!i?.previousCode)throw Error("No previous release to roll back to.");M(`Rolling back ${r.slug} (${t}) → ${i.previousSha?.slice(0,12)}`);for(let[a,o]of Object.entries(i.functionNames)){if(!o)continue;m(`Restoring ${a} (${o})`);let c=i.previousFunctionEnv?.[a]??i.functionEnv[a]??{};await F(n,o,c,i.previousCode);let u=i.previousFunctionVersions?.[a];if(u)await D(()=>n.updateAlias({FunctionName:o,Name:"live",FunctionVersion:u}))}await Re(s,r.artifactBucket,r.slug,t,{...i,sha:i.previousSha??i.sha,code:i.previousCode,functionEnv:i.previousFunctionEnv??i.functionEnv,functionVersions:i.previousFunctionVersions??i.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),V("Rollback complete")}async function Ye(e,t,r,s){let n=v(e,t),i=new b(n.region),a=`${n.slug}-${t}-http`,c={...(await i.getFunction(a)).Configuration?.Environment?.Variables??{}};if(c.MAINTENANCE_MODE=r?"1":"0",r&&s)c.MAINTENANCE_BYPASS_SECRET=s;if(!r)delete c.MAINTENANCE_BYPASS_SECRET;if(await D(()=>i.updateFunctionConfiguration({FunctionName:a,Environment:{Variables:c}})),(n.app.provisionedConcurrency??0)>0)await i.waitForFunctionActive(a,120),await z(i,a);V(r?"Application is now in maintenance mode (503)":"Application is live")}async function xe(e,t,r){let s=v(e,t),n=new b(s.region),i=`${s.slug}-${t}-cli`,a=await n.invoke({FunctionName:i,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"});if(a.FunctionError)throw Error(`Command failed: ${a.Payload}`);return a.Payload??""}var ve=(e,t)=>`commands/${e}/${t}/history.json`,Ve=50;async function Ne(e,t,r,s){try{return(await e.getObjectJson(t,ve(r,s)))?.records??[]}catch{return[]}}async function Qe(e,t,r){let s=v(e,t),n=new b(s.region),i=`${s.slug}-${t}-cli`,a=await n.invoke({FunctionName:i,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"}),o=a.Payload??"",c=a.FunctionError?"error":"ok",u=-1;try{let p=new P(s.region);if(await p.bucketExists(s.artifactBucket)){let d=await Ne(p,s.artifactBucket,s.slug,t);u=d.reduce((y,C)=>Math.max(y,C.id),0)+1,d.push({id:u,command:r,timestamp:new Date().toISOString(),status:c,output:o.slice(0,4000)}),await p.putObjectJson(s.artifactBucket,ve(s.slug,t),{records:d.slice(-Ve)})}}catch{}if(a.FunctionError)throw Error(`Command failed${u>0?` (#${u})`:""}: ${o}`);return{id:u,status:c,output:o}}async function Be(e,t){let r=v(e,t),s=new P(r.region);return Ne(s,r.artifactBucket,r.slug,t)}async function Ze(e,t,r){let s=await Be(e,t);if(!s.length)return;return r==null?s[s.length-1]:s.find((n)=>n.id===r)}async function et(e,t,r){let s=Buffer.from(r,"utf-8").toString("base64");return xe(e,t,`tscloud:db-query --sql-base64=${s}`)}async function tt(e,t){let r=v(e,t),s=new Z(r.region),n=new b(r.region),i=new P(r.region),a="not deployed",o={};try{let{Stacks:A}=await s.describeStacks({stackName:r.stackName});a=A?.[0]?.StackStatus??a;for(let g of A?.[0]?.Outputs??[])if(g.OutputKey)o[g.OutputKey]=g.OutputValue??""}catch{}let c=de(r.app,r.slug,t),u=r.app.provisionedConcurrency??0,p=["http","cli",...c.length?["queue"]:[]],d=`${r.slug}-${t}`,y=[];for(let A of p){let g=`${d}-${A}`,k={mode:A,name:g,version:"$LATEST"};if(u>0){let N=await n.getAlias(g,"live").catch(()=>null);if(N?.FunctionVersion){k.version=N.FunctionVersion;let h=await n.getProvisionedConcurrencyConfig(g,"live").catch(()=>null);if(h)k.provisioned={status:h.Status??"-",allocated:h.AllocatedProvisionedConcurrentExecutions??0,requested:h.RequestedProvisionedConcurrentExecutions??0}}}y.push(k)}let C=await J(i,r.artifactBucket,r.slug,t).catch(()=>null);return{slug:r.slug,environment:t,region:r.region,stackStatus:a,endpoint:o.HttpApiEndpoint,assetUrl:C?.assetUrl,scheduler:r.app.scheduler??"on",queues:c,provisionedConcurrency:u,functions:y,lastRelease:C?{sha:C.sha,timestamp:C.timestamp}:void 0}}function we(e,t){return`${e}-${t}-db`}async function rt(e,t,r,s){let n=v(e,t);if(n.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:i}=await import("./chunk-tvz9c388.js"),a=new i(n.region),o=we(n.slug,t);m(`Scaling ${o} → ${r}–${s} ACUs`),await a.modifyDBCluster({DBClusterIdentifier:o,ServerlessV2ScalingConfiguration:{MinCapacity:r,MaxCapacity:s},ApplyImmediately:!0}),V(`Scaling applied to ${o} (takes effect shortly).`)}async function st(e,t,r){let s=v(e,t);if(s.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!r.toTime&&!r.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:n}=await import("./chunk-tvz9c388.js"),i=new n(s.region),a=we(s.slug,t),o=r.latest?"latest":r.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),c=r.target??`${a}-restore-${o}`;m(`Restoring ${a} → new cluster ${c} (${r.latest?"latest restorable time":r.toTime.toISOString()})`),await i.restoreDBClusterToPointInTime({DBClusterIdentifier:c,SourceDBClusterIdentifier:a,RestoreToTime:r.toTime,UseLatestRestorableTime:r.latest}),m("Waiting for the restored cluster to be ready");for(let u=0;u<120;u++){let{DBClusters:p}=await i.describeDBClusters({DBClusterIdentifier:c}),d=p?.[0]?.Status;if(d&&d!=="creating")break;await new Promise((y)=>setTimeout(y,15000))}return m("Adding a writer instance"),await i.createDBInstance({DBInstanceIdentifier:`${c}-1`,DBClusterIdentifier:c,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),V(`Restore complete → cluster ${c} with writer ${c}-1. Point an env's database at it once available.`),c}
3
- export{_ as Id,He as Jd,Ie as Kd,De as Ld,Y as Md,Oe as Nd,We as Od,Xe as Pd,Ge as Qd,Ye as Rd,xe as Sd,Qe as Td,Be as Ud,Ze as Vd,et as Wd,tt as Xd,rt as Yd,st as Zd};
@@ -1,2 +0,0 @@
1
- import{Ig as O}from"./chunk-9a88fp00.js";import{Pg as E}from"./chunk-6tfwm33r.js";import{Xo as I,ap as U,bp as j,io as R,ko as b,uo as A}from"./chunk-4q6tad44.js";import{execFileSync as B}from"node:child_process";import{mkdirSync as v,mkdtempSync as q,rmSync as N,writeFileSync as m}from"node:fs";import{tmpdir as F}from"node:os";import{dirname as T,join as i}from"node:path";function C(n,e){for(let t of e){let c=i(n,t.name);v(T(c),{recursive:!0}),m(c,t.data,t.mode?{mode:t.mode}:void 0)}}async function Q(n){let{app:e,projectRoot:t,region:c,repository:d}=n,w=e.architecture??"x86_64",P=w==="arm64"?"linux/arm64":"linux/amd64",z=e.kind==="php",o=n.onStep??(()=>{}),s=q(i(F(),"tscloud-img-"));try{let g=i(s,"app");v(g,{recursive:!0});let h,f;if(z){U({projectRoot:t,app:e,skipBuild:n.skipBuild,onStep:o}),o("staging application tree");let r=j(t);C(g,r),C(i(s,"runtime"),I().map((p)=>({name:p.path,data:p.contents,mode:p.mode})));let S=e.handlers?.http??"public/index.php";h={http:S,queue:e.handlers?.queue??S,cli:e.handlers?.cli??S},f=R(r.map((p)=>`${p.name}:${p.data.length}`).join("|"))}else{o("bundling application");let r=await b({projectRoot:t,app:e,skipBuild:n.skipBuild,onStep:o});m(i(g,"index.mjs"),r.bundle),h=r.handlers,f=r.sha256}let x=f.slice(0,16);m(i(s,"Dockerfile"),A({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:w}));let y=new O(c),a;try{a=(await y.describeRepositories({repositoryNames:[d]})).repositories?.[0]?.repositoryUri??""}catch{a=""}if(!a)o(`creating ECR repository ${d}`),a=(await y.createRepository({repositoryName:d,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!a)throw Error(`could not resolve ECR repository URI for ${d}`);let u=`${a}:${x}`;o("docker build"),B("docker",["build","--platform",P,"--provenance=false","--sbom=false","-t",u,s],{stdio:"inherit"}),o("ecr auth + push");let l=(await y.getAuthorizationToken()).authorizationData?.[0];if(!l?.authorizationToken||!l.proxyEndpoint)throw Error("failed to get an ECR authorization token");let D=l.proxyEndpoint.replace(/^https?:\/\//,""),k=i(s,".docker");return v(k,{recursive:!0}),m(i(k,"config.json"),JSON.stringify({auths:{[D]:{auth:l.authorizationToken}}})),B("docker",["push",u],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:k}}),E(`Image: ${u}`),{imageUri:u,tag:x,handlers:h}}finally{N(s,{recursive:!0,force:!0})}}
2
- export{Q as Hg};
@@ -1,2 +0,0 @@
1
- import{og as y}from"./chunk-e5ab5twy.js";import{dh as k}from"./chunk-ja1vjdn1.js";var I=new Set(["A","AAAA","CNAME"]);function E(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function N(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,s=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,s))}class R{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let n=1;n<=8;n+=1){let s,o=new AbortController,i=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{s=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(c){if(r=c,n===8)throw c;await N(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!E(s.status)||n===8)throw r;await N(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!E(0,a.message)||n===8)throw r;await N(n,s);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!R.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${s.message??"unknown provider error"}`];let o=[];for(let i of s.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)o.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return!0;return s.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===n&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)s.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)s.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)s.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,s);if(R.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.listRecords(e,t.type);if(s.success){let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(o?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,i),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let n=this.getSubdomain(t.name,r),s=await this.listRecords(e);if(!s.success)return{success:!1,message:"Failed to list records"};let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/dns/getNS/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/dns/updateNS/${r}`,{ns:t}),!0}catch{return!1}}}class D{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let n=`${this.baseUrl}${t}`,s={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let i=await fetch(n,o);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;return s}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),o=s.filter((i)=>i.data!==t.content);if(o.length===s.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var O="https://api.cloudflare.com/client/v4",S="[ts-cloud]";class w{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let n=`${O}${t}`,s={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:s};if(r)o.body=JSON.stringify(r);let a=await(await fetch(n,o)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let s=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!s.result||s.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=s.result[0].id;return this.zoneCache.set(r,o),{id:o,name:s.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},s=r??e.proxied;if(s!==void 0&&I.has(e.type)){if(n.proxied=s,s)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let o=z(e);if(o)n.data=o,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),n=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??o?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let i=o.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let s=[],o=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${o}`);if(s.push(...a.result||[]),a.result_info)i=o<a.result_info.total_pages,o++;else i=!1}return{success:!0,records:s.map((a)=>this.fromCloudflareRecord(a))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let s=await this.getZoneDetails(r);if(s)return{...s,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(o){let i=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(i))throw o;let a=await this.getZoneDetails(r);if(!a)throw o;return{...a,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),n=new Set;for(let s of r.result||[]){if(s.status!=="active")continue;for(let o of s.hosts||[])n.add(o.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,s=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(o.result&&o.result.length>0)return o.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),s=n.id,o=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${s}/dns_records/${a.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),n={};for(let s of r.result||[])n[s.id]=s.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),s=[],o=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&T(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),s.push({id:i,from:c,to:a})}catch(d){o.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:s,failed:o}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let n=await this.getZoneId(e),o=(await this.getPhaseRules(e,t)).filter((c)=>!(c.description||"").startsWith(S)),i=r.map((c)=>({...c,description:c.description?.startsWith(S)?c.description:`${S} ${c.description||t}`})),a=[...o,...i].map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}function T(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((s,o)=>T(s,t[o]))}let r=e,n=t;return Object.keys(n).every((s)=>T(r[s],n[s]))}function z(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:x(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,s,o]=r.slice(0,3).map(Number);if(![n,s,o].every(Number.isFinite))return null;return{priority:n,weight:s,port:o,target:x(r.slice(3).join(" "))}}function x(e){return e.replace(/\.$/,"")}var L=new Set(["A","AAAA","CNAME","ALIAS"]);function v(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function p(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function f(e){return e.replace(/\.$/,"").toLowerCase()}function V(e,t){let r=f(t),n=(e??"@").trim();if(!n||n==="@")return r;let s=f(n);if(s===r||s.endsWith(`.${r}`))return s;return`${s}.${r}`}function U(e,t){return e.map((r)=>({...r,name:V(r.name,t),proxied:r.proxied??!1}))}function q(e,t){if(e.type!==t.type)return!1;if(f(e.name)!==f(t.name))return!1;if(L.has(t.type))return!0;if(t.type==="TXT"){let r=v(t.content);if(r)return v(p(e.content))===r;return p(e.content)===p(t.content)}return p(e.content)===p(t.content)}function j(e,t){if(p(e.content)!==p(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function F(e){let{provider:t,zone:r,records:n}=e,s={outcomes:[],warnings:[]};if(n.length===0)return s;let o=await t.listRecords(r);if(!o.success)return s.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),s;let i=o.records;for(let a of n){let c=i.filter((u)=>q(u,a));if(c.length>0&&c.every((u)=>j(u,a))){s.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},m=a.type==="TXT"&&v(a.content)!==void 0;if(m)for(let u of c){let b=await t.deleteRecord(r,{name:u.name,type:u.type,content:u.content});if(!b.success)s.warnings.push(`could not remove superseded ${u.type} at ${u.name}: ${b.message||"unknown error"}`)}let g=m||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(g.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:g.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>f(d.name)));for(let d of c){let m=new Set(n.filter((u)=>u.type===a&&f(u.name)===d).map((u)=>p(u.content).toLowerCase())),g=i.filter((u)=>u.type===a&&f(u.name)===d&&!m.has(p(u.content).toLowerCase()));for(let u of g)s.warnings.push(`${d} has an undeclared ${a} record (${u.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class A{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new y(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let n=await this.client.findHostedZoneForDomain(e);if(n){let s=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,s),s}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),s=t.content;if(t.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(t.type==="MX"&&t.priority!==void 0)s=`${t.priority} ${s}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:s}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),s=[];for(let o of n.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let i of o.ResourceRecords||[]){let a=i.Value,c;if(o.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(o.Type==="TXT"&&a.startsWith('"')&&a.endsWith('"'))a=a.slice(1,-1);s.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:a,ttl:o.TTL,priority:c})}}return{success:!0,records:s}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:y.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=y.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}async function G(e,t){let r=[],n,s;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:s,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(n=o.NextRecordName,s=o.NextRecordType,!n)break}return r}function l(e){return e.replace(/\.$/,"").toLowerCase()}function M(e){return e.replace(/\.$/,"")}function C(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${M(e.content)}`;return M(e.content)}function W(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function H(e,t){let r=l(t),n=[],s=[],o=[],i=new Set;for(let a of e){let c=l(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){s.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){s.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let m=l(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:m,ttl:300,translatedFrom:`${d} ALIAS → ${m}`}),a.AliasTarget.EvaluateTargetHealth)o.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let m of a.ResourceRecords||[]){let g=K(c,d,m.Value,a.TTL);if("reason"in g){s.push({name:c,type:d,reason:g.reason}),o.push(`${d} ${c}: ${g.reason}`);continue}n.push(g)}}return{zone:r,records:n,skipped:s,warnings:o}}function K(e,t,r,n){let s={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...s,type:t==="PTR"?"CNAME":t,content:l(r)};case"TXT":return{...s,type:"TXT",content:W(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:l(i.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=o.slice(0,3).map(Number);return{...s,type:"SRV",content:l(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:l(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var X=new Set(["TXT","MX","SRV","NS","CAA"]);async function B(e,t){let r=[],n=[],s=new Set;try{let o=await e.listRecords(t.zone);for(let i of o.records||[])s.add(`${l(i.name)}|${i.type}|${C(i)}`)}catch{}for(let o of t.records){let i={...o,proxied:!1},a=`${l(o.name)}|${o.type}|${C(o)}`;if(!X.has(o.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(o);else n.push({record:o,message:d.message||"unknown provider error"});continue}if(s.has(a)){r.push(o);continue}let c=await e.createRecord(t.zone,i);if(c.success)s.add(a),r.push(o);else n.push({record:o,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Y(e,t){let r=await e.listRecords(t.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${l(i.name)}|${i.type}`,c=o.get(a)??[];c.push(C(i)),o.set(a,c)}for(let i of t.records){let a=o.get(`${l(i.name)}|${i.type}`),c=C(i);if(a?.some((d)=>d===c))n.push(i);else s.push({record:i,found:a?.join(", ")})}return{matched:n,missing:s,ok:s.length===0}}class _{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new P(t),"provider"in e)this.dnsProvider=h(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:s=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let i=await this.acm.getDnsValidationRecords(o);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(o,s*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,records:s.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],s=await this.acm.getDnsValidationRecords(t);for(let o of s){let i=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!i.success)n.push(`Failed to delete record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:s}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let i=o.SubjectAlternativeNames||[o.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:n,maxWaitMinutes:s})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:s=[],waitForValidation:o=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...s),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function h(e){switch(e.provider){case"route53":return new A(e.region,e.hostedZoneId);case"porkbun":return new R(e.apiKey,e.secretKey);case"godaddy":return new D(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new w(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class Z{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,n=process.env.GODADDY_API_SECRET;if(r&&n){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,o)}let s=process.env.CLOUDFLARE_API_TOKEN;if(s)this.addCloudflare(s,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((s)=>s.provider===e);if(!r)return null;let n=h(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=h(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>h(e))}}var ye=new Z;class P{client;region;constructor(e="us-east-1"){this.client=new k,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((n)=>({CertificateArn:n.CertificateArn,DomainName:n.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((n)=>n.DomainName===e||n.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let n=0;n<t;n++){let s=await this.describeCertificate({CertificateArn:e});if(s.Status==="ISSUED")return s;if(s.Status==="FAILED"||s.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let n=r.DomainName.slice(2),s=t.split("."),o=n.split(".");if(s.slice(-o.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}}return!1}}class J{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new P(e),this.route53=new y,t&&t.provider!=="route53")this.dnsProvider=h(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(s){if(!await this.acm.waitForCertificateValidation(i,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let i=n||s[0]?.domainName;for(let a of s){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});o.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of s){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});o.push({...i,changeId:a.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,s=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=n||s[0]?.domainName;for(let i of s)try{await this.dnsProvider.deleteRecord(o,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let o of s)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
- export{R as hd,D as id,w as jd,U as kd,F as ld,A as md,G as nd,H as od,B as pd,Y as qd,P as rd,J as sd,_ as td,h as ud,Z as vd};
@@ -1,34 +0,0 @@
1
- import{og as P}from"./chunk-e5ab5twy.js";import{qg as A}from"./chunk-btsyjhk7.js";import{dh as d}from"./chunk-ja1vjdn1.js";import{op as y}from"./chunk-ehc63fvs.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-edvvx3hg.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 kg,p as lg,h as mg,M as ng};
@@ -1 +0,0 @@
1
- import{jg as a}from"./chunk-a7w13qfm.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as CloudFormationClient};
@@ -1 +0,0 @@
1
- import{Hg as a}from"./chunk-mcr0r4at.js";import"./chunk-9a88fp00.js";import"./chunk-6tfwm33r.js";import"./chunk-ja1vjdn1.js";import"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{a as buildAndPushServerlessImage};
@@ -1,4 +0,0 @@
1
- import{dh as d}from"./chunk-ja1vjdn1.js";class u{client;region;constructor(e="us-east-1"){this.region=e,this.client=new d}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,a)=>{t[`InstanceId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeInstancesResponse||s;return{Reservations:this.parseReservations(n.reservationSet?.item),NextToken:n.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let s={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)s.Latest="true";let n=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()}),r=n.GetConsoleOutputResponse||n;return{InstanceId:r.instanceId,Output:r.output,Timestamp:r.timestamp}}async getConsoleOutputDecoded(e,t){let s=await this.getConsoleOutput(e,t?.latest);if(!s.Output)return"No console output available yet";let n=Buffer.from(s.Output,"base64").toString("utf-8");if(t?.tailLines)return n.split(`
2
- `).slice(-t.tailLines).join(`
3
- `);return n}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(s.instanceStatusSet?.item).map((n)=>({InstanceId:n.instanceId,InstanceState:n.instanceState?{Code:Number.parseInt(n.instanceState.code),Name:n.instanceState.name}:void 0,InstanceStatus:n.instanceStatus?{Status:n.instanceStatus.status,Details:this.parseArray(n.instanceStatus.details?.item).map((r)=>({Name:r.name,Status:r.status}))}:void 0,SystemStatus:n.systemStatus?{Status:n.systemStatus.status,Details:this.parseArray(n.systemStatus.details?.item).map((r)=>({Name:r.name,Status:r.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(s.instancesSet?.item).map((n)=>({InstanceId:n.instanceId,CurrentState:n.currentState?{Name:n.currentState.name}:void 0,PreviousState:n.previousState?{Name:n.previousState.name}:void 0}))}}async stopInstances(e,t){let s={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((r,a)=>{s[`InstanceId.${a+1}`]=r}),t)s.Force="true";let n=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()});return{StoppingInstances:this.parseArray(n.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((s,n)=>{t[`InstanceId.${n+1}`]=s}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(s.instancesSet?.item).map((n)=>({InstanceId:n.instanceId,CurrentState:n.currentState?{Name:n.currentState.name}:void 0,PreviousState:n.previousState?{Name:n.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(s.CreateImageResponse||s).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((n,r)=>{t[`VpcId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(s.vpcSet?.item).map((n)=>({VpcId:n.vpcId,CidrBlock:n.cidrBlock,State:n.state,DhcpOptionsId:n.dhcpOptionsId,InstanceTenancy:n.instanceTenancy,IsDefault:n.isDefault==="true",Tags:this.parseTags(n.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((n,r)=>{t[`SubnetId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(s.subnetSet?.item).map((n)=>({SubnetId:n.subnetId,VpcId:n.vpcId,CidrBlock:n.cidrBlock,AvailabilityZone:n.availabilityZone,AvailableIpAddressCount:Number.parseInt(n.availableIpAddressCount),State:n.state,MapPublicIpOnLaunch:n.mapPublicIpOnLaunch==="true",Tags:this.parseTags(n.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((n,r)=>{t[`GroupId.${r+1}`]=n});if(e?.GroupNames)e.GroupNames.forEach((n,r)=>{t[`GroupName.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(s.securityGroupInfo?.item).map((n)=>({GroupId:n.groupId,GroupName:n.groupName,Description:n.groupDescription,VpcId:n.vpcId,IpPermissions:this.parseIpPermissions(n.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(n.ipPermissionsEgress?.item),Tags:this.parseTags(n.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((n,r)=>{t[`InternetGatewayId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(s.internetGatewaySet?.item).map((n)=>({InternetGatewayId:n.internetGatewayId,Attachments:this.parseArray(n.attachmentSet?.item).map((r)=>({VpcId:r.vpcId,State:r.state})),Tags:this.parseTags(n.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((n,r)=>{t[`AllocationId.${r+1}`]=n});if(e?.PublicIps)e.PublicIps.forEach((n,r)=>{t[`PublicIp.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(s.addressesSet?.item).map((n)=>({PublicIp:n.publicIp,AllocationId:n.allocationId,AssociationId:n.associationId,InstanceId:n.instanceId,NetworkInterfaceId:n.networkInterfaceId,PrivateIpAddress:n.privateIpAddress,Domain:n.domain,Tags:this.parseTags(n.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((n,r)=>{t[`TagSpecification.${r+1}.ResourceType`]=n.ResourceType,n.Tags.forEach((a,i)=>{t[`TagSpecification.${r+1}.Tag.${i+1}.Key`]=a.Key,t[`TagSpecification.${r+1}.Tag.${i+1}.Value`]=a.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:s.allocationId,PublicIp:s.publicIp,Domain:s.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((s,n)=>{t[`ResourceId.${n+1}`]=s}),e.Tags.forEach((s,n)=>{t[`Tag.${n+1}.Key`]=s.Key,t[`Tag.${n+1}.Value`]=s.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,s){let n=s?.maxWaitMs||300000,r=s?.pollIntervalMs||5000,a=Date.now();while(Date.now()-a<n){let i;try{i=await this.getInstance(e)}catch{i=void 0}if(i?.State?.Name===t)return i;await new Promise((c)=>setTimeout(c,r))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((a,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=a.ResourceType,a.Tags.forEach((c,o)=>{t[`TagSpecification.${i+1}.Tag.${o+1}.Key`]=c.Key,t[`TagSpecification.${i+1}.Tag.${o+1}.Value`]=c.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=(s.CreateVpcResponse||s).vpc;return{Vpc:r?{VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((a,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=a.ResourceType,a.Tags.forEach((c,o)=>{t[`TagSpecification.${i+1}.Tag.${o+1}.Key`]=c.Key,t[`TagSpecification.${i+1}.Tag.${o+1}.Value`]=c.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=(s.CreateSubnetResponse||s).subnet;return{Subnet:r?{SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:r.availableIpAddressCount?Number.parseInt(r.availableIpAddressCount):void 0,State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(s.CreateSecurityGroupResponse||s).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((r,a)=>{t[`RouteTableId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeRouteTablesResponse||s;return{RouteTables:this.parseArray(n.routeTableSet?.item).map((r)=>({RouteTableId:r.routeTableId,VpcId:r.vpcId,Routes:this.parseArray(r.routeSet?.item).map((a)=>({DestinationCidrBlock:a.destinationCidrBlock,GatewayId:a.gatewayId,NatGatewayId:a.natGatewayId,State:a.state})),Associations:this.parseArray(r.associationSet?.item).map((a)=>({RouteTableAssociationId:a.routeTableAssociationId,SubnetId:a.subnetId,Main:a.main==="true"||a.main===!0})),Tags:this.parseTags(r.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((r,a)=>{t[`NetworkInterfaceId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeNetworkInterfacesResponse||s;return{NetworkInterfaces:this.parseArray(n.networkInterfaceSet?.item).map((r)=>({NetworkInterfaceId:r.networkInterfaceId,SubnetId:r.subnetId,VpcId:r.vpcId,Status:r.status,Attachment:r.attachment?{AttachmentId:r.attachment.attachmentId,InstanceId:r.attachment.instanceId,Status:r.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let s={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)s.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),s=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(s.regionInfo?.item).map((n)=>({RegionName:n.regionName,Endpoint:n.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((r,a)=>{t[`SecurityGroupId.${a+1}`]=r});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.RunInstancesResponse||s;return{Instances:this.parseInstances(n.instancesSet?.item||n.instancesSet)}}encodeIpPermissions(e,t){t.forEach((s,n)=>{let r=`IpPermissions.${n+1}`;if(s.IpProtocol!==void 0)e[`${r}.IpProtocol`]=s.IpProtocol;if(s.FromPort!==void 0)e[`${r}.FromPort`]=String(s.FromPort);if(s.ToPort!==void 0)e[`${r}.ToPort`]=String(s.ToPort);if(s.IpRanges)s.IpRanges.forEach((a,i)=>{if(a.CidrIp)e[`${r}.IpRanges.${i+1}.CidrIp`]=a.CidrIp;if(a.Description)e[`${r}.IpRanges.${i+1}.Description`]=a.Description});if(s.Ipv6Ranges)s.Ipv6Ranges.forEach((a,i)=>{if(a.CidrIpv6)e[`${r}.Ipv6Ranges.${i+1}.CidrIpv6`]=a.CidrIpv6;if(a.Description)e[`${r}.Ipv6Ranges.${i+1}.Description`]=a.Description});if(s.UserIdGroupPairs)s.UserIdGroupPairs.forEach((a,i)=>{if(a.GroupId)e[`${r}.Groups.${i+1}.GroupId`]=a.GroupId;if(a.UserId)e[`${r}.Groups.${i+1}.UserId`]=a.UserId;if(a.Description)e[`${r}.Groups.${i+1}.Description`]=a.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let s of this.parseArray(t?.ipv6AddressesSet?.item))if(s?.ipv6Address)return s.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((s)=>({GroupId:s.groupId,GroupName:s.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((s)=>({DeviceName:s.deviceName,Ebs:s.ebs?{VolumeId:s.ebs.volumeId,Status:s.ebs.status,AttachTime:s.ebs.attachTime,DeleteOnTermination:s.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((s)=>({CidrIp:s.cidrIp,Description:s.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((s)=>({CidrIpv6:s.cidrIpv6,Description:s.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((s)=>({GroupId:s.groupId,UserId:s.userId,Description:s.description}))}))}}
4
- export{u as kf};
@@ -1,2 +0,0 @@
1
- import{dh as n}from"./chunk-ja1vjdn1.js";class s{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new n(void 0,{profile:e})}async getCallerIdentity(){let t=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof t==="string"){let r=t.match(/<Account>(\d+)<\/Account>/),i=t.match(/<UserId>([^<]+)<\/UserId>/),c=t.match(/<Arn>([^<]+)<\/Arn>/);return{Account:r?.[1],UserId:i?.[1],Arn:c?.[1]}}let e=t?.GetCallerIdentityResponse?.GetCallerIdentityResult||t?.GetCallerIdentityResult;if(e)return{Account:String(e.Account),UserId:e.UserId,Arn:e.Arn};if(t?.Account)return{Account:String(t.Account),UserId:t.UserId,Arn:t.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}
2
- export{s as fd};
@@ -1,2 +0,0 @@
1
- function r(n){let t=new RegExp("[\\u007F-\\uFFFF]","g");return JSON.stringify(n).replace(t,(o)=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)}
2
- export{r as Xa};
@@ -1 +0,0 @@
1
- import{gd as a}from"./chunk-3aph4c1w.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as RDSClient};
@@ -1 +0,0 @@
1
- import{kf as a}from"./chunk-r6b3pq31.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as EC2Client};