@stacksjs/ts-cloud 0.9.3 → 0.9.4

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 (143) hide show
  1. package/dist/aws/index.js +1 -269
  2. package/dist/bin/chunk-00kg80qg.js +1 -0
  3. package/dist/bin/{chunk-hzqw8xm5.js → chunk-1k5kszjp.js} +1 -1
  4. package/dist/bin/{chunk-9v39615t.js → chunk-21e0mavm.js} +1 -1
  5. package/dist/bin/{chunk-waayf9ay.js → chunk-2empps47.js} +1 -1
  6. package/dist/bin/{chunk-14cwr6eh.js → chunk-3vqfexc4.js} +1 -1
  7. package/dist/bin/chunk-5ectjq0b.js +1 -0
  8. package/dist/bin/{chunk-b5gd39s8.js → chunk-5erkxpt7.js} +4 -4
  9. package/dist/bin/{chunk-41x17hw1.js → chunk-5mrtzemj.js} +1 -1
  10. package/dist/bin/{chunk-p8q9bq9g.js → chunk-5n9fmabb.js} +1 -1
  11. package/dist/bin/{chunk-gqf6jsmy.js → chunk-9knpg30y.js} +1 -1
  12. package/dist/bin/{chunk-r3kv0vm9.js → chunk-ddk4rt4j.js} +1 -1
  13. package/dist/bin/{chunk-avm7tnwe.js → chunk-e0rkrq70.js} +1 -1
  14. package/dist/bin/{chunk-ry030a6b.js → chunk-etrb03mt.js} +1 -1
  15. package/dist/bin/{chunk-8v7ddyvf.js → chunk-k9t9wvms.js} +1 -1
  16. package/dist/bin/{chunk-92mea34a.js → chunk-m7dgskt1.js} +1 -1
  17. package/dist/bin/{chunk-3r4fb59r.js → chunk-mz0wbbsj.js} +1 -1
  18. package/dist/bin/{chunk-b9qbp8j1.js → chunk-qk9qgepa.js} +1 -1
  19. package/dist/bin/chunk-rxcvf10f.js +7364 -0
  20. package/dist/bin/{chunk-r9hjwcj9.js → chunk-tga3hhwk.js} +1 -1
  21. package/dist/bin/{chunk-ynjvbphf.js → chunk-tx0tqq2k.js} +1 -1
  22. package/dist/bin/{chunk-57y1zxbf.js → chunk-vm3q5gf2.js} +1 -1
  23. package/dist/bin/{chunk-bz828v8q.js → chunk-y7s5r8y6.js} +1 -1
  24. package/dist/bin/{chunk-sgyffpgm.js → chunk-zmegvjp8.js} +1 -1
  25. package/dist/bin/cli.js +14 -14
  26. package/dist/bin/dashboard-server.js +1 -1
  27. package/dist/chunk-0ccta6z6.js +6 -0
  28. package/dist/chunk-0k1cs6pp.js +1 -0
  29. package/dist/chunk-1egjn203.js +704 -0
  30. package/dist/chunk-2wx29qga.js +5 -0
  31. package/dist/chunk-5m5rqmv7.js +1 -0
  32. package/dist/chunk-8ea5022g.js +114 -0
  33. package/dist/chunk-8xqn3c0w.js +2 -0
  34. package/dist/chunk-b4esxhmw.js +2 -0
  35. package/dist/chunk-b8e5wzwn.js +44 -0
  36. package/dist/chunk-bggt4n6e.js +2 -0
  37. package/dist/chunk-cwkg37rs.js +37 -0
  38. package/dist/chunk-dskvqt67.js +7355 -0
  39. package/dist/chunk-gahsdmxf.js +1617 -0
  40. package/dist/chunk-gnv3r2jg.js +1 -0
  41. package/dist/chunk-hg3c48cp.js +34 -0
  42. package/dist/chunk-m5azeva3.js +2 -0
  43. package/dist/chunk-r3qf56b3.js +92 -0
  44. package/dist/chunk-sdqa9ghv.js +141 -0
  45. package/dist/chunk-svrvvcm7.js +1 -0
  46. package/dist/chunk-v0p3hpc3.js +60 -0
  47. package/dist/chunk-wdzjbecg.js +50 -0
  48. package/dist/chunk-ww8k3g7j.js +1 -0
  49. package/dist/chunk-xmqfc62w.js +1 -0
  50. package/dist/chunk-xrebj679.js +435 -0
  51. package/dist/chunk-xt3s24vr.js +2 -0
  52. package/dist/chunk-y21zk0pn.js +4 -0
  53. package/dist/deploy/index.js +1 -168
  54. package/dist/dns/index.js +1 -41
  55. package/dist/drivers/index.js +1 -154
  56. package/dist/index.js +100 -6129
  57. package/dist/protection/index.js +1 -89
  58. package/dist/push/index.js +1 -509
  59. package/dist/spend/index.js +1 -173
  60. package/dist/ui/404.html +1 -1
  61. package/dist/ui/accept-invitation.html +1 -1
  62. package/dist/ui/access-denied.html +1 -1
  63. package/dist/ui/account/automation.html +6 -6
  64. package/dist/ui/account/security.html +2 -2
  65. package/dist/ui/applications/compose.html +6 -6
  66. package/dist/ui/applications/new.html +2 -2
  67. package/dist/ui/data/backups.html +5 -5
  68. package/dist/ui/data/services.html +5 -5
  69. package/dist/ui/data/volumes.html +6 -6
  70. package/dist/ui/index.html +6 -6
  71. package/dist/ui/infrastructure/topology.html +5 -5
  72. package/dist/ui/integrations.html +1 -1
  73. package/dist/ui/operations/alerts.html +5 -5
  74. package/dist/ui/operations/configuration.html +5 -5
  75. package/dist/ui/operations/jobs.html +5 -5
  76. package/dist/ui/operations/maintenance.html +5 -5
  77. package/dist/ui/operations/observability.html +6 -6
  78. package/dist/ui/operations/previews.html +6 -6
  79. package/dist/ui/operations/queue.html +6 -6
  80. package/dist/ui/operations/regions.html +6 -6
  81. package/dist/ui/operations/releases.html +6 -6
  82. package/dist/ui/operations/spend.html +6 -6
  83. package/dist/ui/operations/workloads.html +6 -6
  84. package/dist/ui/security.html +1 -1
  85. package/dist/ui/server/actions.html +5 -5
  86. package/dist/ui/server/activity.html +1 -1
  87. package/dist/ui/server/capacity.html +6 -6
  88. package/dist/ui/server/database.html +6 -6
  89. package/dist/ui/server/deployments.html +6 -6
  90. package/dist/ui/server/diagnostics.html +2 -2
  91. package/dist/ui/server/firewall.html +6 -6
  92. package/dist/ui/server/fleet.html +6 -6
  93. package/dist/ui/server/logs.html +6 -6
  94. package/dist/ui/server/metrics.html +6 -6
  95. package/dist/ui/server/security.html +2 -2
  96. package/dist/ui/server/services.html +1 -1
  97. package/dist/ui/server/sites.html +6 -6
  98. package/dist/ui/server/ssh-keys.html +6 -6
  99. package/dist/ui/server/team.html +6 -6
  100. package/dist/ui/server/terminal.html +1 -1
  101. package/dist/ui/serverless/alarms.html +5 -5
  102. package/dist/ui/serverless/assets.html +2 -2
  103. package/dist/ui/serverless/cost.html +1 -1
  104. package/dist/ui/serverless/data.html +6 -6
  105. package/dist/ui/serverless/deployments.html +2 -2
  106. package/dist/ui/serverless/firewall.html +1 -1
  107. package/dist/ui/serverless/functions.html +6 -6
  108. package/dist/ui/serverless/logs.html +6 -6
  109. package/dist/ui/serverless/metrics.html +2 -2
  110. package/dist/ui/serverless/queues.html +6 -6
  111. package/dist/ui/serverless/secrets.html +6 -6
  112. package/dist/ui/serverless/traces.html +6 -6
  113. package/dist/ui/serverless.html +5 -5
  114. package/package.json +3 -3
  115. package/dist/bin/chunk-jpjamjey.js +0 -6935
  116. package/dist/bin/chunk-m2zwtapr.js +0 -1
  117. package/dist/bin/chunk-rtczra13.js +0 -1
  118. package/dist/chunk-01d86gt1.js +0 -1324
  119. package/dist/chunk-050r7ycy.js +0 -46516
  120. package/dist/chunk-1c8dbv57.js +0 -7278
  121. package/dist/chunk-29rse4p1.js +0 -12203
  122. package/dist/chunk-32e7ya18.js +0 -642
  123. package/dist/chunk-4cjrg98a.js +0 -597
  124. package/dist/chunk-50jpda9q.js +0 -371
  125. package/dist/chunk-6a1t7fnq.js +0 -12121
  126. package/dist/chunk-728jvrr0.js +0 -1701
  127. package/dist/chunk-7m60qnc8.js +0 -1762
  128. package/dist/chunk-aa2dkn7b.js +0 -205
  129. package/dist/chunk-d48vtdj4.js +0 -433
  130. package/dist/chunk-f55nkpvb.js +0 -8
  131. package/dist/chunk-fgk8cqew.js +0 -152
  132. package/dist/chunk-he9a874b.js +0 -769
  133. package/dist/chunk-k2yyatfw.js +0 -10
  134. package/dist/chunk-k4px0bnv.js +0 -23
  135. package/dist/chunk-nsgqsmrh.js +0 -1779
  136. package/dist/chunk-q0st3se8.js +0 -42033
  137. package/dist/chunk-qr803fye.js +0 -2122
  138. package/dist/chunk-rds0sy87.js +0 -1771
  139. package/dist/chunk-ttz2ra5j.js +0 -12
  140. package/dist/chunk-v0bahtg2.js +0 -4
  141. package/dist/chunk-va2yd85b.js +0 -200
  142. package/dist/chunk-x9s0cqfx.js +0 -13
  143. package/dist/chunk-zqtpg06c.js +0 -1752
