@stacksjs/ts-cloud 0.16.20 → 0.16.22

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 (196) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/aws/secrets-manager.d.ts +1 -0
  3. package/dist/aws/xml-result.d.ts +20 -0
  4. package/dist/{chunk-g6g33pt9.js → bin/chunk-09d5qe73.js} +7 -7
  5. package/dist/bin/chunk-0cefbrxg.js +1 -0
  6. package/dist/bin/{chunk-ys5n5c84.js → chunk-12q8xrct.js} +5 -5
  7. package/dist/bin/chunk-1srmd473.js +1 -0
  8. package/dist/bin/{chunk-mxvekmdx.js → chunk-24njmb7d.js} +114 -114
  9. package/dist/bin/chunk-27ka240w.js +1 -0
  10. package/dist/bin/{chunk-ngyqqy6d.js → chunk-2gd8kqzq.js} +5 -5
  11. package/dist/bin/{chunk-djjj62c0.js → chunk-330kytpm.js} +2 -2
  12. package/dist/bin/{chunk-h1rb8qvt.js → chunk-3425j97b.js} +2 -2
  13. package/dist/bin/chunk-3bq69jqk.js +1 -0
  14. package/dist/bin/chunk-4pysr1ky.js +1 -0
  15. package/dist/bin/chunk-56zfvf7e.js +1 -0
  16. package/dist/bin/chunk-59nav625.js +1 -0
  17. package/dist/bin/{chunk-6kx50dyc.js → chunk-5bsknbr7.js} +1 -1
  18. package/dist/bin/{chunk-t10e32an.js → chunk-636jsmnz.js} +6 -6
  19. package/dist/bin/chunk-7kj8f72p.js +2 -0
  20. package/dist/bin/{chunk-e55fdn0r.js → chunk-7xr71hnt.js} +3 -3
  21. package/dist/bin/chunk-87f5d9qj.js +2 -0
  22. package/dist/bin/chunk-8agf66wn.js +3 -0
  23. package/dist/bin/chunk-8fjzcr2w.js +1 -0
  24. package/dist/bin/{chunk-apnhhfkj.js → chunk-8wnkx3jf.js} +2 -2
  25. package/dist/bin/{chunk-z1dtdw3j.js → chunk-95v6ry1x.js} +5 -5
  26. package/dist/bin/chunk-9fq0bezb.js +1 -0
  27. package/dist/bin/chunk-9wpy7r9f.js +1 -0
  28. package/dist/bin/{chunk-5a7sxtwn.js → chunk-a0me5fed.js} +2 -2
  29. package/dist/bin/{chunk-148x1zq8.js → chunk-and7khsv.js} +2 -2
  30. package/dist/bin/{chunk-7zfydgfz.js → chunk-ardzx4dw.js} +130 -130
  31. package/dist/bin/{chunk-0trtkv9g.js → chunk-c04dygzg.js} +6 -6
  32. package/dist/bin/chunk-eetz9jgy.js +1 -0
  33. package/dist/bin/chunk-eg6156wp.js +1 -0
  34. package/dist/bin/chunk-ezpz96kp.js +1 -0
  35. package/dist/bin/chunk-f2qpsrrj.js +1 -0
  36. package/dist/bin/chunk-f3sbq7pw.js +2 -0
  37. package/dist/bin/chunk-gmabk4qn.js +1 -0
  38. package/dist/bin/{chunk-9vmtm7nq.js → chunk-hmnaen1z.js} +2 -2
  39. package/dist/bin/{chunk-x63yz8xg.js → chunk-jp23ed1q.js} +1 -1
  40. package/dist/bin/{chunk-0f1qpmd6.js → chunk-k6apknm8.js} +5 -5
  41. package/dist/bin/{chunk-2mv692y4.js → chunk-k97ms0bs.js} +5 -5
  42. package/dist/bin/chunk-kr51h4gk.js +1 -0
  43. package/dist/bin/{chunk-48x0wc2g.js → chunk-m51vpvr6.js} +3 -3
  44. package/dist/bin/{chunk-mx9ppkmn.js → chunk-mbqwrs7a.js} +4 -4
  45. package/dist/bin/{chunk-rbtt23vx.js → chunk-mz2jbtcs.js} +3 -3
  46. package/dist/bin/{chunk-dyh0vndw.js → chunk-n7hmjzgd.js} +4 -4
  47. package/dist/bin/{chunk-dmdg23a5.js → chunk-n8dsby4k.js} +2 -2
  48. package/dist/bin/chunk-nx8gpr90.js +34 -0
  49. package/dist/bin/chunk-q62ggp3g.js +1 -0
  50. package/dist/bin/chunk-q957s44c.js +1 -0
  51. package/dist/bin/{chunk-k7wh1wr5.js → chunk-qqqx70g6.js} +2 -2
  52. package/dist/bin/{chunk-gfr2215x.js → chunk-rm59bcnw.js} +60 -60
  53. package/dist/bin/chunk-rm6qnyce.js +2 -0
  54. package/dist/bin/chunk-rxehseyz.js +1 -0
  55. package/dist/bin/chunk-tfz7djw9.js +1 -0
  56. package/dist/bin/chunk-tr8901hb.js +1 -0
  57. package/dist/bin/{chunk-3n733cgx.js → chunk-v5bjbyve.js} +2 -2
  58. package/dist/bin/{chunk-90102shh.js → chunk-v980gs11.js} +2 -2
  59. package/dist/bin/chunk-vqb80dyg.js +1 -0
  60. package/dist/bin/{chunk-1j8b1d58.js → chunk-vskhr9qy.js} +2 -2
  61. package/dist/bin/{chunk-e24bscb0.js → chunk-wqydambz.js} +17 -17
  62. package/dist/bin/chunk-wysyyysg.js +1 -0
  63. package/dist/bin/chunk-xfs7rscr.js +1 -0
  64. package/dist/bin/cli.js +356 -356
  65. package/dist/bin/dashboard-server.js +1 -1
  66. package/dist/chunk-2ap78e1s.js +5 -0
  67. package/dist/{chunk-k53agv2m.js → chunk-2dextjqf.js} +2 -2
  68. package/dist/chunk-2fa9cdyf.js +1 -0
  69. package/dist/{chunk-z3wynefj.js → chunk-3jkc3s8c.js} +19 -19
  70. package/dist/chunk-3zzm5f28.js +92 -0
  71. package/dist/{chunk-e8e1h2h9.js → chunk-5dz6bzdj.js} +2 -2
  72. package/dist/chunk-6d5e10md.js +1 -0
  73. package/dist/chunk-9gypn8w9.js +1 -0
  74. package/dist/{chunk-hyeeqga9.js → chunk-9p89msvs.js} +6 -6
  75. package/dist/{chunk-31tvc877.js → chunk-9s24pbbc.js} +18 -18
  76. package/dist/chunk-badb5mf3.js +34 -0
  77. package/dist/{chunk-w9jhyy09.js → chunk-cfrv8110.js} +4 -4
  78. package/dist/{bin/chunk-8jbkphmg.js → chunk-dv1jkay7.js} +6 -6
  79. package/dist/{chunk-e52me1c6.js → chunk-ezgpamw6.js} +1 -1
  80. package/dist/chunk-j6a577hr.js +1 -0
  81. package/dist/chunk-jt49qs0f.js +2 -0
  82. package/dist/{chunk-aw1tp3p3.js → chunk-khatwx29.js} +99 -99
  83. package/dist/{chunk-v2p7c7s4.js → chunk-kpyhx96m.js} +133 -133
  84. package/dist/{chunk-0j2tpr8d.js → chunk-kw852q5m.js} +164 -164
  85. package/dist/{chunk-3m9ghthh.js → chunk-mgg0psgc.js} +2 -2
  86. package/dist/{chunk-9wmer0zx.js → chunk-ms4dnha2.js} +2 -2
  87. package/dist/{chunk-qcaqc5b8.js → chunk-np8vgbv0.js} +3 -3
  88. package/dist/chunk-p0b08g9f.js +114 -0
  89. package/dist/{chunk-srrscggm.js → chunk-pcns0kz4.js} +5 -5
  90. package/dist/{chunk-kczzc599.js → chunk-pffebjr8.js} +31 -31
  91. package/dist/{chunk-vs0qrm09.js → chunk-pwywwdq2.js} +1 -1
  92. package/dist/{chunk-5far81q7.js → chunk-w4s3rswa.js} +2 -2
  93. package/dist/chunk-whdbz3h8.js +1 -0
  94. package/dist/{chunk-bxrzsth8.js → chunk-x60w04y3.js} +2 -2
  95. package/dist/{chunk-zx8ecz8b.js → chunk-y6k0vwfn.js} +4 -4
  96. package/dist/deploy/index.js +1 -1
  97. package/dist/dns/index.js +1 -1
  98. package/dist/drivers/index.js +1 -1
  99. package/dist/index.js +85 -85
  100. package/dist/operations/index.js +1 -1
  101. package/dist/protection/index.js +1 -1
  102. package/dist/spend/index.js +1 -1
  103. package/dist/ui/404.html +1 -1
  104. package/dist/ui/accept-invitation.html +1 -1
  105. package/dist/ui/access-denied.html +1 -1
  106. package/dist/ui/account/automation.html +6 -6
  107. package/dist/ui/account/security.html +2 -2
  108. package/dist/ui/applications/compose.html +6 -6
  109. package/dist/ui/applications/new.html +2 -2
  110. package/dist/ui/data/backups.html +6 -6
  111. package/dist/ui/data/services.html +6 -6
  112. package/dist/ui/data/volumes.html +6 -6
  113. package/dist/ui/index.html +6 -6
  114. package/dist/ui/infrastructure/topology.html +6 -6
  115. package/dist/ui/integrations.html +2 -2
  116. package/dist/ui/operations/alerts.html +6 -6
  117. package/dist/ui/operations/configuration.html +6 -6
  118. package/dist/ui/operations/jobs.html +5 -5
  119. package/dist/ui/operations/maintenance.html +5 -5
  120. package/dist/ui/operations/observability.html +6 -6
  121. package/dist/ui/operations/previews.html +6 -6
  122. package/dist/ui/operations/queue.html +5 -5
  123. package/dist/ui/operations/regions.html +5 -5
  124. package/dist/ui/operations/releases.html +6 -6
  125. package/dist/ui/operations/spend.html +6 -6
  126. package/dist/ui/operations/workloads.html +6 -6
  127. package/dist/ui/security.html +2 -2
  128. package/dist/ui/server/actions.html +6 -6
  129. package/dist/ui/server/activity.html +1 -1
  130. package/dist/ui/server/capacity.html +5 -5
  131. package/dist/ui/server/database.html +5 -5
  132. package/dist/ui/server/deployments.html +5 -5
  133. package/dist/ui/server/diagnostics.html +1 -1
  134. package/dist/ui/server/firewall.html +5 -5
  135. package/dist/ui/server/fleet.html +5 -5
  136. package/dist/ui/server/logs.html +6 -6
  137. package/dist/ui/server/metrics.html +5 -5
  138. package/dist/ui/server/security.html +2 -2
  139. package/dist/ui/server/services.html +1 -1
  140. package/dist/ui/server/sites.html +6 -6
  141. package/dist/ui/server/ssh-keys.html +6 -6
  142. package/dist/ui/server/team.html +6 -6
  143. package/dist/ui/server/terminal.html +2 -2
  144. package/dist/ui/serverless/alarms.html +6 -6
  145. package/dist/ui/serverless/assets.html +2 -2
  146. package/dist/ui/serverless/cost.html +1 -1
  147. package/dist/ui/serverless/data.html +6 -6
  148. package/dist/ui/serverless/deployments.html +2 -2
  149. package/dist/ui/serverless/firewall.html +1 -1
  150. package/dist/ui/serverless/functions.html +5 -5
  151. package/dist/ui/serverless/logs.html +5 -5
  152. package/dist/ui/serverless/metrics.html +2 -2
  153. package/dist/ui/serverless/queues.html +6 -6
  154. package/dist/ui/serverless/secrets.html +6 -6
  155. package/dist/ui/serverless/traces.html +6 -6
  156. package/dist/ui/serverless.html +5 -5
  157. package/package.json +3 -3
  158. package/dist/bin/chunk-0h6cggyt.js +0 -1
  159. package/dist/bin/chunk-28ztnqjk.js +0 -1
  160. package/dist/bin/chunk-2g2zrtjs.js +0 -2
  161. package/dist/bin/chunk-4cs098d1.js +0 -1
  162. package/dist/bin/chunk-52fhq35h.js +0 -1
  163. package/dist/bin/chunk-6se7ygxa.js +0 -1
  164. package/dist/bin/chunk-72g1hr4z.js +0 -1
  165. package/dist/bin/chunk-840arz58.js +0 -34
  166. package/dist/bin/chunk-c7vxdwth.js +0 -1
  167. package/dist/bin/chunk-e0c3agf2.js +0 -1
  168. package/dist/bin/chunk-egn33pr9.js +0 -2
  169. package/dist/bin/chunk-gf7yavs5.js +0 -1
  170. package/dist/bin/chunk-gp5w7e4c.js +0 -1
  171. package/dist/bin/chunk-gt7g41js.js +0 -1
  172. package/dist/bin/chunk-hagakkgm.js +0 -1
  173. package/dist/bin/chunk-hr3vbg6y.js +0 -1
  174. package/dist/bin/chunk-hyb5v8wr.js +0 -1
  175. package/dist/bin/chunk-ndddd2ft.js +0 -3
  176. package/dist/bin/chunk-nqb1faqj.js +0 -1
  177. package/dist/bin/chunk-p831sptd.js +0 -1
  178. package/dist/bin/chunk-qxx1a51w.js +0 -1
  179. package/dist/bin/chunk-sh248v2y.js +0 -1
  180. package/dist/bin/chunk-swfmx4f8.js +0 -1
  181. package/dist/bin/chunk-vjkyj3xy.js +0 -2
  182. package/dist/bin/chunk-w8k1gyzr.js +0 -1
  183. package/dist/bin/chunk-wagzxm7z.js +0 -1
  184. package/dist/bin/chunk-xdxk6baf.js +0 -1
  185. package/dist/bin/chunk-y286zhty.js +0 -1
  186. package/dist/bin/chunk-ysv52qcc.js +0 -1
  187. package/dist/chunk-07rjctzz.js +0 -1
  188. package/dist/chunk-49vvjfrd.js +0 -1
  189. package/dist/chunk-6kcmbymp.js +0 -1
  190. package/dist/chunk-7xnwa0s8.js +0 -5
  191. package/dist/chunk-9asn5fpt.js +0 -92
  192. package/dist/chunk-d46p0h6t.js +0 -34
  193. package/dist/chunk-dak9hfrd.js +0 -1
  194. package/dist/chunk-ptq9v346.js +0 -2
  195. package/dist/chunk-wgf1ndgq.js +0 -114
  196. package/dist/chunk-z4xzd43p.js +0 -1