@@ -0,0 +1 @@
1
+ import{ml as L}from"./chunk-b8e5wzwn.js";var _="\x00";function X(R,E){if(R==="*"||R==="**")return!0;let D=R.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${D}$`).test(E)}function A(R,E){if(R.startsWith("*.")){let D=R.slice(1);return E.endsWith(D)&&E.length>D.length}return R===E}function W(R,E){if(R.enabled===!1)return!1;if(R.methods?.length&&!R.methods.some((D)=>D.toUpperCase()===E.method.toUpperCase()))return!1;if(R.path&&!X(R.path,E.path))return!1;if(R.host&&!A(R.host,E.host??""))return!1;return!0}function Z(R,E){let D=R.key??{source:"ip"},F=D.fallbackToIp!==!1,H;if(D.source==="ip")H=E.ip;else if(D.source==="global")H="global";else if(D.source==="host")H=E.host??"";else if(D.source==="path")H=E.path;else if(D.source==="header")H=D.name?E.headers?.[D.name.toLowerCase()]:void 0;else if(D.source==="cookie")H=D.name?E.cookies?.[D.name]:void 0;if(!H&&D.source!=="global")H=F?E.ip:"__missing__";return`${R.id}\x00${H}`}class C{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(R,E=()=>Date.now(),D=1e5){this.clock=E;this.maxTrackedKeys=D;this.rules=[...R].sort((F,H)=>(F.priority??0)-(H.priority??0))}check(R){let E=this.clock(),D=this.rules.filter((j)=>W(j,R)),F;for(let j of D){let z=this.test(j,R,E);if(z.allowed)continue;if(!F||$(z.action)>$(F.action))F=z}if(F)return F;let H={action:"allow",allowed:!0};for(let j of D){let z=this.consume(j,R,E);if(z.remaining!=null&&(H.remaining??1/0)>z.remaining)H=z}return H}test(R,E,D){let F=Z(R,E);if((R.algorithm??"token_bucket")==="token_bucket"){let j=R.burst??R.limit,z=this.buckets.get(F),B=z?Math.min(j,z.tokens+this.refill(R,D-z.updatedAt)):j;if(B>=1)return{action:"allow",allowed:!0};return this.blocked(R,F,0,this.msPerToken(R)*(1-B),D)}let H=(this.windows.get(F)?.hits??[]).filter((j)=>j>D-R.windowMs);if(H.length<R.limit)return{action:"allow",allowed:!0};return this.blocked(R,F,0,H[0]+R.windowMs-D,D)}peek(R){let E=this.clock();for(let D of this.rules){if(!W(D,R))continue;let F=this.test(D,R,E);if(!F.allowed)return F}return{action:"allow",allowed:!0}}msPerToken(R){return R.windowMs/Math.max(1,R.limit)}refill(R,E){return Math.max(0,E)/this.msPerToken(R)}blocked(R,E,D,F,H){let j=R.action??"deny";return{action:j,allowed:j==="allow"||j==="log",ruleId:R.id,limit:R.limit,remaining:D,retryAfterMs:Math.max(0,Math.ceil(F)),resetAt:H+Math.max(0,F),key:E}}consume(R,E,D){let F=Z(R,E);if((R.algorithm??"token_bucket")==="token_bucket"){let J=R.burst??R.limit,V=this.buckets.get(F)??{tokens:J,updatedAt:D},Q=Math.min(J,V.tokens+this.refill(R,D-V.updatedAt));if(Q<1)return this.buckets.set(F,{tokens:Q,updatedAt:D}),this.blocked(R,F,0,this.msPerToken(R)*(1-Q),D);return this.evictIfNeeded(this.buckets),this.buckets.set(F,{tokens:Q-1,updatedAt:D}),{action:"allow",allowed:!0,ruleId:R.id,limit:J,remaining:Math.floor(Q-1),resetAt:D+this.msPerToken(R)*(J-(Q-1)),key:F}}let j=this.windows.get(F)??{hits:[]},z=D-R.windowMs,B=j.hits.filter((J)=>J>z);if(B.length>=R.limit)return this.windows.set(F,{hits:B}),this.blocked(R,F,0,B[0]+R.windowMs-D,D);return B.push(D),this.evictIfNeeded(this.windows),this.windows.set(F,{hits:B}),{action:"allow",allowed:!0,ruleId:R.id,limit:R.limit,remaining:R.limit-B.length,resetAt:B[0]+R.windowMs,key:F}}evictIfNeeded(R){if(R.size<this.maxTrackedKeys)return;let E=R.size-this.maxTrackedKeys+1,D=0;for(let F of R.keys())if(R.delete(F),++D>=E)break}sweep(){let R=this.clock(),E=0;for(let[D,F]of this.windows){let H=D.split("\x00")[0],j=this.rules.find((z)=>z.id===H);if(!j){this.windows.delete(D),E++;continue}if(F.hits.every((z)=>z<=R-j.windowMs))this.windows.delete(D),E++}for(let[D,F]of this.buckets){let H=D.split("\x00")[0],j=this.rules.find((z)=>z.id===H);if(!j||R-F.updatedAt>j.windowMs*2)this.buckets.delete(D),E++}return E}get trackedKeys(){return this.buckets.size+this.windows.size}}function $(R){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[R]}function O(R){let E={};if(R.limit!=null)E["ratelimit-limit"]=String(R.limit);if(R.remaining!=null)E["ratelimit-remaining"]=String(R.remaining);if(R.resetAt!=null)E["ratelimit-reset"]=String(Math.max(0,Math.ceil((R.resetAt-Date.now())/1000)));if(!R.allowed&&R.retryAfterMs!=null)E["retry-after"]=String(Math.max(1,Math.ceil(R.retryAfterMs/1000)));return E}function T(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var G="protection.controls",U=24,N=4,P={ipRules:{allow:[],block:[]}};function Y(R,E){if(!R?.enabled)return;return new Date(R.expiresAt).getTime()>E.getTime()?R:void 0}function I(R,E){let D=Number.isFinite(R)?Number(R):E;return Math.min(U,Math.max(0.25,D))}var K=500;class S{controlPlane;options;constructor(R,E={}){this.controlPlane=R;this.options=E}now(){return this.options.now?.()??new Date}read(){let R=this.controlPlane.getSetting(G);if(!R||typeof R!=="object"||Array.isArray(R))return{...P,ipRules:{allow:[],block:[]}};let E=R;return{attackMode:E.attackMode,mitigationPause:E.mitigationPause,ipRules:{allow:Array.isArray(E.ipRules?.allow)?E.ipRules.allow:[],block:Array.isArray(E.ipRules?.block)?E.ipRules.block:[]},updatedAt:E.updatedAt}}write(R){let E={...R,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(G,E),E}raw(){return this.read()}current(){let R=this.now(),E=this.read();return{attackMode:Y(E.attackMode,R),mitigationPause:Y(E.mitigationPause,R),ipRules:E.ipRules}}enableAttackMode(R){let E=this.now(),D={enabled:!0,startedAt:E.toISOString(),expiresAt:new Date(E.getTime()+I(R.hours,N)*3600000).toISOString(),reason:R.reason.trim()||"Attack mode enabled by an operator.",actorId:R.actorId};return this.write({...this.read(),attackMode:D}),D}disableAttackMode(){let R=this.read();if(!R.attackMode?.enabled)return!1;return this.write({...R,attackMode:{...R.attackMode,enabled:!1}}),!0}pauseMitigations(R){let E=R.reason.trim();if(!E)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let D=this.now(),F={enabled:!0,startedAt:D.toISOString(),expiresAt:new Date(D.getTime()+I(R.hours,U)*3600000).toISOString(),reason:E,actorId:R.actorId};return this.write({...this.read(),mitigationPause:F}),F}resumeMitigations(){let R=this.read();if(!R.mitigationPause?.enabled)return!1;return this.write({...R,mitigationPause:{...R.mitigationPause,enabled:!1}}),!0}addIpRule(R,E){let D=E.trim();if(!L(D))throw Error(`Not a valid IP or CIDR: ${E}`);let F=this.read(),H={...F.ipRules,[R]:[...new Set([...F.ipRules[R],D])]};if(H[R].length>K)throw Error(`At most ${K} ${R} rules are supported.`);let j=R==="allow"?"block":"allow";return H[j]=H[j].filter((z)=>z!==D),this.write({...F,ipRules:H}),H}removeIpRule(R,E){let D=this.read(),F={...D.ipRules,[R]:D.ipRules[R].filter((H)=>H!==E.trim())};return this.write({...D,ipRules:F}),F}}function b(R){if(R.mitigationPause)return{attackMode:!!R.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${R.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:R.mitigationPause.expiresAt};if(R.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${R.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:R.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function m(R,E){if(E.mitigationPause)return R.map((D)=>({...D,enabled:!1}));if(!E.attackMode)return[...R];return R.map((D)=>({...D,action:D.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(D.burst??D.limit,5))}))}function x(R,E){let D=[...new Set([...R.allowlist??[],...E.ipRules.allow])],F=[...new Set([...R.blocklist??[],...E.ipRules.block])];if(E.mitigationPause)return{...R,allowlist:D,blocklist:F,monitorOnly:!0};if(!E.attackMode)return{...R,allowlist:D,blocklist:F};let H=R.thresholds??{};return{...R,allowlist:D,blocklist:F,thresholds:{...H,newConnectionsPerSecond:Math.max(1,Math.floor((H.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((H.concurrentPerSource??100)/5))}}}function f(R,E){let D=R?.infrastructure?.compute;if(!D||D.ddos===!1)return R;let F=typeof D.ddos==="object"&&D.ddos!==null?D.ddos:{};return{...R,infrastructure:{...R.infrastructure,compute:{...D,ddos:x(F,E)}}}}export{_ as Sk,X as Tk,W as Uk,Z as Vk,C as Wk,O as Xk,T as Yk,G as Zk,U as _k,N as $k,S as al,b as bl,m as cl,x as dl,f as el};
@@ -0,0 +1,34 @@
1
+ import{Pf as j}from"./chunk-wdzjbecg.js";import{Rh as E}from"./chunk-r3qf56b3.js";import{Th as L}from"./chunk-0ccta6z6.js";import{qt as W}from"./chunk-xt3s24vr.js";function h(z,D){let F=[`Action=${z}`,"Version=2010-05-08"];for(let[J,H]of Object.entries(D)){if(H===void 0||H===null)continue;if(Array.isArray(H))H.forEach((O,Z)=>{if(typeof O==="object"&&O!==null)for(let[$,_]of Object.entries(O))F.push(`${J}.member.${Z+1}.${$}=${encodeURIComponent(String(_))}`);else F.push(`${J}.member.${Z+1}=${encodeURIComponent(String(O))}`)});else if(typeof H==="object"){for(let[O,Z]of Object.entries(H))if(Z!==void 0&&Z!==null)F.push(`${J}.${O}=${encodeURIComponent(String(Z))}`)}else F.push(`${J}=${encodeURIComponent(String(H))}`)}return F.join("&")}function G(z,D){let F=new RegExp(`<${D}>([^<]*)</${D}>`),J=z.match(F);return J?J[1]:void 0}function Y(z,D,F){let J=new RegExp(`<${D}>([\\s\\S]*?)</${D}>`),H=z.match(J);if(!H)return[];let O=[],Z=new RegExp(`<${F}>([\\s\\S]*?)</${F}>`,"g"),$;while(($=Z.exec(H[1]))!==null)O.push($[1]);return O}class w{client;region;constructor(z="us-east-1",D){this.client=new L(void 0,{profile:D}),this.region=z}async request(z,D={}){let F=h(z,D);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:F})}async createUser(z){let D=await this.request("CreateUser",z);return this.parseUser(D)}async getUser(z={}){let D=await this.request("GetUser",z);return this.parseUser(D)}async listUsers(z={}){let D=await this.request("ListUsers",z),F=this.parseUsers(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Users:F,IsTruncated:J,Marker:H}}async updateUser(z){await this.request("UpdateUser",z)}async deleteUser(z){await this.request("DeleteUser",z)}parseUser(z){return{UserName:G(z,"UserName")||"",UserId:G(z,"UserId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate"),PasswordLastUsed:G(z,"PasswordLastUsed")}}parseUsers(z){return Y(z,"Users","member").map((F)=>({UserName:G(F,"UserName")||"",UserId:G(F,"UserId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate"),PasswordLastUsed:G(F,"PasswordLastUsed")}))}async createGroup(z){let D=await this.request("CreateGroup",z);return this.parseGroup(D)}async getGroup(z){let D=await this.request("GetGroup",z),F=this.parseGroup(D),J=this.parseUsers(D),H=G(D,"IsTruncated")==="true",O=G(D,"Marker");return{Group:F,Users:J,IsTruncated:H,Marker:O}}async listGroups(z={}){let D=await this.request("ListGroups",z),F=this.parseGroups(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Groups:F,IsTruncated:J,Marker:H}}async updateGroup(z){await this.request("UpdateGroup",z)}async deleteGroup(z){await this.request("DeleteGroup",z)}async addUserToGroup(z){await this.request("AddUserToGroup",z)}async removeUserFromGroup(z){await this.request("RemoveUserFromGroup",z)}async listGroupsForUser(z){let D=await this.request("ListGroupsForUser",z),F=this.parseGroups(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Groups:F,IsTruncated:J,Marker:H}}parseGroup(z){return{GroupName:G(z,"GroupName")||"",GroupId:G(z,"GroupId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate")}}parseGroups(z){return Y(z,"Groups","member").map((F)=>({GroupName:G(F,"GroupName")||"",GroupId:G(F,"GroupId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate")}))}async createRole(z){let D=await this.request("CreateRole",z);return this.parseRole(D)}async getRole(z){let D=await this.request("GetRole",z);return this.parseRole(D)}async listRoles(z={}){let D=await this.request("ListRoles",z),F=this.parseRoles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Roles:F,IsTruncated:J,Marker:H}}async updateRole(z){await this.request("UpdateRole",z)}async updateRoleDescription(z){let D=await this.request("UpdateRoleDescription",z);return this.parseRole(D)}async updateAssumeRolePolicy(z){await this.request("UpdateAssumeRolePolicy",z)}async deleteRole(z){await this.request("DeleteRole",z)}async tagRole(z){await this.request("TagRole",z)}async untagRole(z){await this.request("UntagRole",z)}async listRoleTags(z){let D=await this.request("ListRoleTags",z),F=this.parseTags(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Tags:F,IsTruncated:J,Marker:H}}parseRole(z){return{RoleName:G(z,"RoleName")||"",RoleId:G(z,"RoleId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate"),AssumeRolePolicyDocument:G(z,"AssumeRolePolicyDocument"),Description:G(z,"Description"),MaxSessionDuration:G(z,"MaxSessionDuration")?Number.parseInt(G(z,"MaxSessionDuration"),10):void 0}}parseRoles(z){return Y(z,"Roles","member").map((F)=>({RoleName:G(F,"RoleName")||"",RoleId:G(F,"RoleId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate"),AssumeRolePolicyDocument:G(F,"AssumeRolePolicyDocument"),Description:G(F,"Description"),MaxSessionDuration:G(F,"MaxSessionDuration")?Number.parseInt(G(F,"MaxSessionDuration"),10):void 0}))}parseTags(z){return Y(z,"Tags","member").map((F)=>({Key:G(F,"Key")||"",Value:G(F,"Value")||""}))}async createPolicy(z){let D=await this.request("CreatePolicy",z);return this.parsePolicy(D)}async getPolicy(z){let D=await this.request("GetPolicy",z);return this.parsePolicy(D)}async getPolicyVersion(z){let D=await this.request("GetPolicyVersion",z);return{VersionId:G(D,"VersionId")||"",IsDefaultVersion:G(D,"IsDefaultVersion")==="true",CreateDate:G(D,"CreateDate"),Document:G(D,"Document")}}async listPolicies(z={}){let D=await this.request("ListPolicies",z),F=this.parsePolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Policies:F,IsTruncated:J,Marker:H}}async listPolicyVersions(z){let D=await this.request("ListPolicyVersions",z),F=this.parsePolicyVersions(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Versions:F,IsTruncated:J,Marker:H}}async createPolicyVersion(z){let D=await this.request("CreatePolicyVersion",z);return{VersionId:G(D,"VersionId")||"",IsDefaultVersion:G(D,"IsDefaultVersion")==="true",CreateDate:G(D,"CreateDate")}}async deletePolicyVersion(z){await this.request("DeletePolicyVersion",z)}async setDefaultPolicyVersion(z){await this.request("SetDefaultPolicyVersion",z)}async deletePolicy(z){await this.request("DeletePolicy",z)}async attachUserPolicy(z){await this.request("AttachUserPolicy",z)}async detachUserPolicy(z){await this.request("DetachUserPolicy",z)}async attachGroupPolicy(z){await this.request("AttachGroupPolicy",z)}async detachGroupPolicy(z){await this.request("DetachGroupPolicy",z)}async attachRolePolicy(z){await this.request("AttachRolePolicy",z)}async detachRolePolicy(z){await this.request("DetachRolePolicy",z)}async listAttachedUserPolicies(z){let D=await this.request("ListAttachedUserPolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}async listAttachedGroupPolicies(z){let D=await this.request("ListAttachedGroupPolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}async listAttachedRolePolicies(z){let D=await this.request("ListAttachedRolePolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}parsePolicy(z){return{PolicyName:G(z,"PolicyName")||"",PolicyId:G(z,"PolicyId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),DefaultVersionId:G(z,"DefaultVersionId"),AttachmentCount:G(z,"AttachmentCount")?Number.parseInt(G(z,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:G(z,"PermissionsBoundaryUsageCount")?Number.parseInt(G(z,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:G(z,"IsAttachable")==="true",Description:G(z,"Description"),CreateDate:G(z,"CreateDate"),UpdateDate:G(z,"UpdateDate")}}parsePolicies(z){return Y(z,"Policies","member").map((F)=>({PolicyName:G(F,"PolicyName")||"",PolicyId:G(F,"PolicyId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),DefaultVersionId:G(F,"DefaultVersionId"),AttachmentCount:G(F,"AttachmentCount")?Number.parseInt(G(F,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:G(F,"PermissionsBoundaryUsageCount")?Number.parseInt(G(F,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:G(F,"IsAttachable")==="true",Description:G(F,"Description"),CreateDate:G(F,"CreateDate"),UpdateDate:G(F,"UpdateDate")}))}parsePolicyVersions(z){return Y(z,"Versions","member").map((F)=>({VersionId:G(F,"VersionId")||"",IsDefaultVersion:G(F,"IsDefaultVersion")==="true",CreateDate:G(F,"CreateDate")}))}parseAttachedPolicies(z){return Y(z,"AttachedPolicies","member").map((F)=>({PolicyName:G(F,"PolicyName")||"",PolicyArn:G(F,"PolicyArn")||""}))}async putUserPolicy(z){await this.request("PutUserPolicy",z)}async getUserPolicy(z){let D=await this.request("GetUserPolicy",z);return{UserName:G(D,"UserName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteUserPolicy(z){await this.request("DeleteUserPolicy",z)}async listUserPolicies(z){let D=await this.request("ListUserPolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async putGroupPolicy(z){await this.request("PutGroupPolicy",z)}async getGroupPolicy(z){let D=await this.request("GetGroupPolicy",z);return{GroupName:G(D,"GroupName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteGroupPolicy(z){await this.request("DeleteGroupPolicy",z)}async listGroupPolicies(z){let D=await this.request("ListGroupPolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async putRolePolicy(z){await this.request("PutRolePolicy",z)}async getRolePolicy(z){let D=await this.request("GetRolePolicy",z);return{RoleName:G(D,"RoleName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteRolePolicy(z){await this.request("DeleteRolePolicy",z)}async listRolePolicies(z){let D=await this.request("ListRolePolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async createAccessKey(z={}){let D=await this.request("CreateAccessKey",z);if(typeof D==="object"){let F=D?.CreateAccessKeyResult?.AccessKey||D?.AccessKey;if(F)return{AccessKey:{UserName:F.UserName||"",AccessKeyId:F.AccessKeyId||"",Status:F.Status||"Active",SecretAccessKey:F.SecretAccessKey||"",CreateDate:F.CreateDate}}}return{AccessKey:{UserName:G(D,"UserName")||"",AccessKeyId:G(D,"AccessKeyId")||"",Status:G(D,"Status")||"Active",SecretAccessKey:G(D,"SecretAccessKey")||"",CreateDate:G(D,"CreateDate")}}}async listAccessKeys(z={}){let D=await this.request("ListAccessKeys",z),F=this.parseAccessKeys(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AccessKeyMetadata:F,IsTruncated:J,Marker:H}}async updateAccessKey(z){await this.request("UpdateAccessKey",z)}async deleteAccessKey(z){await this.request("DeleteAccessKey",z)}async getAccessKeyLastUsed(z){let D=await this.request("GetAccessKeyLastUsed",z);return{UserName:G(D,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:G(D,"LastUsedDate"),ServiceName:G(D,"ServiceName"),Region:G(D,"Region")}}}parseAccessKeys(z){return Y(z,"AccessKeyMetadata","member").map((F)=>({UserName:G(F,"UserName"),AccessKeyId:G(F,"AccessKeyId")||"",Status:G(F,"Status")||"Active",CreateDate:G(F,"CreateDate")}))}async createInstanceProfile(z){let D=await this.request("CreateInstanceProfile",z);return this.parseInstanceProfile(D)}async getInstanceProfile(z){let D=await this.request("GetInstanceProfile",z);return this.parseInstanceProfile(D)}async listInstanceProfiles(z={}){let D=await this.request("ListInstanceProfiles",z),F=this.parseInstanceProfiles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{InstanceProfiles:F,IsTruncated:J,Marker:H}}async listInstanceProfilesForRole(z){let D=await this.request("ListInstanceProfilesForRole",z),F=this.parseInstanceProfiles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{InstanceProfiles:F,IsTruncated:J,Marker:H}}async addRoleToInstanceProfile(z){await this.request("AddRoleToInstanceProfile",z)}async removeRoleFromInstanceProfile(z){await this.request("RemoveRoleFromInstanceProfile",z)}async deleteInstanceProfile(z){await this.request("DeleteInstanceProfile",z)}parseInstanceProfile(z){return{InstanceProfileName:G(z,"InstanceProfileName")||"",InstanceProfileId:G(z,"InstanceProfileId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate")}}parseInstanceProfiles(z){return Y(z,"InstanceProfiles","member").map((F)=>({InstanceProfileName:G(F,"InstanceProfileName")||"",InstanceProfileId:G(F,"InstanceProfileId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate")}))}async getAccountPasswordPolicy(){let z=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:G(z,"MinimumPasswordLength")?Number.parseInt(G(z,"MinimumPasswordLength"),10):void 0,RequireSymbols:G(z,"RequireSymbols")==="true",RequireNumbers:G(z,"RequireNumbers")==="true",RequireUppercaseCharacters:G(z,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:G(z,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:G(z,"AllowUsersToChangePassword")==="true",ExpirePasswords:G(z,"ExpirePasswords")==="true",MaxPasswordAge:G(z,"MaxPasswordAge")?Number.parseInt(G(z,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:G(z,"PasswordReusePrevention")?Number.parseInt(G(z,"PasswordReusePrevention"),10):void 0,HardExpiry:G(z,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(z){await this.request("UpdateAccountPasswordPolicy",z)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let z=await this.request("GetAccountSummary"),D={},F=Y(z,"SummaryMap","entry");for(let J of F){let H=G(J,"key"),O=G(J,"value");if(H&&O)D[H]=Number.parseInt(O,10)}return D}async listAccountAliases(){let z=await this.request("ListAccountAliases"),D=Y(z,"AccountAliases","member"),F=G(z,"IsTruncated")==="true",J=G(z,"Marker");return{AccountAliases:D,IsTruncated:F,Marker:J}}async createAccountAlias(z){await this.request("CreateAccountAlias",z)}async deleteAccountAlias(z){await this.request("DeleteAccountAlias",z)}async simulatePrincipalPolicy(z){let D=await this.request("SimulatePrincipalPolicy",z);return this.parseSimulationResults(D)}parseSimulationResults(z){let F=Y(z,"EvaluationResults","member").map((O)=>{let $=Y(O,"MatchedStatements","member").map((_)=>({SourcePolicyId:G(_,"SourcePolicyId"),SourcePolicyType:G(_,"SourcePolicyType")}));return{EvalActionName:G(O,"EvalActionName")||"",EvalResourceName:G(O,"EvalResourceName"),EvalDecision:G(O,"EvalDecision")||"",MatchedStatements:$.length>0?$:void 0}}),J=G(z,"IsTruncated")==="true",H=G(z,"Marker");return{EvaluationResults:F,IsTruncated:J,Marker:H}}}class U{client;region;constructor(z="us-east-1",D){this.region=z,this.client=new L(D)}async createEmailIdentity(z){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})}async getEmailIdentity(z){let D=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:D.IdentityType,IdentityName:z,SendingEnabled:D.VerifiedForSendingStatus,VerificationStatus:D.VerificationStatus,DkimAttributes:D.DkimAttributes,MailFromAttributes:D.MailFromAttributes}}async putEmailIdentityMailFromAttributes(z,D){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(z)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(D)})}async listEmailIdentities(z){let D="/v2/email/identities",F=[];if(z?.PageSize)F.push(`PageSize=${z.PageSize}`);if(z?.NextToken)F.push(`NextToken=${encodeURIComponent(z.NextToken)}`);if(F.length>0)D+=`?${F.join("&")}`;let J=await this.client.request({service:"email",region:this.region,method:"GET",path:D,headers:{"Content-Type":"application/json"}});return{EmailIdentities:J.EmailIdentities,NextToken:J.NextToken}}async deleteEmailIdentity(z){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(z){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(z.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:z.SigningEnabled})})}async sendEmail(z){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(z)})).MessageId}}async sendBulkEmail(z){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(z)})).BulkEmailEntryResults}}async createEmailTemplate(z){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})}async getEmailTemplate(z){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(z){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(z){let D="/v2/email/templates",F=[];if(z?.PageSize)F.push(`PageSize=${z.PageSize}`);if(z?.NextToken)F.push(`NextToken=${encodeURIComponent(z.NextToken)}`);if(F.length>0)D+=`?${F.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:D,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 D=(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:D?.Max24HourSend?Number(D.Max24HourSend):void 0,MaxSendRate:D?.MaxSendRate?Number(D.MaxSendRate):void 0,SentLast24Hours:D?.SentLast24Hours?Number(D.SentLast24Hours):void 0}}async verifyDomain(z){let D=await this.createEmailIdentity({EmailIdentity:z});return{dkimTokens:D.DkimAttributes?.Tokens,verificationStatus:D.DkimAttributes?.Status}}async sendSimpleEmail(z){let D=Array.isArray(z.to)?z.to:[z.to],F=z.replyTo?Array.isArray(z.replyTo)?z.replyTo:[z.replyTo]:void 0,J={};if(z.text)J.Text={Data:z.text};if(z.html)J.Html={Data:z.html};return this.sendEmail({FromEmailAddress:z.from,Destination:{ToAddresses:D},Content:{Simple:{Subject:{Data:z.subject},Body:J}},ReplyToAddresses:F})}async sendTemplatedEmail(z){let D=Array.isArray(z.to)?z.to:[z.to],F=z.replyTo?Array.isArray(z.replyTo)?z.replyTo:[z.replyTo]:void 0;return this.sendEmail({FromEmailAddress:z.from,Destination:{ToAddresses:D},Content:{Template:{TemplateName:z.templateName,TemplateData:JSON.stringify(z.templateData)}},ReplyToAddresses:F})}async getDkimRecords(z){let D=await this.getEmailIdentity(z);if(!D.DkimAttributes?.Tokens)return[];return D.DkimAttributes.Tokens.map((F)=>({name:`${F}._domainkey.${z}`,type:"CNAME",value:`${F}.dkim.amazonses.com`}))}async isDomainVerified(z){try{let D=await this.getEmailIdentity(z);return D.VerificationStatus==="SUCCESS"&&D.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(z,D=60,F=30000){for(let J=0;J<D;J++){if(await this.isDomainVerified(z))return!0;await new Promise((O)=>setTimeout(O,F))}return!1}buildFormBody(z){return Object.entries(z).filter(([,F])=>F!==void 0).map(([F,J])=>`${encodeURIComponent(F)}=${encodeURIComponent(J)}`).join("&")}async createReceiptRuleSet(z){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:z})})}async deleteReceiptRuleSet(z){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:z})})}async setActiveReceiptRuleSet(z){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:z})})}async listReceiptRuleSets(z){let D={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(z)D.NextToken=z;let F=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(D)}),J=F?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||F?.ListReceiptRuleSetsResult,H=J?.RuleSets?.member;return{RuleSets:Array.isArray(H)?H:H?[H]:[],NextToken:J?.NextToken}}async describeReceiptRuleSet(z){let D=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:z})}),F=D?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||D?.DescribeReceiptRuleSetResult,J=F?.Rules?.member;return{Metadata:F?.Metadata,Rules:Array.isArray(J)?J:J?[J]:[]}}async createReceiptRule(z){let D={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:z.RuleSetName,"Rule.Name":z.Rule.Name,"Rule.Enabled":z.Rule.Enabled!==!1?"true":"false"};if(z.Rule.TlsPolicy)D["Rule.TlsPolicy"]=z.Rule.TlsPolicy;if(z.Rule.ScanEnabled!==void 0)D["Rule.ScanEnabled"]=z.Rule.ScanEnabled?"true":"false";if(z.After)D.After=z.After;if(z.Rule.Recipients)z.Rule.Recipients.forEach((F,J)=>{D[`Rule.Recipients.member.${J+1}`]=F});z.Rule.Actions.forEach((F,J)=>{let H=J+1;if(F.S3Action){if(D[`Rule.Actions.member.${H}.S3Action.BucketName`]=F.S3Action.BucketName,F.S3Action.ObjectKeyPrefix)D[`Rule.Actions.member.${H}.S3Action.ObjectKeyPrefix`]=F.S3Action.ObjectKeyPrefix;if(F.S3Action.KmsKeyArn)D[`Rule.Actions.member.${H}.S3Action.KmsKeyArn`]=F.S3Action.KmsKeyArn}if(F.LambdaAction)D[`Rule.Actions.member.${H}.LambdaAction.FunctionArn`]=F.LambdaAction.FunctionArn,D[`Rule.Actions.member.${H}.LambdaAction.InvocationType`]=F.LambdaAction.InvocationType||"Event";if(F.SNSAction){if(D[`Rule.Actions.member.${H}.SNSAction.TopicArn`]=F.SNSAction.TopicArn,F.SNSAction.Encoding)D[`Rule.Actions.member.${H}.SNSAction.Encoding`]=F.SNSAction.Encoding}if(F.StopAction){if(D[`Rule.Actions.member.${H}.StopAction.Scope`]=F.StopAction.Scope,F.StopAction.TopicArn)D[`Rule.Actions.member.${H}.StopAction.TopicArn`]=F.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(D)})}async deleteReceiptRule(z,D){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:z,RuleName:D})})}async receiptRuleSetExists(z){try{return await this.describeReceiptRuleSet(z),!0}catch(D){if(D.code==="RuleSetDoesNotExist"||D.statusCode===400)return!1;throw D}}async getActiveReceiptRuleSet(){let z=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"})}),D=z?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||z?.DescribeActiveReceiptRuleSetResult;if(!D?.Metadata)return null;let F=D?.Rules?.member;return{Metadata:D?.Metadata,Rules:Array.isArray(F)?F:F?[F]:[]}}async updateReceiptRule(z){let D={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:z.RuleSetName,"Rule.Name":z.Rule.Name};if(z.Rule.Enabled!==void 0)D["Rule.Enabled"]=z.Rule.Enabled?"true":"false";if(z.Rule.TlsPolicy)D["Rule.TlsPolicy"]=z.Rule.TlsPolicy;if(z.Rule.ScanEnabled!==void 0)D["Rule.ScanEnabled"]=z.Rule.ScanEnabled?"true":"false";if(z.Rule.Recipients)z.Rule.Recipients.forEach((F,J)=>{D[`Rule.Recipients.member.${J+1}`]=F});z.Rule.Actions.forEach((F,J)=>{let H=J+1;if(F.S3Action){if(D[`Rule.Actions.member.${H}.S3Action.BucketName`]=F.S3Action.BucketName,F.S3Action.ObjectKeyPrefix)D[`Rule.Actions.member.${H}.S3Action.ObjectKeyPrefix`]=F.S3Action.ObjectKeyPrefix;if(F.S3Action.KmsKeyArn)D[`Rule.Actions.member.${H}.S3Action.KmsKeyArn`]=F.S3Action.KmsKeyArn}if(F.LambdaAction)D[`Rule.Actions.member.${H}.LambdaAction.FunctionArn`]=F.LambdaAction.FunctionArn,D[`Rule.Actions.member.${H}.LambdaAction.InvocationType`]=F.LambdaAction.InvocationType||"Event";if(F.SNSAction){if(D[`Rule.Actions.member.${H}.SNSAction.TopicArn`]=F.SNSAction.TopicArn,F.SNSAction.Encoding)D[`Rule.Actions.member.${H}.SNSAction.Encoding`]=F.SNSAction.Encoding}if(F.StopAction){if(D[`Rule.Actions.member.${H}.StopAction.Scope`]=F.StopAction.Scope,F.StopAction.TopicArn)D[`Rule.Actions.member.${H}.StopAction.TopicArn`]=F.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(D)})}async sendRawEmail(z){let D=Buffer.from(z.rawMessage).toString("base64"),F={Action:"SendRawEmail",Version:"2010-12-01",Source:z.source,"RawMessage.Data":D};z.destinations.forEach((O,Z)=>{F[`Destinations.member.${Z+1}`]=O});let J=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(F)});return{MessageId:(J?.SendRawEmailResponse?.SendRawEmailResult||J?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(z){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(z)}`}))?.SuppressedDestination||null}catch(D){if(D.message?.includes("404")||D.message?.includes("NotFoundException"))return null;throw D}}async deleteSuppressedDestination(z){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(z)}`})}}class M{ses;s3;iam;route53;region;domain;defaultFrom;constructor(z={}){this.region=z.region||"us-east-1",this.domain=z.domain,this.defaultFrom=z.defaultFrom,this.ses=new U(this.region),this.s3=new E(this.region),this.iam=new w(this.region),this.route53=new j(this.region)}async send(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let F=z.fromName?`${z.fromName} <${D}>`:D,J=Array.isArray(z.to)?z.to:[z.to];if(!z.attachments||z.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:F,to:J,subject:z.subject,text:z.text,html:z.html,replyTo:z.replyTo})).MessageId||""};let H=this.buildRawEmail(z,F,J);return{messageId:(await this.ses.sendEmail({FromEmailAddress:F,Destination:{ToAddresses:J,CcAddresses:z.cc?Array.isArray(z.cc)?z.cc:[z.cc]:void 0,BccAddresses:z.bcc?Array.isArray(z.bcc)?z.bcc:[z.bcc]:void 0},Content:{Raw:{Data:Buffer.from(H).toString("base64")}}})).MessageId||""}}async sendTemplate(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required");let F=z.fromName?`${z.fromName} <${D}>`:D;return{messageId:(await this.ses.sendTemplatedEmail({from:F,to:z.to,templateName:z.templateName,templateData:z.templateData,replyTo:z.replyTo})).MessageId||""}}async sendBulk(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required");let F=z.recipients.map((H)=>({Destination:{ToAddresses:Array.isArray(H.to)?H.to:[H.to]},ReplacementEmailContent:H.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(H.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:D,BulkEmailEntries:F,DefaultContent:{Template:{TemplateName:z.templateName,TemplateData:JSON.stringify(z.defaultTemplateData)}}})).BulkEmailEntryResults?.map((H)=>({status:H.Status||"UNKNOWN",messageId:H.MessageId,error:H.Error}))||[]}}async setupDomain(z){let D;try{D=await this.ses.getEmailIdentity(z)}catch{let J=await this.ses.createEmailIdentity({EmailIdentity:z});D={VerificationStatus:J.DkimAttributes?.Status,DkimAttributes:J.DkimAttributes,SendingEnabled:J.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:z,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(z,{MailFromDomain:`mail.${z}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let F=await this.ses.getDkimRecords(z);return{domainVerified:D.SendingEnabled===!0,dkimStatus:D.DkimAttributes?.Status||"UNKNOWN",dkimTokens:D.DkimAttributes?.Tokens,mailFromStatus:D.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(z){let D=[],F=await this.ses.getDkimRecords(z);for(let J of F)D.push({type:J.type,name:J.name,value:J.value,ttl:1800});return D.push({type:"MX",name:z,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),D.push({type:"MX",name:`mail.${z}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),D.push({type:"TXT",name:`mail.${z}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),D.push({type:"TXT",name:`_dmarc.${z}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${z}`,ttl:3600}),D}async isDomainReady(z){try{let D=await this.ses.getEmailIdentity(z);return D.SendingEnabled===!0&&D.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(z){let D={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${z.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":z.accountId}}}]};await this.s3.putBucketPolicy(z.bucketName,D);try{await this.ses.createReceiptRuleSet(z.ruleSetName)}catch(J){if(!J.message?.includes("already exists")&&J.code!=="AlreadyExists")throw J}let F=[{S3Action:{BucketName:z.bucketName,ObjectKeyPrefix:z.prefix||"inbox/"}}];if(z.lambdaArn)F.push({LambdaAction:{FunctionArn:z.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:z.ruleSetName,Rule:{Name:z.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:z.recipients||[z.domain],ScanEnabled:z.scanEnabled!==!1,Actions:F}})}catch(J){if(J.message?.includes("already exists"))await this.ses.deleteReceiptRule(z.ruleSetName,z.ruleName),await this.ses.createReceiptRule({RuleSetName:z.ruleSetName,Rule:{Name:z.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:z.recipients||[z.domain],ScanEnabled:z.scanEnabled!==!1,Actions:F}});else throw J}await this.ses.setActiveReceiptRuleSet(z.ruleSetName)}async getIncomingEmails(z){return(await this.s3.list({bucket:z.bucket,prefix:z.prefix||"incoming/",maxKeys:z.maxResults||100})).map((F)=>({key:F.Key||"",lastModified:F.LastModified||"",size:F.Size||0}))}async readEmail(z){return await this.s3.getObject(z.bucket,z.key)}async createSmtpCredentials(z){let D=`ses-smtp-${z.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:F}=await import("./chunk-ww8k3g7j.js"),J=new F,H=(Q,C)=>{let I={Action:Q,Version:"2010-05-08",...C};return Object.entries(I).map(([R,K])=>`${encodeURIComponent(R)}=${encodeURIComponent(K)}`).join("&")};try{await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("CreateUser",{UserName:D})})}catch(Q){if(!Q.message?.includes("EntityAlreadyExists"))throw Q}let O={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${z.domain}`}}}]},Z=`ses-smtp-policy-${z.domain.replace(/\./g,"-")}`;try{await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("PutUserPolicy",{UserName:D,PolicyName:Z,PolicyDocument:JSON.stringify(O)})})}catch{}let _=(await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("CreateAccessKey",{UserName:D})}))?.CreateAccessKeyResult?.AccessKey;if(!_?.AccessKeyId||!_?.SecretAccessKey)throw Error("Failed to create access key");let B=this.deriveSmtpPassword(_.SecretAccessKey);return{username:_.AccessKeyId,password:B,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(z){let D=W("node:crypto"),F="SendRawEmail",J=Buffer.from([4]),H=D.createHmac("sha256",`AWS4${z}`).update("11111111").digest();return H=D.createHmac("sha256",H).update(this.region).digest(),H=D.createHmac("sha256",H).update("ses").digest(),H=D.createHmac("sha256",H).update("aws4_request").digest(),H=D.createHmac("sha256",H).update("SendRawEmail").digest(),Buffer.concat([J,H]).toString("base64")}async createTemplate(z){await this.ses.createEmailTemplate({TemplateName:z.name,TemplateContent:{Subject:z.subject,Text:z.text,Html:z.html}})}async getTemplate(z){try{let D=await this.ses.getEmailTemplate(z);return{name:D.TemplateName||z,subject:D.TemplateContent?.Subject,text:D.TemplateContent?.Text,html:D.TemplateContent?.Html}}catch{return null}}async deleteTemplate(z){await this.ses.deleteEmailTemplate(z)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((D)=>({name:D.TemplateName||"",createdAt:D.CreatedTimestamp}))||[]}async deploy(z){let D=`${z.appName}-${z.environment}-email-rules`,F=`${z.appName}-inbound-email`,J=z.storage?.bucketName||`${z.appName}-${z.environment}-email`,H=await this.setupDomain(z.domain);if(!(await this.s3.listBuckets()).Buckets?.some((_)=>_.Name===J))await this.s3.createBucket(J);await this.setupReceiving({domain:z.domain,ruleSetName:D,ruleName:F,bucketName:J,prefix:z.storage?.prefix||"inbox/",accountId:z.accountId,recipients:z.catchAll?[z.domain]:z.mailboxes,scanEnabled:!0});let $=await this.getDnsRecords(z.domain);return{success:!0,domainVerified:H.domainVerified,dkimStatus:H.dkimStatus,receiptRuleSet:D,storageBucket:J,dnsRecords:$}}async undeploy(z){let D=`${z.appName}-${z.environment}-email-rules`,F=`${z.appName}-inbound-email`,J=`${z.appName}-${z.environment}-email`;try{await this.ses.deleteReceiptRule(D,F)}catch{}try{await this.ses.deleteReceiptRuleSet(D)}catch{}if(z.deleteBucket)try{await this.s3.emptyAndDeleteBucket(J)}catch{}}async getSendingStats(){let z=await this.ses.getSendQuota();return{sentLast24Hours:z.SentLast24Hours||0,maxSendRate:z.MaxSendRate||0,max24HourSend:z.Max24HourSend||0}}buildRawEmail(z,D,F){let J=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,H="";if(H+=`From: ${D}\r
2
+ `,H+=`To: ${F.join(", ")}\r
3
+ `,z.cc){let O=Array.isArray(z.cc)?z.cc:[z.cc];H+=`Cc: ${O.join(", ")}\r
4
+ `}if(H+=`Subject: ${z.subject}\r
5
+ `,H+=`MIME-Version: 1.0\r
6
+ `,H+=`Content-Type: multipart/mixed; boundary="${J}"\r
7
+ `,H+=`\r
8
+ `,z.text||z.html)if(H+=`--${J}\r
9
+ `,z.html&&z.text){let O=`----=_Alt_${Date.now()}`;H+=`Content-Type: multipart/alternative; boundary="${O}"\r
10
+ `,H+=`\r
11
+ `,H+=`--${O}\r
12
+ `,H+=`Content-Type: text/plain; charset="UTF-8"\r
13
+ `,H+=`\r
14
+ `,H+=`${z.text}\r
15
+ `,H+=`--${O}\r
16
+ `,H+=`Content-Type: text/html; charset="UTF-8"\r
17
+ `,H+=`\r
18
+ `,H+=`${z.html}\r
19
+ `,H+=`--${O}--\r
20
+ `}else if(z.html)H+=`Content-Type: text/html; charset="UTF-8"\r
21
+ `,H+=`\r
22
+ `,H+=`${z.html}\r
23
+ `;else H+=`Content-Type: text/plain; charset="UTF-8"\r
24
+ `,H+=`\r
25
+ `,H+=`${z.text}\r
26
+ `;if(z.attachments)for(let O of z.attachments)H+=`--${J}\r
27
+ `,H+=`Content-Type: ${O.contentType||"application/octet-stream"}; name="${O.filename}"\r
28
+ `,H+=`Content-Transfer-Encoding: base64\r
29
+ `,H+=`Content-Disposition: attachment; filename="${O.filename}"\r
30
+ `,H+=`\r
31
+ `,H+=`${O.content}\r
32
+ `;return H+=`--${J}--\r
33
+ `,H}}var y=new M;
34
+ export{w as of,U as pf,M as qf,y as rf};
@@ -0,0 +1,2 @@
1
+ import{Th as T,Uh as J}from"./chunk-0ccta6z6.js";class U{client;region;constructor(k="us-east-1"){this.region=k,this.client=new T}async describeDBInstances(k){let w={Action:"DescribeDBInstances",Version:"2014-10-31"};if(k?.DBInstanceIdentifier)w.DBInstanceIdentifier=k.DBInstanceIdentifier;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;if(k?.Filters)k.Filters.forEach((K,L)=>{w[`Filters.Filter.${L+1}.Name`]=K.Name,K.Values.forEach((O,R)=>{w[`Filters.Filter.${L+1}.Values.Value.${R+1}`]=O})});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBInstancesResult||z,G=H.DBInstances?.DBInstance||[];if(!Array.isArray(G))G=G?[G]:[];return{DBInstances:G,Marker:H.Marker}}async describeDBInstance(k){return(await this.describeDBInstances({DBInstanceIdentifier:k})).DBInstances?.[0]}async describeDBClusters(k){let w={Action:"DescribeDBClusters",Version:"2014-10-31"};if(k?.DBClusterIdentifier)w.DBClusterIdentifier=k.DBClusterIdentifier;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;if(k?.Filters)k.Filters.forEach((K,L)=>{w[`Filters.Filter.${L+1}.Name`]=K.Name,K.Values.forEach((O,R)=>{w[`Filters.Filter.${L+1}.Values.Value.${R+1}`]=O})});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBClustersResult||z,G=H.DBClusters?.DBCluster||[];if(!Array.isArray(G))G=G?[G]:[];return{DBClusters:G,Marker:H.Marker}}async describeDBSnapshots(k){let w={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if(k?.DBInstanceIdentifier)w.DBInstanceIdentifier=k.DBInstanceIdentifier;if(k?.DBSnapshotIdentifier)w.DBSnapshotIdentifier=k.DBSnapshotIdentifier;if(k?.SnapshotType)w.SnapshotType=k.SnapshotType;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBSnapshotsResult||z,G=H.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSnapshots:G,Marker:H.Marker}}async describeDBSubnetGroups(k){let w={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if(k?.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k?.MaxRecords)w.MaxRecords=k.MaxRecords;if(k?.Marker)w.Marker=k.Marker;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E}),H=z.DescribeDBSubnetGroupsResult||z,G=H.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSubnetGroups:G,Marker:H.Marker}}async createDBInstance(k){let w={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier,DBInstanceClass:k.DBInstanceClass,Engine:k.Engine};if(k.DBClusterIdentifier)w.DBClusterIdentifier=k.DBClusterIdentifier;if(k.MasterUsername)w.MasterUsername=k.MasterUsername;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.DBName)w.DBName=k.DBName;if(k.AllocatedStorage)w.AllocatedStorage=k.AllocatedStorage;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.AvailabilityZone)w.AvailabilityZone=k.AvailabilityZone;if(k.PreferredMaintenanceWindow)w.PreferredMaintenanceWindow=k.PreferredMaintenanceWindow;if(k.PreferredBackupWindow)w.PreferredBackupWindow=k.PreferredBackupWindow;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.MultiAZ!==void 0)w.MultiAZ=k.MultiAZ;if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.AutoMinorVersionUpgrade!==void 0)w.AutoMinorVersionUpgrade=k.AutoMinorVersionUpgrade;if(k.LicenseModel)w.LicenseModel=k.LicenseModel;if(k.PubliclyAccessible!==void 0)w.PubliclyAccessible=k.PubliclyAccessible;if(k.StorageType)w.StorageType=k.StorageType;if(k.StorageEncrypted!==void 0)w.StorageEncrypted=k.StorageEncrypted;if(k.KmsKeyId)w.KmsKeyId=k.KmsKeyId;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});if(k.Tags)k.Tags.forEach((G,K)=>{w[`Tags.Tag.${K+1}.Key`]=G.Key,w[`Tags.Tag.${K+1}.Value`]=G.Value});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.CreateDBInstanceResult||z).DBInstance}}async createDBCluster(k){let w={Action:"CreateDBCluster",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier,Engine:k.Engine};if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.MasterUsername)w.MasterUsername=k.MasterUsername;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.DatabaseName)w.DatabaseName=k.DatabaseName;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.StorageEncrypted!==void 0)w.StorageEncrypted=k.StorageEncrypted;if(k.KmsKeyId)w.KmsKeyId=k.KmsKeyId;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.ServerlessV2ScalingConfiguration)w["ServerlessV2ScalingConfiguration.MinCapacity"]=k.ServerlessV2ScalingConfiguration.MinCapacity,w["ServerlessV2ScalingConfiguration.MaxCapacity"]=k.ServerlessV2ScalingConfiguration.MaxCapacity;k.VpcSecurityGroupIds?.forEach((H,G)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${G+1}`]=H});let E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()});return{DBCluster:(E.CreateDBClusterResult||E).DBCluster}}async deleteDBInstance(k){let w={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.SkipFinalSnapshot!==void 0)w.SkipFinalSnapshot=k.SkipFinalSnapshot;if(k.FinalDBSnapshotIdentifier)w.FinalDBSnapshotIdentifier=k.FinalDBSnapshotIdentifier;if(k.DeleteAutomatedBackups!==void 0)w.DeleteAutomatedBackups=k.DeleteAutomatedBackups;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.DeleteDBInstanceResult||z).DBInstance}}async modifyDBInstance(k){let w={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.DBInstanceClass)w.DBInstanceClass=k.DBInstanceClass;if(k.AllocatedStorage)w.AllocatedStorage=k.AllocatedStorage;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.PreferredBackupWindow)w.PreferredBackupWindow=k.PreferredBackupWindow;if(k.PreferredMaintenanceWindow)w.PreferredMaintenanceWindow=k.PreferredMaintenanceWindow;if(k.MultiAZ!==void 0)w.MultiAZ=k.MultiAZ;if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.AutoMinorVersionUpgrade!==void 0)w.AutoMinorVersionUpgrade=k.AutoMinorVersionUpgrade;if(k.PubliclyAccessible!==void 0)w.PubliclyAccessible=k.PubliclyAccessible;if(k.ApplyImmediately!==void 0)w.ApplyImmediately=k.ApplyImmediately;if(k.StorageType)w.StorageType=k.StorageType;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.ModifyDBInstanceResult||z).DBInstance}}async modifyDBCluster(k){let w={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier};if(k.ServerlessV2ScalingConfiguration)w["ServerlessV2ScalingConfiguration.MinCapacity"]=k.ServerlessV2ScalingConfiguration.MinCapacity,w["ServerlessV2ScalingConfiguration.MaxCapacity"]=k.ServerlessV2ScalingConfiguration.MaxCapacity;if(k.BackupRetentionPeriod!==void 0)w.BackupRetentionPeriod=k.BackupRetentionPeriod;if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.MasterUserPassword)w.MasterUserPassword=k.MasterUserPassword;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.ApplyImmediately!==void 0)w.ApplyImmediately=k.ApplyImmediately;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBCluster:(z.ModifyDBClusterResult||z).DBCluster}}async rebootDBCluster(k){let w={Action:"FailoverDBCluster",Version:"2014-10-31",DBClusterIdentifier:k},E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()});return{DBCluster:(E.FailoverDBClusterResult||E).DBCluster}}async createDBClusterSnapshot(k,w){let E={Action:"CreateDBClusterSnapshot",Version:"2014-10-31",DBClusterIdentifier:k,DBClusterSnapshotIdentifier:w};return this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(E)).toString()})}async describeDBClusterSnapshots(k={}){let w={Action:"DescribeDBClusterSnapshots",Version:"2014-10-31",...k},E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()}),z=E.DescribeDBClusterSnapshotsResult||E,H=z.DBClusterSnapshots?.DBClusterSnapshot??z.DBClusterSnapshots??[];return{DBClusterSnapshots:Array.isArray(H)?H:[H]}}async deleteDBClusterSnapshot(k){await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J({Action:"DeleteDBClusterSnapshot",Version:"2014-10-31",DBClusterSnapshotIdentifier:k})).toString()})}async deleteDBCluster(k,w){let E={Action:"DeleteDBCluster",Version:"2014-10-31",DBClusterIdentifier:k,SkipFinalSnapshot:!w};if(w)E.FinalDBSnapshotIdentifier=w;let z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(E)).toString()});return{DBCluster:(z.DeleteDBClusterResult||z).DBCluster}}async restoreDBClusterToPointInTime(k){let w={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier,SourceDBClusterIdentifier:k.SourceDBClusterIdentifier};if(k.RestoreToTime)w.RestoreToTime=k.RestoreToTime.toISOString();if(k.UseLatestRestorableTime)w.UseLatestRestorableTime=!0;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBCluster:(z.RestoreDBClusterToPointInTimeResult||z).DBCluster}}async restoreDBClusterFromSnapshot(k){let w={Action:"RestoreDBClusterFromSnapshot",Version:"2014-10-31",DBClusterIdentifier:k.DBClusterIdentifier,SnapshotIdentifier:k.SnapshotIdentifier,Engine:k.Engine};if(k.EngineVersion)w.EngineVersion=k.EngineVersion;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds?.forEach((H,G)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${G+1}`]=H}),k.ServerlessV2ScalingConfiguration)w["ServerlessV2ScalingConfiguration.MinCapacity"]=k.ServerlessV2ScalingConfiguration.MinCapacity,w["ServerlessV2ScalingConfiguration.MaxCapacity"]=k.ServerlessV2ScalingConfiguration.MaxCapacity;let E=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J(w)).toString()});return{DBCluster:(E.RestoreDBClusterFromSnapshotResult||E).DBCluster}}async startDBInstance(k){let E=new URLSearchParams(J({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k})).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.StartDBInstanceResult||z).DBInstance}}async stopDBInstance(k){let w={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.DBSnapshotIdentifier)w.DBSnapshotIdentifier=k.DBSnapshotIdentifier;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.StopDBInstanceResult||z).DBInstance}}async rebootDBInstance(k){let w={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier};if(k.ForceFailover!==void 0)w.ForceFailover=k.ForceFailover;let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.RebootDBInstanceResult||z).DBInstance}}async createDBSnapshot(k){let w={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier,DBSnapshotIdentifier:k.DBSnapshotIdentifier};if(k.Tags)k.Tags.forEach((G,K)=>{w[`Tags.Tag.${K+1}.Key`]=G.Key,w[`Tags.Tag.${K+1}.Value`]=G.Value});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBSnapshot:(z.CreateDBSnapshotResult||z).DBSnapshot}}async deleteDBSnapshot(k){let E=new URLSearchParams(J({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:k})).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBSnapshot:(z.DeleteDBSnapshotResult||z).DBSnapshot}}async restoreDBInstanceFromDBSnapshot(k){let w={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:k.DBInstanceIdentifier,DBSnapshotIdentifier:k.DBSnapshotIdentifier};if(k.DBInstanceClass)w.DBInstanceClass=k.DBInstanceClass;if(k.Port)w.Port=k.Port;if(k.AvailabilityZone)w.AvailabilityZone=k.AvailabilityZone;if(k.DBSubnetGroupName)w.DBSubnetGroupName=k.DBSubnetGroupName;if(k.MultiAZ!==void 0)w.MultiAZ=k.MultiAZ;if(k.PubliclyAccessible!==void 0)w.PubliclyAccessible=k.PubliclyAccessible;if(k.AutoMinorVersionUpgrade!==void 0)w.AutoMinorVersionUpgrade=k.AutoMinorVersionUpgrade;if(k.StorageType)w.StorageType=k.StorageType;if(k.DeletionProtection!==void 0)w.DeletionProtection=k.DeletionProtection;if(k.VpcSecurityGroupIds)k.VpcSecurityGroupIds.forEach((G,K)=>{w[`VpcSecurityGroupIds.VpcSecurityGroupId.${K+1}`]=G});if(k.Tags)k.Tags.forEach((G,K)=>{w[`Tags.Tag.${K+1}.Key`]=G.Key,w[`Tags.Tag.${K+1}.Value`]=G.Value});let E=new URLSearchParams(J(w)).toString(),z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E});return{DBInstance:(z.RestoreDBInstanceFromDBSnapshotResult||z).DBInstance}}async waitForDBInstanceAvailable(k,w=60,E=30000){for(let z=0;z<w;z++){let H=await this.describeDBInstance(k);if(H?.DBInstanceStatus==="available")return H;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(H?.DBInstanceStatus||""))throw Error(`DB instance ${k} is in terminal state: ${H?.DBInstanceStatus}`);await new Promise((G)=>setTimeout(G,E))}throw Error(`Timeout waiting for DB instance ${k} to become available`)}async waitForDBInstanceDeleted(k,w=60,E=30000){for(let z=0;z<w;z++)try{let H=await this.describeDBInstance(k);if(H?.DBInstanceStatus==="deleting"){await new Promise((G)=>setTimeout(G,E));continue}throw Error(`DB instance ${k} is in state: ${H?.DBInstanceStatus}`)}catch(H){if(H.code==="DBInstanceNotFound"||H.code==="DBInstanceNotFoundFault")return;throw H}throw Error(`Timeout waiting for DB instance ${k} to be deleted`)}}
2
+ export{U as uf};
@@ -0,0 +1,92 @@
1
+ import{Sh as y,Th as b}from"./chunk-0ccta6z6.js";import{qt as H}from"./chunk-xt3s24vr.js";import*as J from"node:crypto";import{readFileSync as m}from"node:fs";import{readdir as d}from"node:fs/promises";import{join as p}from"node:path";function f(_){if(_){let C=h(_);if(!C)throw Error(`AWS profile '${_}' not found in ~/.aws/credentials`);return C}let E=process.env.AWS_ACCESS_KEY_ID,W=process.env.AWS_SECRET_ACCESS_KEY;if(E&&W)return{accessKeyId:E,secretAccessKey:W,sessionToken:process.env.AWS_SESSION_TOKEN};return h(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function h(_){let{existsSync:E,readFileSync:W}=H("node:fs"),{homedir:C}=H("node:os"),{join:A}=H("node:path"),Y=process.env.AWS_SHARED_CREDENTIALS_FILE||A(C(),".aws","credentials");if(!E(Y))return null;let $=W(Y,"utf-8"),G=null,V,Z,Q;for(let N of $.split(`
2
+ `)){let L=N.trim();if(!L||L.startsWith("#")||L.startsWith(";"))continue;let w=L.match(/^\[([^\]]+)\]$/);if(w){if(G===_&&V&&Z)return{accessKeyId:V,secretAccessKey:Z,sessionToken:Q};G=w[1],V=void 0,Z=void 0,Q=void 0;continue}if(G===_){let[M,...U]=L.split("="),F=U.join("=").trim();switch(M.trim().toLowerCase()){case"aws_access_key_id":V=F;break;case"aws_secret_access_key":Z=F;break;case"aws_session_token":Q=F;break}}}if(G===_&&V&&Z)return{accessKeyId:V,secretAccessKey:Z,sessionToken:Q};return null}function g(_){let{buffer:E,byteOffset:W,byteLength:C}=_;if(E instanceof ArrayBuffer)return E.slice(W,W+C);let A=new ArrayBuffer(C);return new Uint8Array(A).set(new Uint8Array(_)),A}class l{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(_="us-east-1",E,W){let C=typeof _==="string"?W:_,A=typeof _==="string"?_:_.region??"us-east-1",Y=typeof _==="string"?E:_.profile,$=C?.endpoint?y({region:A,path:"/",endpoint:C.endpoint}):void 0;this.region=A,this.explicitProfile=Y,this.endpoint=$?.host,this.endpointProtocol=$?.protocol??"https",this.forcePathStyle=C?.forcePathStyle,this.explicitCredentials=C?.credentials,this.client=new b(C?.credentials,{profile:Y,endpoint:C?.endpoint,forcePathStyle:C?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let _=f(this.explicitProfile);if(_.accessKeyId&&_.secretAccessKey)return _;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(_){return this.forcePathStyle?this.s3BaseHost():`${_}.${this.s3BaseHost()}`}objectPath(_,E){return this.forcePathStyle?`/${_}/${E}`:`/${E}`}objectUrl(_,E){return`${this.endpointProtocol}://${this.s3VirtualHost(_)}${this.objectPath(_,E)}`}async listBuckets(){let _=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),E=[],C=(_?.ListAllMyBucketsResult??_)?.Buckets?.Bucket;if(C){let A=Array.isArray(C)?C:[C];for(let Y of A)E.push({Name:Y.Name,CreationDate:Y.CreationDate})}return{Buckets:E}}async createBucket(_,E){let W={};if(E?.acl)W["x-amz-acl"]=E.acl;let C;if(this.region!=="us-east-1"&&!this.endpoint)C=`<?xml version="1.0" encoding="UTF-8"?>
3
+ <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
4
+ <LocationConstraint>${this.region}</LocationConstraint>
5
+ </CreateBucketConfiguration>`,W["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,headers:W,body:C})}async deleteBucket(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`})}async emptyAndDeleteBucket(_){let E=!0;while(E){let W=await this.listAllObjects({bucket:_});if(W.length===0){E=!1;break}let C=W.map((A)=>A.Key);for(let A=0;A<C.length;A+=1000){let Y=C.slice(A,A+1000);await this.deleteObjects(_,Y)}}await this.deleteBucket(_)}async listAllObjects(_){let E=[],W;do{let C={"list-type":"2","max-keys":"1000"};if(_.prefix)C.prefix=_.prefix;if(W)C["continuation-token"]=W;let A=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_.bucket}`,queryParams:C}),Y=A?.ListBucketResult??A,$=Y?.Contents;if($){let V=Array.isArray($)?$:[$];for(let Z of V)E.push({Key:Z.Key,LastModified:Z.LastModified||"",Size:Number.parseInt(Z.Size||"0"),ETag:Z.ETag})}let G=Y?.IsTruncated;W=G==="true"||G===!0?Y?.NextContinuationToken:void 0}while(W);return E}async list(_){let E=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_.bucket}`}),W=[],A=(E?.ListBucketResult??E)?.Contents;if(A){let Y=Array.isArray(A)?A:[A];for(let $ of Y){if(_.prefix&&!$.Key?.startsWith(_.prefix))continue;if(W.push({Key:$.Key||"",LastModified:$.LastModified||"",Size:Number.parseInt($.Size||"0"),ETag:$.ETag}),_.maxKeys&&W.length>=_.maxKeys)break}}return W}async putObject(_){let E={};if(_.acl)E["x-amz-acl"]=_.acl;if(_.cacheControl)E["Cache-Control"]=_.cacheControl;if(_.contentType)E["Content-Type"]=_.contentType;if(_.metadata)for(let[A,Y]of Object.entries(_.metadata))E[`x-amz-meta-${A}`]=Y;let W=_.key.split("/").map((A)=>encodeURIComponent(A)).join("/"),C=_.body instanceof Uint8Array&&!Buffer.isBuffer(_.body)?Buffer.from(_.body):_.body;if(Buffer.isBuffer(C)||C instanceof Uint8Array){let A=Buffer.isBuffer(C)?C:Buffer.from(C),{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=this.s3VirtualHost(_.bucket),Z=this.objectPath(_.bucket,W),Q=this.objectUrl(_.bucket,W),N=new Date,L=N.toISOString().replace(/[:-]|\.\d{3}/g,""),w=N.toISOString().slice(0,10).replace(/-/g,""),M=J.createHash("sha256").update(A).digest("hex"),U={host:V,"x-amz-date":L,"x-amz-content-sha256":M,...E};if(G)U["x-amz-security-token"]=G;let F=Object.keys(U).sort().map((B)=>`${B.toLowerCase()}:${U[B].trim()}
6
+ `).join(""),x=Object.keys(U).sort().map((B)=>B.toLowerCase()).join(";"),I=["PUT",Z,"",F,x,M].join(`
7
+ `),z="AWS4-HMAC-SHA256",P=`${w}/${this.region}/s3/aws4_request`,K=[z,L,P,J.createHash("sha256").update(I).digest("hex")].join(`
8
+ `),v=J.createHmac("sha256",`AWS4${$}`).update(w).digest(),X=J.createHmac("sha256",v).update(this.region).digest(),O=J.createHmac("sha256",X).update("s3").digest(),j=J.createHmac("sha256",O).update("aws4_request").digest(),T=J.createHmac("sha256",j).update(K).digest("hex"),R=`${z} Credential=${Y}/${P}, SignedHeaders=${x}, Signature=${T}`,D=await fetch(Q,{method:"PUT",headers:{...U,Authorization:R},body:g(A)});if(!D.ok){let B=await D.text();throw Error(`S3 PUT failed: ${D.status} ${B}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${W}`,bucket:_.bucket,headers:E,body:_.body})}async getObject(_,E){let W=E.split("/").map((A)=>encodeURIComponent(A)).join("/");return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${W}`,bucket:_,rawResponse:!0})}async getObjectBytes(_,E){let{accessKeyId:W,secretAccessKey:C,sessionToken:A}=this.getCredentials(),Y=this.s3VirtualHost(_),$=E.split("/").map((B)=>encodeURIComponent(B)).join("/"),G=this.objectPath(_,$),V=this.objectUrl(_,$),Z=new Date,Q=Z.toISOString().replace(/[:-]|\.\d{3}/g,""),N=Z.toISOString().slice(0,10).replace(/-/g,""),L=J.createHash("sha256").update("").digest("hex"),w={host:Y,"x-amz-date":Q,"x-amz-content-sha256":L};if(A)w["x-amz-security-token"]=A;let M=Object.keys(w).sort().map((B)=>`${B.toLowerCase()}:${w[B].trim()}
9
+ `).join(""),U=Object.keys(w).sort().map((B)=>B.toLowerCase()).join(";"),F=["GET",G,"",M,U,L].join(`
10
+ `),x="AWS4-HMAC-SHA256",I=`${N}/${this.region}/s3/aws4_request`,z=[x,Q,I,J.createHash("sha256").update(F).digest("hex")].join(`
11
+ `),P=J.createHmac("sha256",`AWS4${C}`).update(N).digest(),K=J.createHmac("sha256",P).update(this.region).digest(),v=J.createHmac("sha256",K).update("s3").digest(),X=J.createHmac("sha256",v).update("aws4_request").digest(),O=J.createHmac("sha256",X).update(z).digest("hex"),j=`${x} Credential=${W}/${I}, SignedHeaders=${U}, Signature=${O}`,T=await fetch(V,{method:"GET",headers:{...w,Authorization:j}});if(!T.ok){let B=await T.text();throw Error(`S3 GET failed: ${T.status} ${B}`)}let R=await T.arrayBuffer(),D=T.headers.get("content-length");return{body:new Uint8Array(R),contentType:T.headers.get("content-type")??void 0,contentLength:D?Number.parseInt(D,10):void 0}}async copyObject(_){let E={"x-amz-copy-source":`/${_.sourceBucket}/${_.sourceKey}`};if(_.metadataDirective)E["x-amz-metadata-directive"]=_.metadataDirective;if(_.contentType)E["Content-Type"]=_.contentType;if(_.metadata)for(let[W,C]of Object.entries(_.metadata))E[`x-amz-meta-${W}`]=C;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_.destinationBucket}/${_.destinationKey}`,headers:E})}async deleteObject(_,E){let W=E.split("/").map((C)=>encodeURIComponent(C)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${W}`,bucket:_})}async deleteObjects(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
12
+ <Delete>
13
+ ${E.map((A)=>`<Object><Key>${A}</Key></Object>`).join(`
14
+ `)}
15
+ </Delete>`,C=J.createHash("md5").update(W).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}`,queryParams:{delete:""},body:W,headers:{"Content-Type":"application/xml","Content-MD5":C}})}async bucketExists(_){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}`}),!0}catch{return!1}}async copy(_){let E=m(_.source);await this.putObject({bucket:_.bucket,key:_.key,body:E,acl:_.acl,cacheControl:_.cacheControl,contentType:_.contentType,metadata:_.metadata})}async sync(_){let E=await this.listFilesRecursive(_.source);for(let W of E){if(_.exclude&&_.exclude.some((Y)=>W.includes(Y)))continue;if(_.include&&!_.include.some((Y)=>W.includes(Y)))continue;let C=W.substring(_.source.length+1),A=_.prefix?`${_.prefix}/${C}`:C;if(!_.dryRun){let Y=m(W);await this.putObject({bucket:_.bucket,key:A,body:Y,acl:_.acl,cacheControl:_.cacheControl,contentType:_.contentType,metadata:_.metadata})}}}async delete(_,E){await this.deleteObject(_,E)}async deletePrefix(_,E){let C=(await this.list({bucket:_,prefix:E})).map((A)=>A.Key);if(C.length>0)await this.deleteObjects(_,C)}async getBucketSize(_,E){return(await this.list({bucket:_,prefix:E})).reduce((C,A)=>C+A.Size,0)}async listFilesRecursive(_){let E=[],W=await d(_,{withFileTypes:!0});for(let C of W){let A=p(_,C.name);if(C.isDirectory()){let Y=await this.listFilesRecursive(A);E.push(...Y)}else E.push(A)}return E}async putBucketPolicy(_,E){let{accessKeyId:W,secretAccessKey:C,sessionToken:A}=this.getCredentials(),Y=this.s3BaseHost(),$=typeof E==="string"?E:JSON.stringify(E),G=new Date,V=G.toISOString().replace(/[:-]|\.\d{3}/g,""),Z=G.toISOString().slice(0,10).replace(/-/g,""),Q=J.createHash("sha256").update($).digest("hex"),N="/"+_,L="policy=",w={host:Y,"x-amz-date":V,"x-amz-content-sha256":Q,"content-type":"application/json"};if(A)w["x-amz-security-token"]=A;let M=Object.keys(w).sort().map((D)=>`${D.toLowerCase()}:${w[D].trim()}
16
+ `).join(""),U=Object.keys(w).sort().map((D)=>D.toLowerCase()).join(";"),F=["PUT",N,"policy=",M,U,Q].join(`
17
+ `),x="AWS4-HMAC-SHA256",I=`${Z}/${this.region}/s3/aws4_request`,z=[x,V,I,J.createHash("sha256").update(F).digest("hex")].join(`
18
+ `),P=J.createHmac("sha256","AWS4"+C).update(Z).digest(),K=J.createHmac("sha256",P).update(this.region).digest(),v=J.createHmac("sha256",K).update("s3").digest(),X=J.createHmac("sha256",v).update("aws4_request").digest(),O=J.createHmac("sha256",X).update(z).digest("hex"),j=`${x} Credential=${W}/${I}, SignedHeaders=${U}, Signature=${O}`,T=`${this.endpointProtocol}://${Y}${N}?policy=`,R=await fetch(T,{method:"PUT",headers:{...w,Authorization:j},body:$});if(!R.ok){let D=await R.text();throw Error(`Failed to put bucket policy: ${R.status} ${D}`)}}async getBucketPolicy(_){let{accessKeyId:E,secretAccessKey:W,sessionToken:C}=this.getCredentials(),A=this.s3BaseHost(),Y=new Date,$=Y.toISOString().replace(/[:-]|\.\d{3}/g,""),G=Y.toISOString().slice(0,10).replace(/-/g,""),V=J.createHash("sha256").update("").digest("hex"),Z="/"+_,Q="policy=",N={host:A,"x-amz-date":$,"x-amz-content-sha256":V};if(C)N["x-amz-security-token"]=C;let L=Object.keys(N).sort().map((R)=>`${R.toLowerCase()}:${N[R].trim()}
19
+ `).join(""),w=Object.keys(N).sort().map((R)=>R.toLowerCase()).join(";"),M=["GET",Z,"policy=",L,w,V].join(`
20
+ `),U="AWS4-HMAC-SHA256",F=`${G}/${this.region}/s3/aws4_request`,x=[U,$,F,J.createHash("sha256").update(M).digest("hex")].join(`
21
+ `),I=J.createHmac("sha256","AWS4"+W).update(G).digest(),z=J.createHmac("sha256",I).update(this.region).digest(),P=J.createHmac("sha256",z).update("s3").digest(),K=J.createHmac("sha256",P).update("aws4_request").digest(),v=J.createHmac("sha256",K).update(x).digest("hex"),X=`${U} Credential=${E}/${F}, SignedHeaders=${w}, Signature=${v}`,O=`${this.endpointProtocol}://${A}${Z}?policy=`,j=await fetch(O,{method:"GET",headers:{...N,Authorization:X}});if(j.status===404)return null;if(!j.ok){let R=await j.text();throw Error(`Failed to get bucket policy: ${j.status} ${R}`)}let T=await j.text();return JSON.parse(T)}async deleteBucketPolicy(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{policy:""}})}async headBucket(_){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch(E){if(E.statusCode===404)return{exists:!1};throw E}}async headObject(_,E){try{let W=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}/${E}`,returnHeaders:!0});return{ContentLength:W?.headers?.["content-length"]?parseInt(W.headers["content-length"]):void 0,ContentType:W?.headers?.["content-type"],ETag:W?.headers?.etag,LastModified:W?.headers?.["last-modified"]}}catch(W){if(W.statusCode===404)return null;throw W}}async getObjectBuffer(_,E){let W=await this.getObject(_,E);return Buffer.from(W)}async getObjectJson(_,E){let W=await this.getObject(_,E);return JSON.parse(W)}async putObjectJson(_,E,W,C){await this.putObject({bucket:_,key:E,body:JSON.stringify(W),contentType:"application/json",...C})}async getBucketVersioning(_){return{Status:(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{versioning:""}}))?.VersioningConfiguration?.Status}}async putBucketVersioning(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
22
+ <VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
23
+ <Status>${E}</Status>
24
+ </VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:W})}async getBucketLifecycleConfiguration(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{lifecycle:""}}))?.LifecycleConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketLifecycleConfiguration(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
25
+ <LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
26
+ ${E.map((A)=>{let Y=`<Rule><ID>${A.ID}</ID><Status>${A.Status}</Status>`;if(A.Filter)Y+=`<Filter><Prefix>${A.Filter.Prefix||""}</Prefix></Filter>`;else Y+="<Filter><Prefix></Prefix></Filter>";if(A.Expiration){if(A.Expiration.Days)Y+=`<Expiration><Days>${A.Expiration.Days}</Days></Expiration>`;else if(A.Expiration.Date)Y+=`<Expiration><Date>${A.Expiration.Date}</Date></Expiration>`}if(A.Transitions)for(let $ of A.Transitions)Y+=`<Transition><Days>${$.Days}</Days><StorageClass>${$.StorageClass}</StorageClass></Transition>`;if(A.NoncurrentVersionExpiration)Y+=`<NoncurrentVersionExpiration><NoncurrentDays>${A.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return Y+="</Rule>",Y}).join("")}
27
+ </LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketLifecycleConfiguration(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{lifecycle:""}})}async getBucketCors(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{cors:""}}))?.CORSConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketCors(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
28
+ <CORSConfiguration>
29
+ ${E.map((A)=>{let Y="<CORSRule>";for(let $ of A.AllowedOrigins)Y+=`<AllowedOrigin>${$}</AllowedOrigin>`;for(let $ of A.AllowedMethods)Y+=`<AllowedMethod>${$}</AllowedMethod>`;if(A.AllowedHeaders)for(let $ of A.AllowedHeaders)Y+=`<AllowedHeader>${$}</AllowedHeader>`;if(A.ExposeHeaders)for(let $ of A.ExposeHeaders)Y+=`<ExposeHeader>${$}</ExposeHeader>`;if(A.MaxAgeSeconds)Y+=`<MaxAgeSeconds>${A.MaxAgeSeconds}</MaxAgeSeconds>`;return Y+="</CORSRule>",Y}).join("")}
30
+ </CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketCors(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{cors:""}})}async getBucketEncryption(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{encryption:""}}))?.ServerSideEncryptionConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketEncryption(_,E,W){let C=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${E}</SSEAlgorithm>`;if(W)C+=`<KMSMasterKeyID>${W}</KMSMasterKeyID>`;C+="</ApplyServerSideEncryptionByDefault>";let A=`<?xml version="1.0" encoding="UTF-8"?>
31
+ <ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
32
+ <Rule>${C}</Rule>
33
+ </ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:A})}async deleteBucketEncryption(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{encryption:""}})}async getBucketTagging(_){try{let W=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!W)return[];return Array.isArray(W)?W:[W]}catch(E){if(E.statusCode===404)return[];throw E}}async putBucketTagging(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
34
+ <Tagging>
35
+ <TagSet>${E.map((A)=>`<Tag><Key>${A.Key}</Key><Value>${A.Value}</Value></Tag>`).join("")}</TagSet>
36
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketTagging(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{tagging:""}})}async getObjectTagging(_,E){try{let C=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}/${E}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!C)return[];return Array.isArray(C)?C:[C]}catch(W){if(W.statusCode===404)return[];throw W}}async putObjectTagging(_,E,W){let A=`<?xml version="1.0" encoding="UTF-8"?>
37
+ <Tagging>
38
+ <TagSet>${W.map((Y)=>`<Tag><Key>${Y.Key}</Key><Value>${Y.Value}</Value></Tag>`).join("")}</TagSet>
39
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}/${E}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:A})}async deleteObjectTagging(_,E){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}/${E}`,queryParams:{tagging:""}})}async getBucketAcl(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putBucketAcl(_,E){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{acl:""},headers:{"x-amz-acl":E}})}async getObjectAcl(_,E){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}/${E}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putObjectAcl(_,E,W){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}/${E}`,queryParams:{acl:""},headers:{"x-amz-acl":W}})}async getBucketLocation(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{location:""}}))?.LocationConstraint||"us-east-1"}async getBucketLogging(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{logging:""}}))?.BucketLoggingStatus}async putBucketLogging(_,E,W){let C=`<?xml version="1.0" encoding="UTF-8"?>
40
+ <BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
41
+ <LoggingEnabled>
42
+ <TargetBucket>${E}</TargetBucket>
43
+ <TargetPrefix>${W}</TargetPrefix>
44
+ </LoggingEnabled>
45
+ </BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:C})}async getBucketNotificationConfiguration(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{notification:""}}))?.NotificationConfiguration}async putBucketNotificationConfiguration(_,E){let W="";if(E.LambdaFunctionConfigurations)for(let A of E.LambdaFunctionConfigurations){if(W+="<CloudFunctionConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<CloudFunction>${A.LambdaFunctionArn}</CloudFunction>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;if(A.Filter?.Key?.FilterRules){W+="<Filter><S3Key>";for(let Y of A.Filter.Key.FilterRules)W+=`<FilterRule><Name>${Y.Name}</Name><Value>${Y.Value}</Value></FilterRule>`;W+="</S3Key></Filter>"}W+="</CloudFunctionConfiguration>"}if(E.TopicConfigurations)for(let A of E.TopicConfigurations){if(W+="<TopicConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<Topic>${A.TopicArn}</Topic>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;W+="</TopicConfiguration>"}if(E.QueueConfigurations)for(let A of E.QueueConfigurations){if(W+="<QueueConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<Queue>${A.QueueArn}</Queue>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;W+="</QueueConfiguration>"}let C=`<?xml version="1.0" encoding="UTF-8"?>
46
+ <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
47
+ ${W}
48
+ </NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:C})}async getBucketWebsite(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{website:""}}))?.WebsiteConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketWebsite(_,E){let W="";if(E.RedirectAllRequestsTo)W=`<RedirectAllRequestsTo>
49
+ <HostName>${E.RedirectAllRequestsTo.HostName}</HostName>
50
+ ${E.RedirectAllRequestsTo.Protocol?`<Protocol>${E.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
51
+ </RedirectAllRequestsTo>`;else if(W=`<IndexDocument><Suffix>${E.IndexDocument}</Suffix></IndexDocument>`,E.ErrorDocument)W+=`<ErrorDocument><Key>${E.ErrorDocument}</Key></ErrorDocument>`;let C=`<?xml version="1.0" encoding="UTF-8"?>
52
+ <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
53
+ ${W}
54
+ </WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketWebsite(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{website:""}})}async getBucketReplication(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{replication:""}}))?.ReplicationConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async deleteBucketReplication(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{replication:""}})}async getPublicAccessBlock(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{publicAccessBlock:""}}))?.PublicAccessBlockConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putPublicAccessBlock(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
55
+ <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
56
+ <BlockPublicAcls>${E.BlockPublicAcls??!0}</BlockPublicAcls>
57
+ <IgnorePublicAcls>${E.IgnorePublicAcls??!0}</IgnorePublicAcls>
58
+ <BlockPublicPolicy>${E.BlockPublicPolicy??!0}</BlockPublicPolicy>
59
+ <RestrictPublicBuckets>${E.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
60
+ </PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:W})}async deletePublicAccessBlock(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl(_,E,W=3600){let{accessKeyId:C,secretAccessKey:A}=this.getCredentials(),Y=this.s3VirtualHost(_),$=new Date,G=$.toISOString().replace(/[:-]|\.\d{3}/g,""),V=$.toISOString().slice(0,10).replace(/-/g,""),Z=`${V}/${this.region}/s3/aws4_request`,Q=`${C}/${Z}`,N=E.split("/").map((P)=>encodeURIComponent(P)).join("/"),L=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":Q,"X-Amz-Date":G,"X-Amz-Expires":W.toString(),"X-Amz-SignedHeaders":"host"}),w=["GET",this.objectPath(_,N),L.toString(),`host:${Y}
61
+ `,"host","UNSIGNED-PAYLOAD"].join(`
62
+ `),M=["AWS4-HMAC-SHA256",G,Z,J.createHash("sha256").update(w).digest("hex")].join(`
63
+ `),U=J.createHmac("sha256",`AWS4${A}`).update(V).digest(),F=J.createHmac("sha256",U).update(this.region).digest(),x=J.createHmac("sha256",F).update("s3").digest(),I=J.createHmac("sha256",x).update("aws4_request").digest(),z=J.createHmac("sha256",I).update(M).digest("hex");return L.append("X-Amz-Signature",z),`${this.endpointProtocol}://${Y}${this.objectPath(_,N)}?${L.toString()}`}generatePresignedPutUrl(_,E,W,C=3600){let{accessKeyId:A,secretAccessKey:Y}=this.getCredentials(),$=this.s3VirtualHost(_),G=new Date,V=G.toISOString().replace(/[:-]|\.\d{3}/g,""),Z=G.toISOString().slice(0,10).replace(/-/g,""),Q=`${Z}/${this.region}/s3/aws4_request`,N=`${A}/${Q}`,L=E.split("/").map((K)=>encodeURIComponent(K)).join("/"),w=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":N,"X-Amz-Date":V,"X-Amz-Expires":C.toString(),"X-Amz-SignedHeaders":"content-type;host"}),M=["PUT",this.objectPath(_,L),w.toString(),`content-type:${W}
64
+ host:${$}
65
+ `,"content-type;host","UNSIGNED-PAYLOAD"].join(`
66
+ `),U=["AWS4-HMAC-SHA256",V,Q,J.createHash("sha256").update(M).digest("hex")].join(`
67
+ `),F=J.createHmac("sha256",`AWS4${Y}`).update(Z).digest(),x=J.createHmac("sha256",F).update(this.region).digest(),I=J.createHmac("sha256",x).update("s3").digest(),z=J.createHmac("sha256",I).update("aws4_request").digest(),P=J.createHmac("sha256",z).update(U).digest("hex");return w.append("X-Amz-Signature",P),`${this.endpointProtocol}://${$}${this.objectPath(_,L)}?${w.toString()}`}async createMultipartUpload(_,E,W){let C={};if(W?.contentType)C["Content-Type"]=W.contentType;if(W?.metadata)for(let[G,V]of Object.entries(W.metadata))C[`x-amz-meta-${G}`]=V;let A=E.split("/").map((G)=>encodeURIComponent(G)).join("/"),Y=await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${A}`,bucket:_,queryParams:{uploads:""},headers:C});return{UploadId:(Y?.InitiateMultipartUploadResult??Y)?.UploadId}}async uploadPart(_,E,W,C,A){let{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=this.s3VirtualHost(_),Z=E.split("/").map((q)=>encodeURIComponent(q)).join("/"),Q=this.objectPath(_,Z),N=`${this.objectUrl(_,Z)}?partNumber=${C}&uploadId=${encodeURIComponent(W)}`,L=new Date,w=L.toISOString().replace(/[:-]|\.\d{3}/g,""),M=L.toISOString().slice(0,10).replace(/-/g,""),U=J.createHash("sha256").update(A).digest("hex"),F={host:V,"x-amz-date":w,"x-amz-content-sha256":U};if(G)F["x-amz-security-token"]=G;let x=Object.keys(F).sort().map((q)=>`${q.toLowerCase()}:${F[q].trim()}
68
+ `).join(""),I=Object.keys(F).sort().map((q)=>q.toLowerCase()).join(";"),z=["PUT",Q,`partNumber=${C}&uploadId=${encodeURIComponent(W)}`,x,I,U].join(`
69
+ `),P="AWS4-HMAC-SHA256",K=`${M}/${this.region}/s3/aws4_request`,v=[P,w,K,J.createHash("sha256").update(z).digest("hex")].join(`
70
+ `),X=J.createHmac("sha256",`AWS4${$}`).update(M).digest(),O=J.createHmac("sha256",X).update(this.region).digest(),j=J.createHmac("sha256",O).update("s3").digest(),T=J.createHmac("sha256",j).update("aws4_request").digest(),R=J.createHmac("sha256",T).update(v).digest("hex"),D=`${P} Credential=${Y}/${K}, SignedHeaders=${I}, Signature=${R}`,B=await fetch(N,{method:"PUT",headers:{...F,Authorization:D},body:g(A)});if(!B.ok){let q=await B.text();throw Error(`Upload part failed: ${B.status} ${q}`)}return{ETag:B.headers.get("etag")||""}}async completeMultipartUpload(_,E,W,C){let A=E.split("/").map((G)=>encodeURIComponent(G)).join("/"),$=`<?xml version="1.0" encoding="UTF-8"?>
71
+ <CompleteMultipartUpload>${C.sort((G,V)=>G.PartNumber-V.PartNumber).map((G)=>`<Part><PartNumber>${G.PartNumber}</PartNumber><ETag>${G.ETag}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${A}`,bucket:_,queryParams:{uploadId:W},headers:{"Content-Type":"application/xml"},body:$})}async abortMultipartUpload(_,E,W){let C=E.split("/").map((A)=>encodeURIComponent(A)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${C}`,bucket:_,queryParams:{uploadId:W}})}async listMultipartUploads(_){let E=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/",bucket:_,queryParams:{uploads:""}}),W=(E?.ListMultipartUploadsResult??E)?.Upload;if(!W)return[];return(Array.isArray(W)?W:[W]).map((A)=>({Key:A.Key,UploadId:A.UploadId,Initiated:A.Initiated}))}async restoreObject(_,E,W,C="Standard"){let A=`<?xml version="1.0" encoding="UTF-8"?>
72
+ <RestoreRequest>
73
+ <Days>${W}</Days>
74
+ <GlacierJobParameters>
75
+ <Tier>${C}</Tier>
76
+ </GlacierJobParameters>
77
+ </RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}/${E}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:A})}async selectObjectContent(_,E,W,C,A="JSON"){let Y="";if(C==="CSV")Y="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(C==="JSON")Y="<JSON><Type>DOCUMENT</Type></JSON>";else Y="<Parquet/>";let $="";if(A==="CSV")$="<CSV/>";else $="<JSON/>";let G=`<?xml version="1.0" encoding="UTF-8"?>
78
+ <SelectObjectContentRequest>
79
+ <Expression>${W}</Expression>
80
+ <ExpressionType>SQL</ExpressionType>
81
+ <InputSerialization>${Y}</InputSerialization>
82
+ <OutputSerialization>${$}</OutputSerialization>
83
+ </SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}/${E}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:G,rawResponse:!0})}async getSignedUrl(_){let{bucket:E,key:W,expiresIn:C=3600,operation:A="getObject"}=_,{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=new Date,Z=V.toISOString().replace(/[:-]|\.\d{3}/g,""),Q=V.toISOString().slice(0,10).replace(/-/g,""),N=this.s3VirtualHost(E),L=A==="putObject"?"PUT":"GET",w="AWS4-HMAC-SHA256",M=`${Q}/${this.region}/s3/aws4_request`,F={"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":`${Y}/${M}`,"X-Amz-Date":Z,"X-Amz-Expires":C.toString(),"X-Amz-SignedHeaders":"host"};if(G)F["X-Amz-Security-Token"]=G;let I=Object.keys(F).sort().map((S)=>`${encodeURIComponent(S)}=${encodeURIComponent(F[S])}`).join("&"),z=W.split("/").map((S)=>encodeURIComponent(S)).join("/"),P=this.objectPath(E,z),K=`host:${N}
84
+ `,O=[L,P,I,K,"host","UNSIGNED-PAYLOAD"].join(`
85
+ `),j=["AWS4-HMAC-SHA256",Z,M,J.createHash("sha256").update(O).digest("hex")].join(`
86
+ `),T=J.createHmac("sha256",`AWS4${$}`).update(Q).digest(),R=J.createHmac("sha256",T).update(this.region).digest(),D=J.createHmac("sha256",R).update("s3").digest(),B=J.createHmac("sha256",D).update("aws4_request").digest(),q=J.createHmac("sha256",B).update(j).digest("hex");return`${this.endpointProtocol}://${N}${P}?${I}&X-Amz-Signature=${q}`}async listObjects(_){let{bucket:E,prefix:W,maxKeys:C=1000,continuationToken:A}=_,Y={"list-type":"2","max-keys":C.toString()};if(W)Y.prefix=W;if(A)Y["continuation-token"]=A;let $=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${E}`,queryParams:Y}),G=[],V=$?.ListBucketResult??$;if(V?.Contents){let Z=Array.isArray(V.Contents)?V.Contents:[V.Contents];for(let Q of Z)G.push({Key:Q.Key||"",LastModified:Q.LastModified||"",Size:Number.parseInt(Q.Size||"0"),ETag:Q.ETag})}return{objects:G,nextContinuationToken:V?.NextContinuationToken}}async emptyBucket(_){let E=0,W=await this.listAllObjects({bucket:_});if(W.length>0)for(let C=0;C<W.length;C+=1000){let Y=W.slice(C,C+1000).map(($)=>$.Key);await this.deleteObjects(_,Y),E+=Y.length}try{let C,A;do{let Y=await this.listObjectVersions({bucket:_,keyMarker:C,versionIdMarker:A,maxKeys:1000}),$=[];if(Y.versions)for(let G of Y.versions)$.push({Key:G.Key,VersionId:G.VersionId});if(Y.deleteMarkers)for(let G of Y.deleteMarkers)$.push({Key:G.Key,VersionId:G.VersionId});if($.length>0)await this.deleteObjectVersions(_,$),E+=$.length;C=Y.nextKeyMarker,A=Y.nextVersionIdMarker}while(C)}catch{}return{deletedCount:E}}async listObjectVersions(_){let{bucket:E,prefix:W,keyMarker:C,versionIdMarker:A,maxKeys:Y=1000}=_,$={versions:"","max-keys":Y.toString()};if(W)$.prefix=W;if(C)$["key-marker"]=C;if(A)$["version-id-marker"]=A;let G=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${E}`,queryParams:$}),V=[],Z=[];if(G.Version){let Q=Array.isArray(G.Version)?G.Version:[G.Version];for(let N of Q)V.push({Key:N.Key,VersionId:N.VersionId,IsLatest:N.IsLatest==="true"})}if(G.DeleteMarker){let Q=Array.isArray(G.DeleteMarker)?G.DeleteMarker:[G.DeleteMarker];for(let N of Q)Z.push({Key:N.Key,VersionId:N.VersionId,IsLatest:N.IsLatest==="true"})}return{versions:V,deleteMarkers:Z,nextKeyMarker:G.NextKeyMarker,nextVersionIdMarker:G.NextVersionIdMarker}}async deleteObjectVersions(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
87
+ <Delete>
88
+ <Quiet>true</Quiet>
89
+ ${E.map((A)=>`<Object><Key>${A.Key}</Key>${A.VersionId?`<VersionId>${A.VersionId}</VersionId>`:""}</Object>`).join(`
90
+ `)}
91
+ </Delete>`,C=J.createHash("md5").update(W).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}`,queryParams:{delete:""},body:W,headers:{"Content-Type":"application/xml","Content-MD5":C}})}}
92
+ export{f as Qh,l as Rh};
@@ -0,0 +1,141 @@
1
+ import{Th as A}from"./chunk-0ccta6z6.js";class N{client;constructor(J,Q){this.client=Q??new A(void 0,{profile:J})}collectionItems(J,Q){let z=J?.Items??J?.[Q];if(!z)return[];if(Array.isArray(z))return z;let Y=z[Q]??z.Item;if(Y===void 0)return typeof z==="object"&&(z.Id||z.PathPattern)?[z]:[];return Array.isArray(Y)?Y:[Y]}validateExistingOriginInput(J,Q){if(!/^[A-Z0-9]{8,32}$/.test(J))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(Q.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(Q.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let z=Q.pathPattern.startsWith("/")?Q.pathPattern:`/${Q.pathPattern}`;if(z==="/"||z==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(z))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(Q.originPath&&(!Q.originPath.startsWith("/")||Q.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(Q.customHeaders??{}).some(([Y,_])=>!/^[A-Za-z0-9-]{1,64}$/.test(Y)||!_||_.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...Q,pathPattern:z}}async upsertExistingDistributionOrigin(J,Q){let z=this.validateExistingOriginInput(J,Q),Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),_=Y.headers?.etag||Y.headers?.ETag||Y.ETag||"",Z=Y.body?.DistributionConfig||Y.DistributionConfig||Y.body;if(!Z||Z.Enabled===void 0||!_)throw Error("Failed to read an ETag-protected CloudFront distribution config");let $=this.collectionItems(Z.Origins,"Origin"),j=this.collectionItems(Z.CacheBehaviors,"CacheBehavior"),L=$.find((H)=>String(H.Id)===z.id),q=j.find((H)=>String(H.PathPattern)===z.pathPattern);if(L&&String(L.DomainName)!==z.domainName&&!z.replaceExisting)throw Error(`Origin ${z.id} already targets ${L.DomainName}; pass replaceExisting only after reviewing the live config`);if(q&&String(q.TargetOriginId)!==z.id&&!z.replaceExisting)throw Error(`Path ${z.pathPattern} already targets ${q.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let W={Id:z.id,DomainName:z.domainName,OriginPath:z.originPath??"",CustomHeaders:{Quantity:Object.keys(z.customHeaders??{}).length,...Object.keys(z.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(z.customHeaders).map(([H,K])=>({HeaderName:H,HeaderValue:K}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:z.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...z.originAccessControlId?{OriginAccessControlId:z.originAccessControlId}:{}},F=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],D={PathPattern:z.pathPattern,TargetOriginId:z.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:F.length,Items:{Method:F},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},G=L?$.map((H)=>String(H.Id)===z.id?W:H):[...$,W],S=q?j.map((H)=>String(H.PathPattern)===z.pathPattern?D:H):[...j,D],U=JSON.stringify($)!==JSON.stringify(G)||JSON.stringify(j)!==JSON.stringify(S);if(!U||z.dryRun)return{distributionId:J,originId:z.id,domainName:z.domainName,pathPattern:z.pathPattern,changed:U,applied:!1,etag:_};Z.Origins={Quantity:G.length,Items:{Origin:G}},Z.CacheBehaviors={Quantity:S.length,...S.length?{Items:{CacheBehavior:S}}:{}};let M=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:this.buildDistributionConfigXml(Z),headers:{"Content-Type":"application/xml","If-Match":_}});return{distributionId:J,originId:z.id,domainName:z.domainName,pathPattern:z.pathPattern,changed:!0,applied:!0,etag:M.ETag||M.headers?.etag||""}}async removeExistingDistributionOrigin(J,Q){let z=this.validateExistingOriginInput(J,Q),Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),_=Y.headers?.etag||Y.headers?.ETag||Y.ETag||"",Z=Y.body?.DistributionConfig||Y.DistributionConfig||Y.body;if(!Z||Z.Enabled===void 0||!_)throw Error("Failed to read an ETag-protected CloudFront distribution config");let $=this.collectionItems(Z.Origins,"Origin"),j=this.collectionItems(Z.CacheBehaviors,"CacheBehavior"),L=$.find((S)=>String(S.Id)===z.id),q=j.find((S)=>String(S.PathPattern)===z.pathPattern);if(L&&String(L.DomainName)!==z.domainName)throw Error(`Origin ${z.id} no longer targets ${z.domainName}; refusing ambiguous removal`);if(q&&String(q.TargetOriginId)!==z.id)throw Error(`Path ${z.pathPattern} no longer targets ${z.id}; refusing ambiguous removal`);if(!q)return{distributionId:J,originId:z.id,domainName:z.domainName,pathPattern:z.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:_};let W=j.filter((S)=>String(S.PathPattern)!==z.pathPattern),F=String(Z.DefaultCacheBehavior?.TargetOriginId)===z.id||W.some((S)=>String(S.TargetOriginId)===z.id),D=F?$:$.filter((S)=>String(S.Id)!==z.id);if(z.dryRun)return{distributionId:J,originId:z.id,domainName:z.domainName,pathPattern:z.pathPattern,changed:!0,applied:!1,originRemoved:!F&&!!L,etag:_};Z.Origins={Quantity:D.length,Items:{Origin:D}},Z.CacheBehaviors={Quantity:W.length,...W.length?{Items:{CacheBehavior:W}}:{}};let G=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:this.buildDistributionConfigXml(Z),headers:{"Content-Type":"application/xml","If-Match":_}});return{distributionId:J,originId:z.id,domainName:z.domainName,pathPattern:z.pathPattern,changed:!0,applied:!0,originRemoved:!F&&!!L,etag:G.ETag||G.headers?.etag||""}}async createInvalidation(J){let Q=J.callerReference||Date.now().toString(),z=`<?xml version="1.0" encoding="UTF-8"?>
2
+ <InvalidationBatch>
3
+ <Paths>
4
+ <Quantity>${J.paths.length}</Quantity>
5
+ <Items>
6
+ ${J.paths.map((_)=>`<Path>${_}</Path>`).join(`
7
+ `)}
8
+ </Items>
9
+ </Paths>
10
+ <CallerReference>${Q}</CallerReference>
11
+ </InvalidationBatch>`,Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${J.distributionId}/invalidation`,body:z,headers:{"Content-Type":"application/xml"}});return{Id:Y.Id||Y.Invalidation?.Id,Status:Y.Status||Y.Invalidation?.Status||"InProgress",CreateTime:Y.CreateTime||Y.Invalidation?.CreateTime||new Date().toISOString()}}async getInvalidation(J,Q){let z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/invalidation/${Q}`});return{Id:z.Id||z.Invalidation?.Id,Status:z.Status||z.Invalidation?.Status,CreateTime:z.CreateTime||z.Invalidation?.CreateTime}}async listInvalidations(J){let Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/invalidation`}),z=[];if(Q.InvalidationSummary){let Y=Array.isArray(Q.InvalidationSummary)?Q.InvalidationSummary:[Q.InvalidationSummary];z.push(...Y.map((_)=>({Id:_.Id,Status:_.Status,CreateTime:_.CreateTime})))}return z}async waitForInvalidation(J,Q){let Y=0;while(Y<60){if((await this.getInvalidation(J,Q)).Status==="Completed")return;await new Promise((Z)=>setTimeout(Z,5000)),Y++}throw Error(`Timeout waiting for invalidation ${Q} to complete`)}async listDistributions(){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/distribution"}),Q=[],Y=(J.DistributionList||J).Items,_=[];if(Array.isArray(Y))_=Y;else if(Y?.DistributionSummary)_=Array.isArray(Y.DistributionSummary)?Y.DistributionSummary:[Y.DistributionSummary];return Q.push(..._.map((Z)=>({Id:Z.Id,ARN:Z.ARN,Status:Z.Status,DomainName:Z.DomainName,Aliases:Z.Aliases||void 0,Enabled:Z.Enabled==="true"||Z.Enabled===!0}))),Q}async getDistribution(J){let Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}`}),z=Q.Distribution||Q;return{Id:z.Id,ARN:z.ARN,Status:z.Status,DomainName:z.DomainName,Aliases:z.DistributionConfig?.Aliases?.Items||z.Aliases?.Items||[],Enabled:z.DistributionConfig?.Enabled==="true"||z.DistributionConfig?.Enabled===!0}}async getDistributionConfig(J){let Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`});return{ETag:Q.ETag||"",DistributionConfig:Q.DistributionConfig||Q}}async invalidateAll(J){return this.createInvalidation({distributionId:J,paths:["/*"]})}async invalidatePaths(J,Q){let z=Q.map((Y)=>Y.startsWith("/")?Y:`/${Y}`);return this.createInvalidation({distributionId:J,paths:z})}async invalidatePattern(J,Q){let z=Q.startsWith("/")?Q:`/${Q}`;return this.createInvalidation({distributionId:J,paths:[z]})}async invalidateAfterDeployment(J){let{distributionId:Q,changedPaths:z,invalidateAll:Y=!1,wait:_=!1}=J,Z;if(Y||!z||z.length===0)Z=await this.invalidateAll(Q);else Z=await this.invalidatePaths(Q,z);if(_)await this.waitForInvalidation(Q,Z.Id);return{invalidationId:Z.Id,status:Z.Status}}async findDistributionByDomain(J){return(await this.listDistributions()).find((Y)=>{if(Y.DomainName===J)return!0;if(Y.Aliases?.Items&&Y.Aliases.Items.includes(J))return!0;return!1})||null}async batchInvalidate(J,Q=["/*"]){return await Promise.all(J.map(async(Y)=>{let _=await this.createInvalidation({distributionId:Y,paths:Q});return{distributionId:Y,invalidationId:_.Id,status:_.Status}}))}async updateCustomErrorResponses(J){let{distributionId:Q,customErrorResponses:z}=J,Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${Q}/config`,returnHeaders:!0}),_=Y.headers?.etag||Y.headers?.ETag||"",Z=Y.body?.DistributionConfig||(Y.body?.Enabled!==void 0?Y.body:void 0)||Y.DistributionConfig;if(!Z||Z.Enabled===void 0)throw Error("Failed to get current distribution config");if(z.length===0)Z.CustomErrorResponses={Quantity:0};else Z.CustomErrorResponses={Quantity:z.length,Items:{CustomErrorResponse:z.map((q)=>({ErrorCode:q.errorCode,...q.responsePagePath&&{ResponsePagePath:q.responsePagePath},...q.responseCode&&{ResponseCode:q.responseCode},...q.errorCachingMinTTL!==void 0&&{ErrorCachingMinTTL:q.errorCachingMinTTL}}))}};let $=this.buildDistributionConfigXml(Z),j=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${Q}/config`,body:$,headers:{"Content-Type":"application/xml","If-Match":_}}),L=j.Distribution||j;return{Distribution:{Id:L.Id,ARN:L.ARN,Status:L.Status,DomainName:L.DomainName,Aliases:L.DistributionConfig?.Aliases?.Items||[],Enabled:L.DistributionConfig?.Enabled==="true"||L.DistributionConfig?.Enabled===!0},ETag:j.ETag||""}}async removeCustomErrorResponses(J){return this.updateCustomErrorResponses({distributionId:J,customErrorResponses:[]})}async updateDistribution(J){let{distributionId:Q,aliases:z,certificateArn:Y,comment:_}=J,Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${Q}/config`,returnHeaders:!0}),$=Z.headers?.etag||Z.headers?.ETag||"",j=Z.body?.DistributionConfig||(Z.body?.Enabled!==void 0?Z.body:void 0)||Z.DistributionConfig;if(!j||j.Enabled===void 0)throw Error("Failed to get current distribution config");if(z&&z.length>0)j.Aliases={Quantity:z.length,Items:{Item:z}};if(Y)j.ViewerCertificate={ACMCertificateArn:Y,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CertificateSource:"acm"};if(_)j.Comment=_;let L=this.buildDistributionConfigXml(j),q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${Q}/config`,body:L,headers:{"Content-Type":"application/xml","If-Match":$}}),W=q.Distribution||q;return{Distribution:{Id:W.Id,ARN:W.ARN,Status:W.Status,DomainName:W.DomainName,Aliases:z?{Quantity:z.length,Items:z}:{Quantity:0,Items:[]},Enabled:W.DistributionConfig?.Enabled==="true"||W.DistributionConfig?.Enabled===!0},ETag:q.ETag||""}}buildDistributionConfigXml(J){let Q=(Z)=>{return Z.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")},z={Items:"",Methods:"Method",Headers:"Name",Cookies:"Name",QueryStringCacheKeys:"Name",TrustedKeyGroups:"KeyGroup",TrustedSigners:"AwsAccountNumber",LambdaFunctionAssociations:"LambdaFunctionAssociation",FunctionAssociations:"FunctionAssociation",CacheBehaviors:"CacheBehavior",CustomErrorResponses:"CustomErrorResponse",GeoRestriction:"Location"},Y={Origins:"Origin",Aliases:"CNAME",AllowedMethods:"Method",CachedMethods:"Method",CustomErrorResponses:"CustomErrorResponse",CacheBehaviors:"CacheBehavior"},_=(Z,$,j="",L="")=>{if($===null||$===void 0)return"";if(Z.startsWith("@_")||Z==="?xml")return"";if(typeof $==="boolean")return`${j}<${Z}>${$}</${Z}>
12
+ `;if(typeof $==="number"||typeof $==="string")return`${j}<${Z}>${Q(String($))}</${Z}>
13
+ `;if(Array.isArray($)){let q=z[Z]||Z.replace(/s$/,"");return $.map((W)=>_(q,W,j,Z)).join("")}if(typeof $==="object"){if(Z==="Items"){let W=Y[L]||"",F=Object.keys($).filter((D)=>!D.startsWith("@_"));if(F.length===1&&!Array.isArray($[F[0]])){let D=F[0],G=$[D];if(typeof G==="string")return`${j}<Items>
14
+ ${j} <${D}>${Q(G)}</${D}>
15
+ ${j}</Items>
16
+ `;else if(typeof G==="object"&&!Array.isArray(G))return`${j}<Items>
17
+ ${_(D,G,j+" ",Z)}${j}</Items>
18
+ `}if(F.length===1&&Array.isArray($[F[0]])){let D=F[0],G=$[D],S="";for(let U of G)if(typeof U==="string")S+=`${j} <${D}>${Q(U)}</${D}>
19
+ `;else S+=_(D,U,j+" ",Z);return`${j}<Items>
20
+ ${S}${j}</Items>
21
+ `}if(Array.isArray($)){let D="",G=W||"Item";for(let S of $)if(typeof S==="string")D+=`${j} <${G}>${Q(S)}</${G}>
22
+ `;else D+=_(G,S,j+" ",Z);return`${j}<Items>
23
+ ${D}${j}</Items>
24
+ `}}let q="";for(let[W,F]of Object.entries($))if(!W.startsWith("@_"))q+=_(W,F,j+" ",Z);if(q==="")return`${j}<${Z}/>
25
+ `;return`${j}<${Z}>
26
+ ${q}${j}</${Z}>
27
+ `}return""};return`<?xml version="1.0" encoding="UTF-8"?>
28
+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
29
+ ${Object.entries(J).filter(([Z])=>!Z.startsWith("@_")).map(([Z,$])=>_(Z,$," ","DistributionConfig")).join("")}</DistributionConfig>`}async ensureDynamicHttpMethods(J){let Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),z=Q.headers?.etag||Q.headers?.ETag||"",Y=Q.body?.DistributionConfig||Q.DistributionConfig||Q.body;if(!Y)throw Error("Failed to get current distribution config");let _=!1,Z=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],$=(q)=>{if(!q)return[];let W=q.Items;if(!W)return[];if(Array.isArray(W))return W.map(String);if(typeof W==="object"&&W.Method){let F=W.Method;return Array.isArray(F)?F.map(String):[String(F)]}if(W.Item)return Array.isArray(W.Item)?W.Item.map(String):[String(W.Item)];return[]},j=Y.DefaultCacheBehavior;if(j){if(!$(j.AllowedMethods).includes("POST"))j.AllowedMethods={Quantity:Z.length,Items:{Method:Z},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},_=!0}if(!_)return!1;let L=this.buildDistributionConfigXml(Y);return await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:L,headers:{"Content-Type":"application/xml","If-Match":z}}),!0}async addAliases(J,Q,z){return this.updateDistribution({distributionId:J,aliases:Q,certificateArn:z})}async createFunction(J){let{name:Q,code:z,comment:Y="",runtime:_="cloudfront-js-2.0"}=J,Z=`<?xml version="1.0" encoding="UTF-8"?>
30
+ <CreateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
31
+ <Name>${Q}</Name>
32
+ <FunctionConfig>
33
+ <Comment>${Y}</Comment>
34
+ <Runtime>${_}</Runtime>
35
+ </FunctionConfig>
36
+ <FunctionCode>${Buffer.from(z).toString("base64")}</FunctionCode>
37
+ </CreateFunctionRequest>`,$=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/function",body:Z,headers:{"Content-Type":"application/xml"}}),j=$.FunctionSummary||$;return{FunctionARN:j.FunctionMetadata?.FunctionARN||j.FunctionARN,Name:j.Name||Q,Stage:j.FunctionMetadata?.Stage||"DEVELOPMENT",ETag:$.ETag||""}}async listFunctions(){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/function"}),Q=[],z=J.FunctionList?.Items?.FunctionSummary;if(z){let Y=Array.isArray(z)?z:[z];for(let _ of Y)Q.push({Name:_.Name,FunctionARN:_.FunctionMetadata?.FunctionARN,Stage:_.FunctionMetadata?.Stage,CreatedTime:_.FunctionMetadata?.CreatedTime,LastModifiedTime:_.FunctionMetadata?.LastModifiedTime})}return Q}async getFunction(J,Q="LIVE"){try{let z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${J}`,queryParams:{Stage:Q},returnHeaders:!0}),Y=z.body?.FunctionSummary||z.FunctionSummary||z.body||z;return{FunctionARN:Y.FunctionMetadata?.FunctionARN,Name:Y.Name||J,Stage:Y.FunctionMetadata?.Stage||Q,ETag:z.headers?.etag||z.ETag||"",FunctionCode:Y.FunctionCode}}catch(z){if(z.message?.includes("404")||z.message?.includes("NoSuchFunctionExists"))return null;throw z}}async publishFunction(J,Q){let z,Y;if(typeof J==="object")z=J.Name,Y=J.IfMatch;else z=J,Y=Q;if(!Y){let $=await this.getFunction(z,"DEVELOPMENT");if(!$)throw Error(`Function ${z} not found`);Y=$.ETag}let _=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/function/${z}/publish`,headers:{"If-Match":Y}}),Z=_.FunctionSummary||_;return{FunctionARN:Z.FunctionMetadata?.FunctionARN,Stage:Z.FunctionMetadata?.Stage||"LIVE",FunctionSummary:Z}}async describeFunction(J){let{Name:Q,Stage:z="DEVELOPMENT"}=J,Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${Q}/describe`,queryParams:{Stage:z},returnHeaders:!0});return{ETag:Y.headers?.etag||Y.ETag||"",FunctionSummary:Y.body?.FunctionSummary||Y.FunctionSummary||Y.body||Y}}async updateFunction(J){let{Name:Q,FunctionCode:z,FunctionConfig:Y,IfMatch:_}=J,Z=`<?xml version="1.0" encoding="UTF-8"?>
38
+ <UpdateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
39
+ <FunctionConfig>
40
+ <Comment>${Y.Comment}</Comment>
41
+ <Runtime>${Y.Runtime}</Runtime>
42
+ </FunctionConfig>
43
+ <FunctionCode>${Buffer.from(z).toString("base64")}</FunctionCode>
44
+ </UpdateFunctionRequest>`,$=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/function/${Q}`,body:Z,headers:{"Content-Type":"application/xml","If-Match":_},returnHeaders:!0});return{ETag:$.headers?.etag||$.ETag||"",FunctionSummary:$.body?.FunctionSummary||$.FunctionSummary||$.body||$}}async deleteFunction(J,Q){let z=Q;if(!z){let Y=await this.getFunction(J,"DEVELOPMENT");if(!Y)return;z=Y.ETag}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/function/${J}`,headers:{"If-Match":z}})}async createIndexRewriteFunction(J){return this.createFunction({name:J,code:`function handler(event) {
45
+ const request = event.request;
46
+ var uri = request.uri;
47
+
48
+ // Check if the request is for a directory (ends with /)
49
+ if (uri.endsWith('/')) {
50
+ request.uri += 'index.html';
51
+ }
52
+ // Check if the request doesn't have a file extension
53
+ else if (!uri.includes('.')) {
54
+ // Add trailing slash to redirect to directory
55
+ request.uri += '/index.html';
56
+ }
57
+
58
+ return request;
59
+ }`,comment:"Rewrite directory requests to index.html for S3 static sites",runtime:"cloudfront-js-2.0"})}async listOriginAccessControls(){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/origin-access-control"}),Q=[];if(J.OriginAccessControlList?.Items?.OriginAccessControlSummary){let z=Array.isArray(J.OriginAccessControlList.Items.OriginAccessControlSummary)?J.OriginAccessControlList.Items.OriginAccessControlSummary:[J.OriginAccessControlList.Items.OriginAccessControlSummary];Q.push(...z.map((Y)=>({Id:Y.Id,Name:Y.Name,Description:Y.Description,SigningProtocol:Y.SigningProtocol,SigningBehavior:Y.SigningBehavior,OriginAccessControlOriginType:Y.OriginAccessControlOriginType})))}return Q}async createOriginAccessControl(J){let{name:Q,description:z=`OAC for ${Q}`,signingProtocol:Y="sigv4",signingBehavior:_="always",originType:Z="s3"}=J,$=`<?xml version="1.0" encoding="UTF-8"?>
60
+ <OriginAccessControlConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
61
+ <Name>${Q}</Name>
62
+ <Description>${z}</Description>
63
+ <SigningProtocol>${Y}</SigningProtocol>
64
+ <SigningBehavior>${_}</SigningBehavior>
65
+ <OriginAccessControlOriginType>${Z}</OriginAccessControlOriginType>
66
+ </OriginAccessControlConfig>`,j=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/origin-access-control",body:$,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),L=j.body?.OriginAccessControl||j.OriginAccessControl||j.body||j;return{Id:L.Id,Name:L.OriginAccessControlConfig?.Name||Q,Description:L.OriginAccessControlConfig?.Description||z,SigningProtocol:L.OriginAccessControlConfig?.SigningProtocol||Y,SigningBehavior:L.OriginAccessControlConfig?.SigningBehavior||_,OriginAccessControlOriginType:L.OriginAccessControlConfig?.OriginAccessControlOriginType||Z,ETag:j.headers?.etag||j.ETag||""}}async findOrCreateOriginAccessControl(J,Q="s3"){let Y=(await this.listOriginAccessControls()).find((Z)=>Z.Name===J&&Z.OriginAccessControlOriginType===Q);if(Y)return{Id:Y.Id,Name:Y.Name,isNew:!1};let _=await this.createOriginAccessControl({name:J,originType:Q});return{Id:_.Id,Name:_.Name,isNew:!0}}async createDistributionForS3(J){let{bucketName:Q,bucketRegion:z,originAccessControlId:Y,aliases:_=[],certificateArn:Z,defaultRootObject:$="index.html",comment:j=`Distribution for ${Q}`,priceClass:L="PriceClass_100",enabled:q=!0,trustedKeyGroupIds:W=[],mediaDelivery:F=!1}=J,D=`S3-${Q}`,G=`${Q}.s3.${z}.amazonaws.com`,S=`${Date.now()}-${Math.random().toString(36).slice(2)}`,U=W.length>0?`<TrustedKeyGroups>
67
+ <Enabled>true</Enabled>
68
+ <Quantity>${W.length}</Quantity>
69
+ <Items>${W.map((w)=>`<KeyGroup>${w}</KeyGroup>`).join("")}</Items>
70
+ </TrustedKeyGroups>`:"<TrustedKeyGroups><Enabled>false</Enabled><Quantity>0</Quantity></TrustedKeyGroups>",M="<Aliases><Quantity>0</Quantity></Aliases>";if(_.length>0)M=`<Aliases>
71
+ <Quantity>${_.length}</Quantity>
72
+ <Items>
73
+ ${_.map((w)=>`<CNAME>${w}</CNAME>`).join(`
74
+ `)}
75
+ </Items>
76
+ </Aliases>`;let H=`<ViewerCertificate>
77
+ <CloudFrontDefaultCertificate>true</CloudFrontDefaultCertificate>
78
+ </ViewerCertificate>`;if(Z&&_.length>0)H=`<ViewerCertificate>
79
+ <ACMCertificateArn>${Z}</ACMCertificateArn>
80
+ <SSLSupportMethod>sni-only</SSLSupportMethod>
81
+ <MinimumProtocolVersion>TLSv1.2_2021</MinimumProtocolVersion>
82
+ <CertificateSource>acm</CertificateSource>
83
+ </ViewerCertificate>`;let K=`<?xml version="1.0" encoding="UTF-8"?>
84
+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
85
+ <CallerReference>${S}</CallerReference>
86
+ <Comment>${j}</Comment>
87
+ <DefaultRootObject>${$}</DefaultRootObject>
88
+ <Origins>
89
+ <Quantity>1</Quantity>
90
+ <Items>
91
+ <Origin>
92
+ <Id>${D}</Id>
93
+ <DomainName>${G}</DomainName>
94
+ <OriginPath></OriginPath>
95
+ <S3OriginConfig>
96
+ <OriginAccessIdentity></OriginAccessIdentity>
97
+ </S3OriginConfig>
98
+ <OriginAccessControlId>${Y}</OriginAccessControlId>
99
+ </Origin>
100
+ </Items>
101
+ </Origins>
102
+ <DefaultCacheBehavior>
103
+ <TargetOriginId>${D}</TargetOriginId>
104
+ <ViewerProtocolPolicy>redirect-to-https</ViewerProtocolPolicy>
105
+ <AllowedMethods>
106
+ <Quantity>2</Quantity>
107
+ <Items>
108
+ <Method>GET</Method>
109
+ <Method>HEAD</Method>
110
+ </Items>
111
+ <CachedMethods>
112
+ <Quantity>2</Quantity>
113
+ <Items>
114
+ <Method>GET</Method>
115
+ <Method>HEAD</Method>
116
+ </Items>
117
+ </CachedMethods>
118
+ </AllowedMethods>
119
+ <Compress>true</Compress>
120
+ <CachePolicyId>658327ea-f89d-4fab-a63d-7e88639e58f6</CachePolicyId>
121
+ ${U}
122
+ </DefaultCacheBehavior>
123
+ ${M}
124
+ ${H}
125
+ <PriceClass>${L}</PriceClass>
126
+ <Enabled>${q}</Enabled>
127
+ <HttpVersion>http2and3</HttpVersion>
128
+ <IsIPV6Enabled>true</IsIPV6Enabled>
129
+ ${F?"<CustomErrorResponses><Quantity>0</Quantity></CustomErrorResponses>":`<CustomErrorResponses>
130
+ <Quantity>1</Quantity>
131
+ <Items>
132
+ <CustomErrorResponse>
133
+ <ErrorCode>403</ErrorCode>
134
+ <ResponsePagePath>/index.html</ResponsePagePath>
135
+ <ResponseCode>200</ResponseCode>
136
+ <ErrorCachingMinTTL>300</ErrorCachingMinTTL>
137
+ </CustomErrorResponse>
138
+ </Items>
139
+ </CustomErrorResponses>`}
140
+ </DistributionConfig>`,V=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/distribution",body:K,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),P=V.body?.Distribution||V.Distribution||V.body||V;return{Id:P.Id,ARN:P.ARN,DomainName:P.DomainName,Status:P.Status,ETag:V.headers?.etag||V.ETag||""}}async createMediaDistributionForS3(J){return this.createDistributionForS3({...J,defaultRootObject:"",mediaDelivery:!0,comment:J.comment??`Media distribution for ${J.bucketName}`})}async listPublicKeys(){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/public-key"});return this.collectionItems(J.PublicKeyList??J,"PublicKeySummary").map((z)=>({Id:String(z.Id),Name:String(z.Name),Comment:z.Comment?String(z.Comment):void 0}))}async createPublicKey(J){if(!/^[A-Za-z0-9_-]{1,128}$/.test(J.name))throw TypeError("CloudFront public key name is invalid");if(!J.encodedKey.includes("BEGIN PUBLIC KEY"))throw TypeError("CloudFront public key must be PEM encoded");let Q=(_)=>_.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/public-key",headers:{"Content-Type":"application/xml"},body:`<PublicKeyConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><CallerReference>${Q(J.callerReference??`${Date.now()}-${J.name}`)}</CallerReference><Name>${Q(J.name)}</Name><EncodedKey>${Q(J.encodedKey)}</EncodedKey><Comment>${Q(J.comment??"")}</Comment></PublicKeyConfig>`}),Y=z.PublicKey??z;return{Id:String(Y.Id),Name:String(Y.PublicKeyConfig?.Name??J.name),EncodedKey:String(Y.PublicKeyConfig?.EncodedKey??J.encodedKey),Comment:String(Y.PublicKeyConfig?.Comment??J.comment??"")}}async listKeyGroups(){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/key-group"});return this.collectionItems(J.KeyGroupList??J,"KeyGroupSummary").map((z)=>({Id:String(z.KeyGroup?.Id??z.Id),Name:String(z.KeyGroup?.KeyGroupConfig?.Name??z.KeyGroupConfig?.Name??z.Name),Items:this.collectionItems(z.KeyGroup?.KeyGroupConfig?.Items??z.KeyGroupConfig?.Items??z.Items,"Item").map(String),Comment:z.KeyGroup?.KeyGroupConfig?.Comment??z.KeyGroupConfig?.Comment??z.Comment}))}async createKeyGroup(J){if(!/^[A-Za-z0-9_-]{1,128}$/.test(J.name))throw TypeError("CloudFront key group name is invalid");let Q=[...new Set(J.publicKeyIds)];if(Q.length===0)throw TypeError("CloudFront key group requires at least one public key");let z=($)=>$.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),Y=Q.map(($)=>`<Item>${z($)}</Item>`).join(""),_=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/key-group",headers:{"Content-Type":"application/xml"},body:`<KeyGroupConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><Name>${z(J.name)}</Name><Items>${Y}</Items><Comment>${z(J.comment??"")}</Comment></KeyGroupConfig>`}),Z=_.KeyGroup??_;return{Id:String(Z.Id),Name:String(Z.KeyGroupConfig?.Name??J.name),Items:Q,Comment:String(Z.KeyGroupConfig?.Comment??J.comment??"")}}static getS3BucketPolicyForCloudFront(J,Q){return{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${J}/*`,Condition:{StringEquals:{"AWS:SourceArn":Q}}}]}}async waitForDistributionDeployed(J,Q=60){for(let z=0;z<Q;z++){if((await this.getDistribution(J)).Status==="Deployed")return!0;await new Promise((_)=>setTimeout(_,30000))}return!1}async disableDistribution(J){let Q=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),z=Q.headers?.etag||Q.headers?.ETag||"",Y=Q.body?.DistributionConfig||(Q.body?.Enabled!==void 0?Q.body:void 0)||Q.DistributionConfig;if(!Y||Y.Enabled===void 0)throw Error("Failed to get current distribution config");Y.Enabled=!1;let _=this.buildDistributionConfigXml(Y),Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:_,headers:{"Content-Type":"application/xml","If-Match":z},returnHeaders:!0});return{ETag:Z.headers?.etag||Z.headers?.ETag||Z.ETag||""}}async deleteDistribution(J,Q){let z=Q||"";if(!z){let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}`,returnHeaders:!0});z=Y.headers?.etag||Y.headers?.ETag||""}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/distribution/${J}`,headers:{"If-Match":z}})}async waitForDistributionDisabled(J,Q=60){for(let z=0;z<Q;z++){let Y=await this.getDistribution(J);if(Y.Status==="Deployed"&&!Y.Enabled)return!0;await new Promise((_)=>setTimeout(_,30000))}return!1}async removeAlias(J,Q){let z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),Y=z.headers?.etag||z.headers?.ETag||"",_=z.body?.DistributionConfig||(z.body?.Enabled!==void 0?z.body:void 0)||z.DistributionConfig;if(!_||_.Enabled===void 0)throw Error("Failed to get current distribution config");let Z=[];if(_.Aliases?.Items){if(Array.isArray(_.Aliases.Items))Z=_.Aliases.Items;else if(typeof _.Aliases.Items==="object"){let q=_.Aliases.Items.CNAME;if(typeof q==="string")Z=[q];else if(Array.isArray(q))Z=q}}if(Z.length===0)throw Error("Distribution has no aliases to remove");let $=Z.filter((q)=>q!==Q);if($.length===Z.length)throw Error(`Alias ${Q} not found in distribution`);if(_.Aliases.Quantity=$.length,_.Aliases.Items=$.length>0?$:void 0,$.length===0)_.ViewerCertificate={CloudFrontDefaultCertificate:!0,MinimumProtocolVersion:"TLSv1.2_2021"};let j=this.buildDistributionConfigXml(_),L=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:j,headers:{"Content-Type":"application/xml","If-Match":Y},returnHeaders:!0});return{ETag:L.headers?.etag||L.headers?.ETag||L.ETag||""}}}
141
+ export{N as sf};
@@ -0,0 +1 @@
1
+ import{Id as a}from"./chunk-2wx29qga.js";import"./chunk-bggt4n6e.js";import"./chunk-0ccta6z6.js";import"./chunk-dskvqt67.js";import"./chunk-xt3s24vr.js";export{a as buildAndPushServerlessImage};