@@ -1,5 +0,0 @@
1
- import{mo,qr,$d,Pi,So,Co}from"./chunk-v2p7c7s4.js";import{_e}from"./chunk-5far81q7.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as S,mkdtempSync as U,rmSync as L,writeFileSync as d}from"node:fs";import{tmpdir as O}from"node:os";import{dirname as j,join as s}from"node:path";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function I(t,e){return`${r[e]}${t}${r.reset}`}function pn(t){console.log(`${r.green}✓${r.reset} ${t}`)}function hu(t){console.error(`${r.red}✗${r.reset} ${t}`)}function ns(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function P(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function v(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function is(t){console.log(`
2
- ${r.bright}${r.cyan}${t}${r.reset}
3
- `)}var F=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function fu(t,e="cyan"){let n=t.split(`
4
- `),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(I(`┌${a}┐`,e)),n.forEach((l)=>{console.log(I(`│ ${l.padEnd(i)} │`,e))}),console.log(I(`└${a}┘`,e))}function A(t,e){for(let n of e){let i=s(t,n.name);S(j(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function xa(t){let{app:e,projectRoot:n,region:i,repository:a}=t,l=e.architecture??"x86_64",R=l==="arm64"?"linux/arm64":"linux/amd64",E=e.kind==="php",c=t.onStep??(()=>{}),p=U(s(O(),"tscloud-img-"));try{let f=s(p,"app");S(f,{recursive:!0});let y,w;if(E){So({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c}),c("staging application tree");let o=Co(n);A(f,o),A(s(p,"runtime"),Pi().map((g)=>({name:g.path,data:g.contents,mode:g.mode})));let b=e.handlers?.http??"public/index.php";y={http:b,queue:e.handlers?.queue??b,cli:e.handlers?.cli??b},w=mo(o.map((g)=>`${g.name}:${g.data.length}`).join("|"))}else{c("bundling application");let o=await qr({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c});d(s(f,"index.mjs"),o.bundle),y=o.handlers,w=o.sha256}let k=w.slice(0,16);d(s(p,"Dockerfile"),$d({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:l}));let x=new _e(i),u;try{u=(await x.describeRepositories({repositoryNames:[a]})).repositories?.[0]?.repositoryUri??""}catch{u=""}if(!u)c(`creating ECR repository ${a}`),u=(await x.createRepository({repositoryName:a,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!u)throw Error(`could not resolve ECR repository URI for ${a}`);let m=`${u}:${k}`;c("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",m,p],{stdio:"inherit"}),c("ecr auth + push");let h=(await x.getAuthorizationToken()).authorizationData?.[0];if(!h?.authorizationToken||!h.proxyEndpoint)throw Error("failed to get an ECR authorization token");let T=h.proxyEndpoint.replace(/^https?:\/\//,""),B=s(p,".docker");return S(B,{recursive:!0}),d(s(B,"config.json"),JSON.stringify({auths:{[T]:{auth:h.authorizationToken}}})),C("docker",["push",m],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:B}}),P(`Image: ${m}`),{imageUri:m,tag:k,handlers:y}}finally{L(p,{recursive:!0,force:!0})}}
5
- export{pn,hu,ns,P,v,is,fu,xa};
@@ -1,92 +0,0 @@
1
- import{br,n}from"./chunk-zx8ecz8b.js";import{Fe}from"./chunk-bxrzsth8.js";import*as l from"node:crypto";import{readFileSync as B}from"node:fs";import{readdir as L}from"node:fs/promises";import{join as z}from"node:path";function Bt(e){if(e){let r=D(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return D(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function D(e){let{existsSync:t,readFileSync:s}=Fe("node:fs"),{homedir:r}=Fe("node:os"),{join:i}=Fe("node:path"),a=process.env.AWS_SHARED_CREDENTIALS_FILE||i(r(),".aws","credentials");if(!t(a))return null;let c=s(a,"utf-8"),g=null,d,u,y;for(let h of c.split(`
2
- `)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};g=p[1],d=void 0,u=void 0,y=void 0;continue}if(g===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":d=f;break;case"aws_secret_access_key":u=f;break;case"aws_session_token":y=f;break}}}if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:r}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+r);let i=new ArrayBuffer(r);return new Uint8Array(i).set(new Uint8Array(e)),i}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let r={...s};return delete r["@_xmlns"],r}class o{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let r=typeof e==="string"?s:e,i=typeof e==="string"?e:e.region??"us-east-1",a=typeof e==="string"?t:e.profile,c=r?.endpoint?br({region:i,path:"/",endpoint:r.endpoint}):void 0;this.region=i,this.explicitProfile=a,this.endpoint=c?.host,this.endpointProtocol=c?.protocol??"https",this.forcePathStyle=r?.forcePathStyle,this.explicitCredentials=r?.credentials,this.client=new n(r?.credentials,{profile:a,endpoint:r?.endpoint,forcePathStyle:r?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=Bt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],r=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(r){let i=Array.isArray(r)?r:[r];for(let a of i)t.push({Name:a.Name,CreationDate:a.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let r;if(this.region!=="us-east-1"&&!this.endpoint)r=`<?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>`,s["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,headers:s,body:r})}async deleteBucket(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`})}async emptyAndDeleteBucket(e){let t=!0;while(t){let s=await this.listAllObjects({bucket:e});if(s.length===0){t=!1;break}let r=s.map((i)=>i.Key);for(let i=0;i<r.length;i+=1000){let a=r.slice(i,i+1000);await this.deleteObjects(e,a)}}await this.deleteBucket(e)}async listAllObjects(e){let t=[],s;do{let r={"list-type":"2","max-keys":"1000"};if(e.prefix)r.prefix=e.prefix;if(s)r["continuation-token"]=s;let i=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`,queryParams:r}),a=i?.ListBucketResult??i,c=a?.Contents;if(c){let d=Array.isArray(c)?c:[c];for(let u of d)t.push({Key:u.Key,LastModified:u.LastModified||"",Size:Number.parseInt(u.Size||"0"),ETag:u.ETag})}let g=a?.IsTruncated;s=g==="true"||g===!0?a?.NextContinuationToken:void 0}while(s);return t}async list(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`}),s=[],i=(t?.ListBucketResult??t)?.Contents;if(i){let a=Array.isArray(i)?i:[i];for(let c of a){if(e.prefix&&!c.Key?.startsWith(e.prefix))continue;if(s.push({Key:c.Key||"",LastModified:c.LastModified||"",Size:Number.parseInt(c.Size||"0"),ETag:c.ETag}),e.maxKeys&&s.length>=e.maxKeys)break}}return s}async putObject(e){let t={};if(e.acl)t["x-amz-acl"]=e.acl;if(e.cacheControl)t["Cache-Control"]=e.cacheControl;if(e.contentType)t["Content-Type"]=e.contentType;if(e.metadata)for(let[i,a]of Object.entries(e.metadata))t[`x-amz-meta-${i}`]=a;let s=e.key.split("/").map((i)=>encodeURIComponent(i)).join("/"),r=e.body instanceof Uint8Array&&!Buffer.isBuffer(e.body)?Buffer.from(e.body):e.body;if(Buffer.isBuffer(r)||r instanceof Uint8Array){let i=Buffer.isBuffer(r)?r:Buffer.from(r),{accessKeyId:a,secretAccessKey:c,sessionToken:g}=this.getCredentials(),d=this.s3VirtualHost(e.bucket),u=this.objectPath(e.bucket,s),y=this.objectUrl(e.bucket,s),h=new Date,m=h.toISOString().replace(/[:-]|\.\d{3}/g,""),p=h.toISOString().slice(0,10).replace(/-/g,""),b=l.createHash("sha256").update(i).digest("hex"),S={host:d,"x-amz-date":m,"x-amz-content-sha256":b,...t};if(g)S["x-amz-security-token"]=g;let f=Object.keys(S).sort().map((P)=>`${P.toLowerCase()}:${S[P].trim()}
6
- `).join(""),k=Object.keys(S).sort().map((P)=>P.toLowerCase()).join(";"),T=["PUT",u,"",f,k,b].join(`
7
- `),w="AWS4-HMAC-SHA256",C=`${p}/${this.region}/s3/aws4_request`,q=[w,m,C,l.createHash("sha256").update(T).digest("hex")].join(`
8
- `),I=l.createHmac("sha256",`AWS4${c}`).update(p).digest(),K=l.createHmac("sha256",I).update(this.region).digest(),H=l.createHmac("sha256",K).update("s3").digest(),E=l.createHmac("sha256",H).update("aws4_request").digest(),v=l.createHmac("sha256",E).update(q).digest("hex"),A=`${w} Credential=${a}/${C}, SignedHeaders=${k}, Signature=${v}`,x=await fetch(y,{method:"PUT",headers:{...S,Authorization:A},body:U(i)});if(!x.ok){let P=await x.text();throw Error(`S3 PUT failed: ${x.status} ${P}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${s}`,bucket:e.bucket,headers:t,body:e.body})}async getObject(e,t){let s=t.split("/").map((i)=>encodeURIComponent(i)).join("/");return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${s}`,bucket:e,rawResponse:!0})}async getObjectBytes(e,t){let{accessKeyId:s,secretAccessKey:r,sessionToken:i}=this.getCredentials(),a=this.s3VirtualHost(e),c=t.split("/").map((P)=>encodeURIComponent(P)).join("/"),g=this.objectPath(e,c),d=this.objectUrl(e,c),u=new Date,y=u.toISOString().replace(/[:-]|\.\d{3}/g,""),h=u.toISOString().slice(0,10).replace(/-/g,""),m=l.createHash("sha256").update("").digest("hex"),p={host:a,"x-amz-date":y,"x-amz-content-sha256":m};if(i)p["x-amz-security-token"]=i;let b=Object.keys(p).sort().map((P)=>`${P.toLowerCase()}:${p[P].trim()}
9
- `).join(""),S=Object.keys(p).sort().map((P)=>P.toLowerCase()).join(";"),f=["GET",g,"",b,S,m].join(`
10
- `),k="AWS4-HMAC-SHA256",T=`${h}/${this.region}/s3/aws4_request`,w=[k,y,T,l.createHash("sha256").update(f).digest("hex")].join(`
11
- `),C=l.createHmac("sha256",`AWS4${r}`).update(h).digest(),q=l.createHmac("sha256",C).update(this.region).digest(),I=l.createHmac("sha256",q).update("s3").digest(),K=l.createHmac("sha256",I).update("aws4_request").digest(),H=l.createHmac("sha256",K).update(w).digest("hex"),E=`${k} Credential=${s}/${T}, SignedHeaders=${S}, Signature=${H}`,v=await fetch(d,{method:"GET",headers:{...p,Authorization:E}});if(!v.ok){let P=await v.text();throw Error(`S3 GET failed: ${v.status} ${P}`)}let A=await v.arrayBuffer(),x=v.headers.get("content-length");return{body:new Uint8Array(A),contentType:v.headers.get("content-type")??void 0,contentLength:x?Number.parseInt(x,10):void 0}}async copyObject(e){let t=(r)=>r.split("/").map((i)=>encodeURIComponent(i)).join("/"),s={"x-amz-copy-source":`/${e.sourceBucket}/${t(e.sourceKey)}`};if(e.metadataDirective)s["x-amz-metadata-directive"]=e.metadataDirective;if(e.contentType)s["Content-Type"]=e.contentType;if(e.metadata)for(let[r,i]of Object.entries(e.metadata))s[`x-amz-meta-${r}`]=i;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e.destinationBucket}/${t(e.destinationKey)}`,headers:s})}async deleteObject(e,t){let s=t.split("/").map((r)=>encodeURIComponent(r)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${s}`,bucket:e})}async deleteObjects(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
12
- <Delete>
13
- ${t.map((i)=>`<Object><Key>${i}</Key></Object>`).join(`
14
- `)}
15
- </Delete>`,r=l.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":r}})}async bucketExists(e){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}`}),!0}catch{return!1}}async copy(e){let t=B(e.source);await this.putObject({bucket:e.bucket,key:e.key,body:t,acl:e.acl,cacheControl:e.cacheControl,contentType:e.contentType,metadata:e.metadata})}async sync(e){let t=await this.listFilesRecursive(e.source);for(let s of t){if(e.exclude&&e.exclude.some((a)=>s.includes(a)))continue;if(e.include&&!e.include.some((a)=>s.includes(a)))continue;let r=s.substring(e.source.length+1),i=e.prefix?`${e.prefix}/${r}`:r;if(!e.dryRun){let a=B(s);await this.putObject({bucket:e.bucket,key:i,body:a,acl:e.acl,cacheControl:e.cacheControl,contentType:e.contentType,metadata:e.metadata})}}}async delete(e,t){await this.deleteObject(e,t)}async deletePrefix(e,t){let r=(await this.list({bucket:e,prefix:t})).map((i)=>i.Key);if(r.length>0)await this.deleteObjects(e,r)}async getBucketSize(e,t){return(await this.list({bucket:e,prefix:t})).reduce((r,i)=>r+i.Size,0)}async listFilesRecursive(e){let t=[],s=await L(e,{withFileTypes:!0});for(let r of s){let i=z(e,r.name);if(r.isDirectory()){let a=await this.listFilesRecursive(i);t.push(...a)}else t.push(i)}return t}async putBucketPolicy(e,t){let{accessKeyId:s,secretAccessKey:r,sessionToken:i}=this.getCredentials(),a=this.s3BaseHost(),c=typeof t==="string"?t:JSON.stringify(t),g=new Date,d=g.toISOString().replace(/[:-]|\.\d{3}/g,""),u=g.toISOString().slice(0,10).replace(/-/g,""),y=l.createHash("sha256").update(c).digest("hex"),h="/"+e,m="policy=",p={host:a,"x-amz-date":d,"x-amz-content-sha256":y,"content-type":"application/json"};if(i)p["x-amz-security-token"]=i;let b=Object.keys(p).sort().map((x)=>`${x.toLowerCase()}:${p[x].trim()}
16
- `).join(""),S=Object.keys(p).sort().map((x)=>x.toLowerCase()).join(";"),f=["PUT",h,"policy=",b,S,y].join(`
17
- `),k="AWS4-HMAC-SHA256",T=`${u}/${this.region}/s3/aws4_request`,w=[k,d,T,l.createHash("sha256").update(f).digest("hex")].join(`
18
- `),C=l.createHmac("sha256","AWS4"+r).update(u).digest(),q=l.createHmac("sha256",C).update(this.region).digest(),I=l.createHmac("sha256",q).update("s3").digest(),K=l.createHmac("sha256",I).update("aws4_request").digest(),H=l.createHmac("sha256",K).update(w).digest("hex"),E=`${k} Credential=${s}/${T}, SignedHeaders=${S}, Signature=${H}`,v=`${this.endpointProtocol}://${a}${h}?policy=`,A=await fetch(v,{method:"PUT",headers:{...p,Authorization:E},body:c});if(!A.ok){let x=await A.text();throw Error(`Failed to put bucket policy: ${A.status} ${x}`)}}async getBucketPolicy(e){let{accessKeyId:t,secretAccessKey:s,sessionToken:r}=this.getCredentials(),i=this.s3BaseHost(),a=new Date,c=a.toISOString().replace(/[:-]|\.\d{3}/g,""),g=a.toISOString().slice(0,10).replace(/-/g,""),d=l.createHash("sha256").update("").digest("hex"),u="/"+e,y="policy=",h={host:i,"x-amz-date":c,"x-amz-content-sha256":d};if(r)h["x-amz-security-token"]=r;let m=Object.keys(h).sort().map((A)=>`${A.toLowerCase()}:${h[A].trim()}
19
- `).join(""),p=Object.keys(h).sort().map((A)=>A.toLowerCase()).join(";"),b=["GET",u,"policy=",m,p,d].join(`
20
- `),S="AWS4-HMAC-SHA256",f=`${g}/${this.region}/s3/aws4_request`,k=[S,c,f,l.createHash("sha256").update(b).digest("hex")].join(`
21
- `),T=l.createHmac("sha256","AWS4"+s).update(g).digest(),w=l.createHmac("sha256",T).update(this.region).digest(),C=l.createHmac("sha256",w).update("s3").digest(),q=l.createHmac("sha256",C).update("aws4_request").digest(),I=l.createHmac("sha256",q).update(k).digest("hex"),K=`${S} Credential=${t}/${f}, SignedHeaders=${p}, Signature=${I}`,H=`${this.endpointProtocol}://${i}${u}?policy=`,E=await fetch(H,{method:"GET",headers:{...h,Authorization:K}});if(E.status===404)return null;if(!E.ok){let A=await E.text();throw Error(`Failed to get bucket policy: ${E.status} ${A}`)}let v=await E.text();return JSON.parse(v)}async deleteBucketPolicy(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{policy:""}})}async headBucket(e){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch(t){if(t.statusCode===404)return{exists:!1};throw t}}async headObject(e,t){try{let s=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}/${t}`,returnHeaders:!0});return{ContentLength:s?.headers?.["content-length"]?parseInt(s.headers["content-length"]):void 0,ContentType:s?.headers?.["content-type"],ETag:s?.headers?.etag,LastModified:s?.headers?.["last-modified"]}}catch(s){if(s.statusCode===404)return null;throw s}}async getObjectBuffer(e,t){let s=await this.getObject(e,t);return Buffer.from(s)}async getObjectJson(e,t){let s=await this.getObject(e,t);return JSON.parse(s)}async putObjectJson(e,t,s,r){await this.putObject({bucket:e,key:t,body:JSON.stringify(s),contentType:"application/json",...r})}async getBucketVersioning(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{versioning:""}});return{Status:(t?.VersioningConfiguration??t)?.Status}}async putBucketVersioning(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
22
- <VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
23
- <Status>${t}</Status>
24
- </VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:s})}async getBucketLifecycleConfiguration(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{lifecycle:""}});return j(t,"LifecycleConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketLifecycleConfiguration(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
25
- <LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
26
- ${t.map((i)=>{let a=`<Rule><ID>${i.ID}</ID><Status>${i.Status}</Status>`;if(i.Filter)a+=`<Filter><Prefix>${i.Filter.Prefix||""}</Prefix></Filter>`;else a+="<Filter><Prefix></Prefix></Filter>";if(i.Expiration){if(i.Expiration.Days)a+=`<Expiration><Days>${i.Expiration.Days}</Days></Expiration>`;else if(i.Expiration.Date)a+=`<Expiration><Date>${i.Expiration.Date}</Date></Expiration>`}if(i.Transitions)for(let c of i.Transitions)a+=`<Transition><Days>${c.Days}</Days><StorageClass>${c.StorageClass}</StorageClass></Transition>`;if(i.NoncurrentVersionExpiration)a+=`<NoncurrentVersionExpiration><NoncurrentDays>${i.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return a+="</Rule>",a}).join("")}
27
- </LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketLifecycleConfiguration(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{lifecycle:""}})}async getBucketCors(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{cors:""}});return j(t,"CORSConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketCors(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
28
- <CORSConfiguration>
29
- ${t.map((i)=>{let a="<CORSRule>";for(let c of i.AllowedOrigins)a+=`<AllowedOrigin>${c}</AllowedOrigin>`;for(let c of i.AllowedMethods)a+=`<AllowedMethod>${c}</AllowedMethod>`;if(i.AllowedHeaders)for(let c of i.AllowedHeaders)a+=`<AllowedHeader>${c}</AllowedHeader>`;if(i.ExposeHeaders)for(let c of i.ExposeHeaders)a+=`<ExposeHeader>${c}</ExposeHeader>`;if(i.MaxAgeSeconds)a+=`<MaxAgeSeconds>${i.MaxAgeSeconds}</MaxAgeSeconds>`;return a+="</CORSRule>",a}).join("")}
30
- </CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketCors(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{cors:""}})}async getBucketEncryption(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{encryption:""}});return j(t,"ServerSideEncryptionConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketEncryption(e,t,s){let r=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${t}</SSEAlgorithm>`;if(s)r+=`<KMSMasterKeyID>${s}</KMSMasterKeyID>`;r+="</ApplyServerSideEncryptionByDefault>";let i=`<?xml version="1.0" encoding="UTF-8"?>
31
- <ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
32
- <Rule>${r}</Rule>
33
- </ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:i})}async deleteBucketEncryption(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{encryption:""}})}async getBucketTagging(e){try{let s=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!s)return[];return Array.isArray(s)?s:[s]}catch(t){if(t.statusCode===404)return[];throw t}}async putBucketTagging(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
34
- <Tagging>
35
- <TagSet>${t.map((i)=>`<Tag><Key>${i.Key}</Key><Value>${i.Value}</Value></Tag>`).join("")}</TagSet>
36
- </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketTagging(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{tagging:""}})}async getObjectTagging(e,t){try{let r=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}/${t}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!r)return[];return Array.isArray(r)?r:[r]}catch(s){if(s.statusCode===404)return[];throw s}}async putObjectTagging(e,t,s){let i=`<?xml version="1.0" encoding="UTF-8"?>
37
- <Tagging>
38
- <TagSet>${s.map((a)=>`<Tag><Key>${a.Key}</Key><Value>${a.Value}</Value></Tag>`).join("")}</TagSet>
39
- </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}/${t}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:i})}async deleteObjectTagging(e,t){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}/${t}`,queryParams:{tagging:""}})}async getBucketAcl(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{acl:""}});return j(t,"AccessControlPolicy")}async putBucketAcl(e,t){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{acl:""},headers:{"x-amz-acl":t}})}async getObjectAcl(e,t){let s=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}/${t}`,queryParams:{acl:""}});return j(s,"AccessControlPolicy")}async putObjectAcl(e,t,s){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}/${t}`,queryParams:{acl:""},headers:{"x-amz-acl":s}})}async getBucketLocation(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{location:""}}),s=j(t,"LocationConstraint");return(typeof s==="string"?s:s?.["#text"])||"us-east-1"}async getBucketLogging(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{logging:""}});return j(t,"BucketLoggingStatus")}async putBucketLogging(e,t,s){let r=`<?xml version="1.0" encoding="UTF-8"?>
40
- <BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
41
- <LoggingEnabled>
42
- <TargetBucket>${t}</TargetBucket>
43
- <TargetPrefix>${s}</TargetPrefix>
44
- </LoggingEnabled>
45
- </BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:r})}async getBucketNotificationConfiguration(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{notification:""}});return j(t,"NotificationConfiguration")}async putBucketNotificationConfiguration(e,t){let s="";if(t.LambdaFunctionConfigurations)for(let i of t.LambdaFunctionConfigurations){if(s+="<CloudFunctionConfiguration>",i.Id)s+=`<Id>${i.Id}</Id>`;s+=`<CloudFunction>${i.LambdaFunctionArn}</CloudFunction>`;for(let a of i.Events)s+=`<Event>${a}</Event>`;if(i.Filter?.Key?.FilterRules){s+="<Filter><S3Key>";for(let a of i.Filter.Key.FilterRules)s+=`<FilterRule><Name>${a.Name}</Name><Value>${a.Value}</Value></FilterRule>`;s+="</S3Key></Filter>"}s+="</CloudFunctionConfiguration>"}if(t.TopicConfigurations)for(let i of t.TopicConfigurations){if(s+="<TopicConfiguration>",i.Id)s+=`<Id>${i.Id}</Id>`;s+=`<Topic>${i.TopicArn}</Topic>`;for(let a of i.Events)s+=`<Event>${a}</Event>`;s+="</TopicConfiguration>"}if(t.QueueConfigurations)for(let i of t.QueueConfigurations){if(s+="<QueueConfiguration>",i.Id)s+=`<Id>${i.Id}</Id>`;s+=`<Queue>${i.QueueArn}</Queue>`;for(let a of i.Events)s+=`<Event>${a}</Event>`;s+="</QueueConfiguration>"}let r=`<?xml version="1.0" encoding="UTF-8"?>
46
- <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
47
- ${s}
48
- </NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:r})}async getBucketWebsite(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{website:""}});return j(t,"WebsiteConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketWebsite(e,t){let s="";if(t.RedirectAllRequestsTo)s=`<RedirectAllRequestsTo>
49
- <HostName>${t.RedirectAllRequestsTo.HostName}</HostName>
50
- ${t.RedirectAllRequestsTo.Protocol?`<Protocol>${t.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
51
- </RedirectAllRequestsTo>`;else if(s=`<IndexDocument><Suffix>${t.IndexDocument}</Suffix></IndexDocument>`,t.ErrorDocument)s+=`<ErrorDocument><Key>${t.ErrorDocument}</Key></ErrorDocument>`;let r=`<?xml version="1.0" encoding="UTF-8"?>
52
- <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
53
- ${s}
54
- </WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketWebsite(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{website:""}})}async getBucketReplication(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{replication:""}});return j(t,"ReplicationConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async deleteBucketReplication(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{replication:""}})}async getPublicAccessBlock(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{publicAccessBlock:""}});return j(t,"PublicAccessBlockConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putPublicAccessBlock(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
55
- <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
56
- <BlockPublicAcls>${t.BlockPublicAcls??!0}</BlockPublicAcls>
57
- <IgnorePublicAcls>${t.IgnorePublicAcls??!0}</IgnorePublicAcls>
58
- <BlockPublicPolicy>${t.BlockPublicPolicy??!0}</BlockPublicPolicy>
59
- <RestrictPublicBuckets>${t.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
60
- </PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:s})}async deletePublicAccessBlock(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl(e,t,s=3600){let{accessKeyId:r,secretAccessKey:i}=this.getCredentials(),a=this.s3VirtualHost(e),c=new Date,g=c.toISOString().replace(/[:-]|\.\d{3}/g,""),d=c.toISOString().slice(0,10).replace(/-/g,""),u=`${d}/${this.region}/s3/aws4_request`,y=`${r}/${u}`,h=t.split("/").map((C)=>encodeURIComponent(C)).join("/"),m=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":y,"X-Amz-Date":g,"X-Amz-Expires":s.toString(),"X-Amz-SignedHeaders":"host"}),p=["GET",this.objectPath(e,h),m.toString(),`host:${a}
61
- `,"host","UNSIGNED-PAYLOAD"].join(`
62
- `),b=["AWS4-HMAC-SHA256",g,u,l.createHash("sha256").update(p).digest("hex")].join(`
63
- `),S=l.createHmac("sha256",`AWS4${i}`).update(d).digest(),f=l.createHmac("sha256",S).update(this.region).digest(),k=l.createHmac("sha256",f).update("s3").digest(),T=l.createHmac("sha256",k).update("aws4_request").digest(),w=l.createHmac("sha256",T).update(b).digest("hex");return m.append("X-Amz-Signature",w),`${this.endpointProtocol}://${a}${this.objectPath(e,h)}?${m.toString()}`}generatePresignedPutUrl(e,t,s,r=3600){let{accessKeyId:i,secretAccessKey:a}=this.getCredentials(),c=this.s3VirtualHost(e),g=new Date,d=g.toISOString().replace(/[:-]|\.\d{3}/g,""),u=g.toISOString().slice(0,10).replace(/-/g,""),y=`${u}/${this.region}/s3/aws4_request`,h=`${i}/${y}`,m=t.split("/").map((q)=>encodeURIComponent(q)).join("/"),p=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":h,"X-Amz-Date":d,"X-Amz-Expires":r.toString(),"X-Amz-SignedHeaders":"content-type;host"}),b=["PUT",this.objectPath(e,m),p.toString(),`content-type:${s}
64
- host:${c}
65
- `,"content-type;host","UNSIGNED-PAYLOAD"].join(`
66
- `),S=["AWS4-HMAC-SHA256",d,y,l.createHash("sha256").update(b).digest("hex")].join(`
67
- `),f=l.createHmac("sha256",`AWS4${a}`).update(u).digest(),k=l.createHmac("sha256",f).update(this.region).digest(),T=l.createHmac("sha256",k).update("s3").digest(),w=l.createHmac("sha256",T).update("aws4_request").digest(),C=l.createHmac("sha256",w).update(S).digest("hex");return p.append("X-Amz-Signature",C),`${this.endpointProtocol}://${c}${this.objectPath(e,m)}?${p.toString()}`}async createMultipartUpload(e,t,s){let r={};if(s?.contentType)r["Content-Type"]=s.contentType;if(s?.metadata)for(let[g,d]of Object.entries(s.metadata))r[`x-amz-meta-${g}`]=d;let i=t.split("/").map((g)=>encodeURIComponent(g)).join("/"),a=await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${i}`,bucket:e,queryParams:{uploads:""},headers:r});return{UploadId:(a?.InitiateMultipartUploadResult??a)?.UploadId}}async uploadPart(e,t,s,r,i){let{accessKeyId:a,secretAccessKey:c,sessionToken:g}=this.getCredentials(),d=this.s3VirtualHost(e),u=t.split("/").map((O)=>encodeURIComponent(O)).join("/"),y=this.objectPath(e,u),h=`${this.objectUrl(e,u)}?partNumber=${r}&uploadId=${encodeURIComponent(s)}`,m=new Date,p=m.toISOString().replace(/[:-]|\.\d{3}/g,""),b=m.toISOString().slice(0,10).replace(/-/g,""),S=l.createHash("sha256").update(i).digest("hex"),f={host:d,"x-amz-date":p,"x-amz-content-sha256":S};if(g)f["x-amz-security-token"]=g;let k=Object.keys(f).sort().map((O)=>`${O.toLowerCase()}:${f[O].trim()}
68
- `).join(""),T=Object.keys(f).sort().map((O)=>O.toLowerCase()).join(";"),w=["PUT",y,`partNumber=${r}&uploadId=${encodeURIComponent(s)}`,k,T,S].join(`
69
- `),C="AWS4-HMAC-SHA256",q=`${b}/${this.region}/s3/aws4_request`,I=[C,p,q,l.createHash("sha256").update(w).digest("hex")].join(`
70
- `),K=l.createHmac("sha256",`AWS4${c}`).update(b).digest(),H=l.createHmac("sha256",K).update(this.region).digest(),E=l.createHmac("sha256",H).update("s3").digest(),v=l.createHmac("sha256",E).update("aws4_request").digest(),A=l.createHmac("sha256",v).update(I).digest("hex"),x=`${C} Credential=${a}/${q}, SignedHeaders=${T}, Signature=${A}`,P=await fetch(h,{method:"PUT",headers:{...f,Authorization:x},body:U(i)});if(!P.ok){let O=await P.text();throw Error(`Upload part failed: ${P.status} ${O}`)}return{ETag:P.headers.get("etag")||""}}async completeMultipartUpload(e,t,s,r){let i=t.split("/").map((g)=>encodeURIComponent(g)).join("/"),c=`<?xml version="1.0" encoding="UTF-8"?>
71
- <CompleteMultipartUpload>${r.sort((g,d)=>g.PartNumber-d.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:`/${i}`,bucket:e,queryParams:{uploadId:s},headers:{"Content-Type":"application/xml"},body:c})}async abortMultipartUpload(e,t,s){let r=t.split("/").map((i)=>encodeURIComponent(i)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${r}`,bucket:e,queryParams:{uploadId:s}})}async listMultipartUploads(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/",bucket:e,queryParams:{uploads:""}}),s=(t?.ListMultipartUploadsResult??t)?.Upload;if(!s)return[];return(Array.isArray(s)?s:[s]).map((i)=>({Key:i.Key,UploadId:i.UploadId,Initiated:i.Initiated}))}async restoreObject(e,t,s,r="Standard"){let i=`<?xml version="1.0" encoding="UTF-8"?>
72
- <RestoreRequest>
73
- <Days>${s}</Days>
74
- <GlacierJobParameters>
75
- <Tier>${r}</Tier>
76
- </GlacierJobParameters>
77
- </RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}/${t}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:i})}async selectObjectContent(e,t,s,r,i="JSON"){let a="";if(r==="CSV")a="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(r==="JSON")a="<JSON><Type>DOCUMENT</Type></JSON>";else a="<Parquet/>";let c="";if(i==="CSV")c="<CSV/>";else c="<JSON/>";let g=`<?xml version="1.0" encoding="UTF-8"?>
78
- <SelectObjectContentRequest>
79
- <Expression>${s}</Expression>
80
- <ExpressionType>SQL</ExpressionType>
81
- <InputSerialization>${a}</InputSerialization>
82
- <OutputSerialization>${c}</OutputSerialization>
83
- </SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}/${t}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:g,rawResponse:!0})}async getSignedUrl(e){let{bucket:t,key:s,expiresIn:r=3600,operation:i="getObject"}=e,{accessKeyId:a,secretAccessKey:c,sessionToken:g}=this.getCredentials(),d=new Date,u=d.toISOString().replace(/[:-]|\.\d{3}/g,""),y=d.toISOString().slice(0,10).replace(/-/g,""),h=this.s3VirtualHost(t),m=i==="putObject"?"PUT":"GET",p="AWS4-HMAC-SHA256",b=`${y}/${this.region}/s3/aws4_request`,f={"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":`${a}/${b}`,"X-Amz-Date":u,"X-Amz-Expires":r.toString(),"X-Amz-SignedHeaders":"host"};if(g)f["X-Amz-Security-Token"]=g;let T=Object.keys(f).sort().map((R)=>`${encodeURIComponent(R)}=${encodeURIComponent(f[R])}`).join("&"),w=s.split("/").map((R)=>encodeURIComponent(R)).join("/"),C=this.objectPath(t,w),q=`host:${h}
84
- `,H=[m,C,T,q,"host","UNSIGNED-PAYLOAD"].join(`
85
- `),E=["AWS4-HMAC-SHA256",u,b,l.createHash("sha256").update(H).digest("hex")].join(`
86
- `),v=l.createHmac("sha256",`AWS4${c}`).update(y).digest(),A=l.createHmac("sha256",v).update(this.region).digest(),x=l.createHmac("sha256",A).update("s3").digest(),P=l.createHmac("sha256",x).update("aws4_request").digest(),O=l.createHmac("sha256",P).update(E).digest("hex");return`${this.endpointProtocol}://${h}${C}?${T}&X-Amz-Signature=${O}`}async listObjects(e){let{bucket:t,prefix:s,maxKeys:r=1000,continuationToken:i}=e,a={"list-type":"2","max-keys":r.toString()};if(s)a.prefix=s;if(i)a["continuation-token"]=i;let c=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${t}`,queryParams:a}),g=[],d=c?.ListBucketResult??c;if(d?.Contents){let u=Array.isArray(d.Contents)?d.Contents:[d.Contents];for(let y of u)g.push({Key:y.Key||"",LastModified:y.LastModified||"",Size:Number.parseInt(y.Size||"0"),ETag:y.ETag})}return{objects:g,nextContinuationToken:d?.NextContinuationToken}}async emptyBucket(e){let t=0,s=await this.listAllObjects({bucket:e});if(s.length>0)for(let r=0;r<s.length;r+=1000){let a=s.slice(r,r+1000).map((c)=>c.Key);await this.deleteObjects(e,a),t+=a.length}try{let r,i;do{let a=await this.listObjectVersions({bucket:e,keyMarker:r,versionIdMarker:i,maxKeys:1000}),c=[];if(a.versions)for(let g of a.versions)c.push({Key:g.Key,VersionId:g.VersionId});if(a.deleteMarkers)for(let g of a.deleteMarkers)c.push({Key:g.Key,VersionId:g.VersionId});if(c.length>0)await this.deleteObjectVersions(e,c),t+=c.length;r=a.nextKeyMarker,i=a.nextVersionIdMarker}while(r)}catch{}return{deletedCount:t}}async listObjectVersions(e){let{bucket:t,prefix:s,keyMarker:r,versionIdMarker:i,maxKeys:a=1000}=e,c={versions:"","max-keys":a.toString()};if(s)c.prefix=s;if(r)c["key-marker"]=r;if(i)c["version-id-marker"]=i;let g=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${t}`,queryParams:c}),d=[],u=[];if(g.Version){let y=Array.isArray(g.Version)?g.Version:[g.Version];for(let h of y)d.push({Key:h.Key,VersionId:h.VersionId,IsLatest:h.IsLatest==="true"})}if(g.DeleteMarker){let y=Array.isArray(g.DeleteMarker)?g.DeleteMarker:[g.DeleteMarker];for(let h of y)u.push({Key:h.Key,VersionId:h.VersionId,IsLatest:h.IsLatest==="true"})}return{versions:d,deleteMarkers:u,nextKeyMarker:g.NextKeyMarker,nextVersionIdMarker:g.NextVersionIdMarker}}async deleteObjectVersions(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
87
- <Delete>
88
- <Quiet>true</Quiet>
89
- ${t.map((i)=>`<Object><Key>${i.Key}</Key>${i.VersionId?`<VersionId>${i.VersionId}</VersionId>`:""}</Object>`).join(`
90
- `)}
91
- </Delete>`,r=l.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":r}})}}
92
- export{Bt,o};
@@ -1,34 +0,0 @@
1
- import{n}from"./chunk-zx8ecz8b.js";import{o}from"./chunk-9asn5fpt.js";import{y}from"./chunk-9wmer0zx.js";import{Fe}from"./chunk-bxrzsth8.js";function f(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${a}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${a}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${a}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function l(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class fe{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=f(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=l(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),c=r(a,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}function p(e,t){return(e?.[`${t}Response`]??e)?.[`${t}Result`]}class tt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=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"}),t=p(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=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"}),t=p(e,"GetSendQuota"),s=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:s(t?.Max24HourSend),MaxSendRate:s(t?.MaxSendRate),SentLast24Hours:s(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class Sn{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new tt(this.region),this.s3=new o(this.region),this.iam=new fe(this.region),this.route53=new y(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-6kcmbymp.js"),a=new s,i=(g,A)=>{let h={Action:g,Version:"2010-05-08",...A};return Object.entries(h).map(([R,S])=>`${encodeURIComponent(R)}=${encodeURIComponent(S)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let P=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:P,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Fe("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
- `,i+=`To: ${s.join(", ")}\r
3
- `,e.cc){let c=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${c.join(", ")}\r
4
- `}if(i+=`Subject: ${e.subject}\r
5
- `,i+=`MIME-Version: 1.0\r
6
- `,i+=`Content-Type: multipart/mixed; boundary="${a}"\r
7
- `,i+=`\r
8
- `,e.text||e.html)if(i+=`--${a}\r
9
- `,e.html&&e.text){let c=`----=_Alt_${Date.now()}`;i+=`Content-Type: multipart/alternative; boundary="${c}"\r
10
- `,i+=`\r
11
- `,i+=`--${c}\r
12
- `,i+=`Content-Type: text/plain; charset="UTF-8"\r
13
- `,i+=`\r
14
- `,i+=`${e.text}\r
15
- `,i+=`--${c}\r
16
- `,i+=`Content-Type: text/html; charset="UTF-8"\r
17
- `,i+=`\r
18
- `,i+=`${e.html}\r
19
- `,i+=`--${c}--\r
20
- `}else if(e.html)i+=`Content-Type: text/html; charset="UTF-8"\r
21
- `,i+=`\r
22
- `,i+=`${e.html}\r
23
- `;else i+=`Content-Type: text/plain; charset="UTF-8"\r
24
- `,i+=`\r
25
- `,i+=`${e.text}\r
26
- `;if(e.attachments)for(let c of e.attachments)i+=`--${a}\r
27
- `,i+=`Content-Type: ${c.contentType||"application/octet-stream"}; name="${c.filename}"\r
28
- `,i+=`Content-Transfer-Encoding: base64\r
29
- `,i+=`Content-Disposition: attachment; filename="${c.filename}"\r
30
- `,i+=`\r
31
- `,i+=`${c.content}\r
32
- `;return i+=`--${a}--\r
33
- `,i}}var Dh=new Sn;
34
- export{fe,tt,Sn,Dh};
@@ -1 +0,0 @@
1
- import{j}from"./chunk-k53agv2m.js";import"./chunk-zx8ecz8b.js";export{j as RDSClient};
@@ -1,2 +0,0 @@
1
- import{n}from"./chunk-zx8ecz8b.js";class h{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
- export{h};