@stacksjs/ts-cloud 0.9.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/dist/aws/index.js +1 -269
  2. package/dist/bin/chunk-08c0pzkb.js +1 -0
  3. package/dist/bin/chunk-12210qvj.js +1 -0
  4. package/dist/bin/chunk-1v6bt68w.js +6 -0
  5. package/dist/bin/chunk-35ttwn26.js +70 -0
  6. package/dist/bin/chunk-3r3be05z.js +1 -0
  7. package/dist/bin/chunk-41yqpdv7.js +2 -0
  8. package/dist/bin/chunk-5rv31chh.js +1 -0
  9. package/dist/bin/chunk-6eat8ezk.js +2 -0
  10. package/dist/bin/chunk-6gktf2m2.js +1 -0
  11. package/dist/bin/chunk-6zjy949y.js +141 -0
  12. package/dist/bin/chunk-7wzdaqh6.js +2 -0
  13. package/dist/bin/chunk-80ar3aty.js +1 -0
  14. package/dist/bin/chunk-8rwhsp5b.js +2 -0
  15. package/dist/bin/chunk-936vp7dx.js +44 -0
  16. package/dist/bin/chunk-9px3rg4a.js +4 -0
  17. package/dist/bin/chunk-anm3ae6z.js +7364 -0
  18. package/dist/bin/{chunk-ynjvbphf.js → chunk-axvr7dwa.js} +6 -6
  19. package/dist/bin/chunk-b0hj9m5e.js +2 -0
  20. package/dist/bin/{chunk-mh0kdzqp.js → chunk-b2ymh8k0.js} +1 -1
  21. package/dist/bin/chunk-b35989e3.js +50 -0
  22. package/dist/bin/chunk-c2b6nk0q.js +37 -0
  23. package/dist/bin/chunk-ckxpgwxw.js +3 -0
  24. package/dist/bin/chunk-d6zzgvtn.js +92 -0
  25. package/dist/bin/chunk-da8zpf82.js +1 -0
  26. package/dist/bin/chunk-ddmjjstg.js +1 -0
  27. package/dist/bin/chunk-dhhz4zyj.js +1 -0
  28. package/dist/bin/chunk-dj9a67c3.js +9 -0
  29. package/dist/bin/chunk-ds1z880f.js +1 -0
  30. package/dist/bin/chunk-dvkj4k6h.js +111 -0
  31. package/dist/bin/chunk-eh40fpvj.js +1 -0
  32. package/dist/bin/chunk-ey9fagrr.js +6 -0
  33. package/dist/bin/chunk-ezftw2q4.js +1 -0
  34. package/dist/bin/chunk-g6a4n3rh.js +1 -0
  35. package/dist/bin/chunk-g90nqfgv.js +585 -0
  36. package/dist/bin/chunk-gs40j75w.js +1 -0
  37. package/dist/bin/chunk-jjjts1vt.js +1 -0
  38. package/dist/bin/{chunk-ry030a6b.js → chunk-jnsbzqzz.js} +30 -30
  39. package/dist/bin/chunk-jnx4jgw8.js +1 -0
  40. package/dist/bin/chunk-jt1tndm2.js +3 -0
  41. package/dist/bin/chunk-kybdb0ws.js +2 -0
  42. package/dist/bin/chunk-m3nqw76h.js +3 -0
  43. package/dist/bin/chunk-mn6j22zn.js +6 -0
  44. package/dist/bin/chunk-nb0yjkv5.js +2 -0
  45. package/dist/bin/chunk-pjpa4x52.js +2 -0
  46. package/dist/bin/chunk-pkgkfe6s.js +2 -0
  47. package/dist/bin/chunk-pnz5hk8n.js +60 -0
  48. package/dist/bin/chunk-q46zr2tv.js +1 -0
  49. package/dist/bin/chunk-qtdngvs8.js +1 -0
  50. package/dist/bin/chunk-sbejksrh.js +2 -0
  51. package/dist/bin/chunk-svyd4v6c.js +34 -0
  52. package/dist/bin/chunk-tna7ay8d.js +1 -0
  53. package/dist/bin/chunk-tp4c2mv1.js +1 -0
  54. package/dist/bin/chunk-w5d6tr2x.js +1 -0
  55. package/dist/bin/chunk-wewcjam5.js +1 -0
  56. package/dist/bin/chunk-xv4bscrm.js +1 -0
  57. package/dist/bin/chunk-y9eyc5pw.js +1 -0
  58. package/dist/bin/chunk-y9f8649w.js +512 -0
  59. package/dist/bin/cli.js +428 -418
  60. package/dist/bin/dashboard-server.js +1 -1
  61. package/dist/chunk-06jk7ba9.js +7355 -0
  62. package/dist/chunk-0e16qt6k.js +5 -0
  63. package/dist/chunk-13hxhzaz.js +34 -0
  64. package/dist/chunk-2p89vt3b.js +2 -0
  65. package/dist/chunk-77t2ctwn.js +2 -0
  66. package/dist/chunk-88z37ey4.js +114 -0
  67. package/dist/chunk-8c4715hz.js +2 -0
  68. package/dist/chunk-9a22225r.js +60 -0
  69. package/dist/chunk-as6by62d.js +1 -0
  70. package/dist/chunk-cd0zpxhf.js +44 -0
  71. package/dist/chunk-cp54a0qn.js +6 -0
  72. package/dist/chunk-d67xbk4v.js +141 -0
  73. package/dist/chunk-dckz9xve.js +2 -0
  74. package/dist/chunk-e1666vjv.js +2 -0
  75. package/dist/chunk-hhdx5k96.js +442 -0
  76. package/dist/chunk-kv2ztkp4.js +1617 -0
  77. package/dist/chunk-nrz6zypg.js +1 -0
  78. package/dist/chunk-q816js1y.js +1 -0
  79. package/dist/chunk-qh9ep11z.js +704 -0
  80. package/dist/chunk-rg720cqg.js +1 -0
  81. package/dist/chunk-snak8s7m.js +92 -0
  82. package/dist/chunk-vq737g82.js +1 -0
  83. package/dist/chunk-xd6w0c11.js +50 -0
  84. package/dist/chunk-xtwjt370.js +37 -0
  85. package/dist/chunk-y26yh5zp.js +1 -0
  86. package/dist/chunk-zmxffmmq.js +4 -0
  87. package/dist/deploy/attach-credentials.d.ts +4 -8
  88. package/dist/deploy/index.js +1 -168
  89. package/dist/dns/cloudflare.d.ts +27 -0
  90. package/dist/dns/godaddy.d.ts +18 -1
  91. package/dist/dns/index.d.ts +2 -0
  92. package/dist/dns/index.js +1 -41
  93. package/dist/dns/zone-migration.d.ts +92 -0
  94. package/dist/dns/zone-migration.test.d.ts +1 -0
  95. package/dist/drivers/hetzner/driver.d.ts +8 -1
  96. package/dist/drivers/index.js +1 -154
  97. package/dist/drivers/shared/compute-provision.d.ts +14 -2
  98. package/dist/drivers/shared/db-provision.d.ts +3 -2
  99. package/dist/drivers/shared/mail-provision.d.ts +116 -0
  100. package/dist/drivers/shared/mail-provision.test.d.ts +1 -0
  101. package/dist/drivers/shared/managed-services-probe.d.ts +47 -0
  102. package/dist/drivers/shared/managed-services-probe.test.d.ts +1 -0
  103. package/dist/drivers/shared/package-manager.d.ts +1 -0
  104. package/dist/drivers/shared/remote-failure.d.ts +21 -0
  105. package/dist/drivers/shared/remote-failure.test.d.ts +1 -0
  106. package/dist/drivers/shared/sqlite-shared-path.d.ts +50 -0
  107. package/dist/drivers/shared/sqlite-shared-path.test.d.ts +1 -0
  108. package/dist/index.d.ts +2 -0
  109. package/dist/index.js +100 -6129
  110. package/dist/operations/plan.d.ts +136 -0
  111. package/dist/operations/plan.test.d.ts +1 -0
  112. package/dist/operations/server-rename.d.ts +84 -0
  113. package/dist/operations/server-rename.test.d.ts +1 -0
  114. package/dist/operations/site-move.d.ts +263 -0
  115. package/dist/operations/site-move.test.d.ts +1 -0
  116. package/dist/protection/index.js +1 -89
  117. package/dist/push/index.js +1 -509
  118. package/dist/spend/index.js +1 -173
  119. package/dist/ui/404.html +1 -1
  120. package/dist/ui/accept-invitation.html +1 -1
  121. package/dist/ui/access-denied.html +1 -1
  122. package/dist/ui/account/automation.html +5 -5
  123. package/dist/ui/account/security.html +2 -2
  124. package/dist/ui/applications/compose.html +6 -6
  125. package/dist/ui/applications/new.html +2 -2
  126. package/dist/ui/data/backups.html +80 -80
  127. package/dist/ui/data/services.html +78 -78
  128. package/dist/ui/data/volumes.html +50 -50
  129. package/dist/ui/index.html +50 -50
  130. package/dist/ui/infrastructure/topology.html +118 -118
  131. package/dist/ui/integrations.html +1 -1
  132. package/dist/ui/operations/alerts.html +47 -47
  133. package/dist/ui/operations/configuration.html +5 -5
  134. package/dist/ui/operations/jobs.html +76 -76
  135. package/dist/ui/operations/maintenance.html +6 -6
  136. package/dist/ui/operations/observability.html +82 -82
  137. package/dist/ui/operations/previews.html +5 -5
  138. package/dist/ui/operations/queue.html +6 -6
  139. package/dist/ui/operations/regions.html +6 -6
  140. package/dist/ui/operations/releases.html +6 -6
  141. package/dist/ui/operations/spend.html +54 -54
  142. package/dist/ui/operations/workloads.html +104 -104
  143. package/dist/ui/security.html +2 -2
  144. package/dist/ui/server/actions.html +56 -56
  145. package/dist/ui/server/activity.html +1 -1
  146. package/dist/ui/server/capacity.html +6 -6
  147. package/dist/ui/server/database.html +106 -106
  148. package/dist/ui/server/deployments.html +50 -50
  149. package/dist/ui/server/diagnostics.html +2 -2
  150. package/dist/ui/server/firewall.html +76 -76
  151. package/dist/ui/server/fleet.html +34 -34
  152. package/dist/ui/server/logs.html +24 -24
  153. package/dist/ui/server/metrics.html +112 -112
  154. package/dist/ui/server/security.html +1 -1
  155. package/dist/ui/server/services.html +27 -27
  156. package/dist/ui/server/sites.html +120 -120
  157. package/dist/ui/server/ssh-keys.html +51 -51
  158. package/dist/ui/server/team.html +144 -144
  159. package/dist/ui/server/terminal.html +15 -15
  160. package/dist/ui/serverless/alarms.html +52 -52
  161. package/dist/ui/serverless/assets.html +27 -27
  162. package/dist/ui/serverless/cost.html +2 -2
  163. package/dist/ui/serverless/data.html +36 -36
  164. package/dist/ui/serverless/deployments.html +27 -27
  165. package/dist/ui/serverless/firewall.html +1 -1
  166. package/dist/ui/serverless/functions.html +40 -40
  167. package/dist/ui/serverless/logs.html +24 -24
  168. package/dist/ui/serverless/metrics.html +2 -2
  169. package/dist/ui/serverless/queues.html +47 -47
  170. package/dist/ui/serverless/secrets.html +52 -52
  171. package/dist/ui/serverless/traces.html +6 -6
  172. package/dist/ui/serverless.html +54 -54
  173. package/dist/ui-src/src/charts.ts +17499 -12662
  174. package/dist/ui-src/src/topology.ts +2 -2
  175. package/package.json +3 -3
  176. package/dist/bin/chunk-09nwf2gy.js +0 -34
  177. package/dist/bin/chunk-14cwr6eh.js +0 -70
  178. package/dist/bin/chunk-271gk1n2.js +0 -6
  179. package/dist/bin/chunk-38pq971s.js +0 -2
  180. package/dist/bin/chunk-3gykfyq4.js +0 -37
  181. package/dist/bin/chunk-3r4fb59r.js +0 -3
  182. package/dist/bin/chunk-41x17hw1.js +0 -1
  183. package/dist/bin/chunk-4vrqm9h0.js +0 -2
  184. package/dist/bin/chunk-57y1zxbf.js +0 -3
  185. package/dist/bin/chunk-598yf4bs.js +0 -1
  186. package/dist/bin/chunk-8v7ddyvf.js +0 -1
  187. package/dist/bin/chunk-92mea34a.js +0 -1
  188. package/dist/bin/chunk-9pvsff8g.js +0 -1
  189. package/dist/bin/chunk-9v39615t.js +0 -1
  190. package/dist/bin/chunk-avm7tnwe.js +0 -1
  191. package/dist/bin/chunk-ax9mr6wm.js +0 -44
  192. package/dist/bin/chunk-axhnkn5g.js +0 -2
  193. package/dist/bin/chunk-b5gd39s8.js +0 -512
  194. package/dist/bin/chunk-b9qbp8j1.js +0 -1
  195. package/dist/bin/chunk-bz828v8q.js +0 -3
  196. package/dist/bin/chunk-c1vcdgvr.js +0 -1
  197. package/dist/bin/chunk-ctd2vg9w.js +0 -2
  198. package/dist/bin/chunk-dbgffky8.js +0 -1
  199. package/dist/bin/chunk-dwr30vbv.js +0 -1
  200. package/dist/bin/chunk-e3xrwh9z.js +0 -1
  201. package/dist/bin/chunk-fhc6ntvd.js +0 -2
  202. package/dist/bin/chunk-fpm59y25.js +0 -6
  203. package/dist/bin/chunk-fvbxvq6b.js +0 -1
  204. package/dist/bin/chunk-fy8j3y8p.js +0 -92
  205. package/dist/bin/chunk-fz21b57w.js +0 -1
  206. package/dist/bin/chunk-gavvf0pg.js +0 -141
  207. package/dist/bin/chunk-ggn7ax8p.js +0 -4
  208. package/dist/bin/chunk-gpe2prkm.js +0 -1
  209. package/dist/bin/chunk-gqf6jsmy.js +0 -1
  210. package/dist/bin/chunk-h5pa5men.js +0 -2
  211. package/dist/bin/chunk-hm08xdxf.js +0 -2
  212. package/dist/bin/chunk-hzgz13nf.js +0 -1
  213. package/dist/bin/chunk-hzqw8xm5.js +0 -111
  214. package/dist/bin/chunk-j703btc5.js +0 -50
  215. package/dist/bin/chunk-jpjamjey.js +0 -6935
  216. package/dist/bin/chunk-m2zwtapr.js +0 -1
  217. package/dist/bin/chunk-m669wtgr.js +0 -1
  218. package/dist/bin/chunk-mr0atd2s.js +0 -2
  219. package/dist/bin/chunk-ngcyftm2.js +0 -1
  220. package/dist/bin/chunk-p66ptpmr.js +0 -2
  221. package/dist/bin/chunk-p8q9bq9g.js +0 -1
  222. package/dist/bin/chunk-r3kv0vm9.js +0 -6
  223. package/dist/bin/chunk-r9hjwcj9.js +0 -6
  224. package/dist/bin/chunk-rtczra13.js +0 -1
  225. package/dist/bin/chunk-rytk89az.js +0 -60
  226. package/dist/bin/chunk-sgyffpgm.js +0 -581
  227. package/dist/bin/chunk-vek8a0w6.js +0 -1
  228. package/dist/bin/chunk-waayf9ay.js +0 -2
  229. package/dist/bin/chunk-yv9sth30.js +0 -1
  230. package/dist/chunk-01d86gt1.js +0 -1324
  231. package/dist/chunk-050r7ycy.js +0 -46516
  232. package/dist/chunk-1c8dbv57.js +0 -7278
  233. package/dist/chunk-29rse4p1.js +0 -12203
  234. package/dist/chunk-32e7ya18.js +0 -642
  235. package/dist/chunk-4cjrg98a.js +0 -597
  236. package/dist/chunk-50jpda9q.js +0 -371
  237. package/dist/chunk-6a1t7fnq.js +0 -12121
  238. package/dist/chunk-728jvrr0.js +0 -1701
  239. package/dist/chunk-7m60qnc8.js +0 -1762
  240. package/dist/chunk-aa2dkn7b.js +0 -205
  241. package/dist/chunk-d48vtdj4.js +0 -433
  242. package/dist/chunk-f55nkpvb.js +0 -8
  243. package/dist/chunk-fgk8cqew.js +0 -152
  244. package/dist/chunk-he9a874b.js +0 -769
  245. package/dist/chunk-k2yyatfw.js +0 -10
  246. package/dist/chunk-k4px0bnv.js +0 -23
  247. package/dist/chunk-nsgqsmrh.js +0 -1779
  248. package/dist/chunk-q0st3se8.js +0 -42033
  249. package/dist/chunk-qr803fye.js +0 -2122
  250. package/dist/chunk-rds0sy87.js +0 -1771
  251. package/dist/chunk-ttz2ra5j.js +0 -12
  252. package/dist/chunk-v0bahtg2.js +0 -4
  253. package/dist/chunk-va2yd85b.js +0 -200
  254. package/dist/chunk-x9s0cqfx.js +0 -13
  255. package/dist/chunk-zqtpg06c.js +0 -1752
@@ -0,0 +1,2 @@
1
+ import{mg as y}from"./chunk-b35989e3.js";import{bh as Z}from"./chunk-ey9fagrr.js";var b=new Set(["A","AAAA","CNAME"]);function I(t,e=""){return t===408||t===409||t===425||t===429||t>=500||/rate limit|temporar|timed? ?out|try again/i.test(e)}async function P(t,e){let r=e?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,s=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(t-1),30000);await new Promise((o)=>setTimeout(o,s))}class h{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(t,e,r=15000){this.apiKey=t,this.secretKey=e,this.requestTimeoutMs=r}async request(t,e={}){let r;for(let n=1;n<=8;n+=1){let s,o=new AbortController,i=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{s=await fetch(`https://api.porkbun.com/api/json/v3${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...e}),signal:o.signal})}catch(c){if(r=c,n===8)throw c;await P(n);continue}finally{clearTimeout(i)}if(!s.ok){if(r=Error(`Porkbun API error: ${s.status} ${s.statusText}`),!I(s.status)||n===8)throw r;await P(n,s);continue}let a=await s.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!I(0,a.message)||n===8)throw r;await P(n,s);continue}return a}throw r}getSubdomain(t,e){let r=t.replace(/\.$/,""),n=e.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(t){let e=t.replace(/\.$/,"").split(".");if(e.length>=2)return e.slice(-2).join(".");return t}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(t,e){if(!h.ADDRESS_TYPES.has(e.type))return[];let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s=await this.listRecords(t);if(!s.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${s.message??"unknown provider error"}`];let o=[];for(let i of s.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(t,i);if(!a.success)o.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return o}async addressRecordExists(t,e){let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s=await this.listRecords(t);if(!s.success)return!0;return s.records.some((o)=>o.type===e.type&&this.getSubdomain(o.name,r)===n&&o.content===e.content)}async createRecord(t,e){try{let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s={type:e.type,content:e.content,ttl:String(e.ttl||600)};if(n)s.name=n;if((e.type==="MX"||e.type==="SRV")&&e.priority!==void 0)s.prio=String(e.priority);if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)s.content=`${e.weight} ${e.port} ${e.content}`;let o=await this.clearConflictingAliases(t,e),i=await this.request(`/dns/create/${r}`,s);if(h.ADDRESS_TYPES.has(e.type)&&!await this.addressRecordExists(t,e))return{success:!1,message:`Porkbun reported success but no ${e.type} record for ${e.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(t,e){try{let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s=await this.listRecords(t,e.type);if(s.success){let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===e.type);if(o?.id){let i={type:e.type,content:e.content,ttl:String(e.ttl||600)};if(n)i.name=n;if((e.type==="MX"||e.type==="SRV")&&e.priority!==void 0)i.prio=String(e.priority);if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)i.content=`${e.weight} ${e.port} ${e.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,i),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(t,e)}catch(r){return this.createRecord(t,e)}}async deleteRecord(t,e){try{let r=this.getRootDomain(t);if("id"in e&&e.id)return await this.request(`/dns/delete/${r}/${e.id}`),{success:!0,message:"Record deleted successfully"};let n=this.getSubdomain(e.name,r),s=await this.listRecords(t);if(!s.success)return{success:!1,message:"Failed to list records"};let o=s.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===e.type&&i.content===e.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(t,e){try{let r=this.getRootDomain(t),n=`/dns/retrieve/${r}`;if(e)n=`/dns/retrieveByNameType/${r}/${e}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(t){try{let e=this.getRootDomain(t);return await this.request(`/dns/retrieve/${e}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((e)=>e.domain)}catch{return[]}}async getNameServers(t){try{let e=this.getRootDomain(t);return(await this.request(`/dns/getNS/${e}`)).ns||[]}catch{return[]}}async updateNameServers(t,e){try{let r=this.getRootDomain(t);return await this.request(`/dns/updateNS/${r}`,{ns:e}),!0}catch{return!1}}}class D{name="godaddy";apiKey;apiSecret;baseUrl;constructor(t,e,r="production"){this.apiKey=t,this.apiSecret=e,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}async request(t,e,r){let n=`${this.baseUrl}${e}`,s={Authorization:`sso-key ${this.apiKey}:${this.apiSecret}`,"Content-Type":"application/json",Accept:"application/json"},o={method:t,headers:s};if(r)o.body=JSON.stringify(r);let i=await fetch(n,o);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(t,e){let r=t.replace(/\.$/,""),n=e.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(t){let e=t.replace(/\.$/,"").split(".");if(e.length>=2)return e.slice(-2).join(".");return t}toGoDaddyRecord(t,e){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),s={type:t.type,name:n,data:t.content,ttl:t.ttl||600};if(t.type==="MX"&&t.priority!==void 0)s.priority=t.priority;return s}fromGoDaddyRecord(t,e){let r=this.getRootDomain(e),n=t.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:t.type,content:t.data,ttl:t.ttl,priority:t.priority}}async createRecord(t,e){try{let r=this.getRootDomain(t),n=this.toGoDaddyRecord(e,t);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(t,e){try{let r=this.getRootDomain(t),n=this.toGoDaddyRecord(e,t);return await this.request("PUT",`/v1/domains/${r}/records/${e.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(t,e)}}async deleteRecord(t,e){try{let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),s=await this.request("GET",`/v1/domains/${r}/records/${e.type}/${n}`),o=s.filter((i)=>i.data!==e.content);if(o.length===s.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${e.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${e.type}/${n}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(t,e){try{let r=this.getRootDomain(t),n=`/v1/domains/${r}/records`;if(e)n=`/v1/domains/${r}/records/${e}`;return{success:!0,records:(await this.request("GET",n)).map((o)=>this.fromGoDaddyRecord(o,t))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(t){try{let e=this.getRootDomain(t);return await this.request("GET",`/v1/domains/${e}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((e)=>e.domain)}catch{return[]}}async getDomainDetails(t){try{let e=this.getRootDomain(t),r=await this.request("GET",`/v1/domains/${e}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(t){return(await this.getDomainDetails(t))?.nameServers??[]}async updateNameServers(t,e){try{let r=this.getRootDomain(t);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:e}),!0}catch{return!1}}async checkDomainAvailability(t){try{let e=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(t)}`);return{available:e.available,price:e.price,currency:e.currency}}catch{return{available:!1}}}}var _="https://api.cloudflare.com/client/v4",N="[ts-cloud]";class v{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(t,e={}){this.apiToken=t,this.configuredZoneId=e.zoneId,this.accountId=e.accountId}async request(t,e,r){let n=`${_}${e}`,s={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:t,headers:s};if(r)o.body=JSON.stringify(r);let a=await(await fetch(n,o)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}getRootDomain(t){let e=t.replace(/\.$/,"").split(".");if(e.length>=2)return e.slice(-2).join(".");return t}async resolveZone(t){let e=t.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let i=await this.resolveConfiguredZoneName();if(i&&(e===i||e.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(e),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let s=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!s.result||s.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=s.result[0].id;return this.zoneCache.set(r,o),{id:o,name:s.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let e=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!e)return;return this.configuredZoneName=e,this.zoneCache.set(e,this.configuredZoneId),e}catch{return}}async getZoneId(t){return(await this.resolveZone(t)).id}getFullRecordName(t,e){let r=t.replace(/\.$/,"");if(!r||r===e||r==="@")return e;if(r.endsWith(`.${e}`))return r;return`${r}.${e}`}toCloudflareRecord(t,e,r){let n={type:t.type,name:this.getFullRecordName(t.name,e),content:t.content||t.value||"",ttl:t.ttl||1},s=r??t.proxied;if(s!==void 0&&b.has(t.type)){if(n.proxied=s,s)n.ttl=1}if(t.type==="MX"&&t.priority!==void 0)n.priority=t.priority;if(t.type==="SRV"){let o=O(t);if(o)n.data=o,delete n.content,delete n.priority;else if(t.priority!==void 0)n.priority=t.priority}return n}fromCloudflareRecord(t){return{id:t.id,name:t.name,type:t.type,content:t.content,ttl:t.ttl,priority:t.priority,proxied:t.proxied}}async createRecord(t,e){try{let r=await this.resolveZone(t),n=this.toCloudflareRecord(e,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(t,e){try{let r=await this.resolveZone(t),n=this.getFullRecordName(e.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${e.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=e.proxied??o?.proxied,a=this.toCloudflareRecord(e,r.name,i);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(t,e)}}async deleteRecord(t,e){try{let r=await this.resolveZone(t),n=r.id,s=this.getFullRecordName(e.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${e.type}&name=${encodeURIComponent(s)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let i=o.result.find((a)=>a.content===e.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(t,e){try{let n=`/zones/${await this.getZoneId(t)}/dns_records?per_page=100`;if(e)n+=`&type=${e}`;let s=[],o=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${o}`);if(s.push(...a.result||[]),a.result_info)i=o<a.result_info.total_pages,o++;else i=!1}return{success:!0,records:s.map((a)=>this.fromCloudflareRecord(a))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(t){try{return await this.getZoneId(t),!0}catch{return!1}}async listDomains(){try{let t=[],e=1,r=!0;while(r){let n=await this.request("GET",`/zones?per_page=50&page=${e}`);if(t.push(...n.result||[]),n.result_info)r=e<n.result_info.total_pages,e++;else r=!1}return t.map((n)=>n.name)}catch{return[]}}async createZone(t,e={}){let r=t.replace(/\.$/,"").toLowerCase(),n=e.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);try{let o=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:e.jumpStart??!1})).result;return this.zoneCache.set(o.name,o.id),{id:o.id,name:o.name,status:o.status,nameServers:o.name_servers??[],created:!0}}catch(s){let o=s instanceof Error?s.message:String(s);if(!/already exists|1061/i.test(o))throw s;let i=await this.getZoneDetails(r);if(!i)throw s;return{...i,created:!1}}}async getZoneDetails(t){try{let e=await this.getZoneId(t),r=await this.request("GET",`/zones/${e}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async purgeCache(t,e){try{let r=await this.getZoneId(t),n={};if(e?.purgeEverything)n.purge_everything=!0;else{if(e?.files)n.files=e.files;if(e?.tags)n.tags=e.tags;if(e?.hosts)n.hosts=e.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(t,e){try{let r=await this.resolveZone(t),n=r.id,s=this.getFullRecordName(e.name,r.name),o=await this.request("GET",`/zones/${n}/dns_records?type=${e.type}&name=${encodeURIComponent(s)}`);if(o.result&&o.result.length>0)return o.result.find((a)=>a.content===e.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(t,e,r){try{let n=await this.resolveZone(t),s=n.id,o=this.getFullRecordName(e.name,n.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${e.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===e.content);if(!a)return!1;return await this.request("PATCH",`/zones/${s}/dns_records/${a.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(t){return this.getZoneId(t)}get account(){return this.accountId}async getZoneSettings(t){let e=await this.getZoneId(t),r=await this.request("GET",`/zones/${e}/settings`),n={};for(let s of r.result||[])n[s.id]=s.value;return n}async applyZoneSettings(t,e){let r=await this.getZoneId(t),n=await this.getZoneSettings(t).catch(()=>({})),s=[],o=[];for(let[i,a]of Object.entries(e)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&S(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),s.push({id:i,from:c,to:a})}catch(d){o.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:s,failed:o}}async getPhaseRules(t,e){let r=await this.getZoneId(t);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${e}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(t,e,r){try{let n=await this.getZoneId(t),o=(await this.getPhaseRules(t,e)).filter((c)=>!(c.description||"").startsWith(N)),i=r.map((c)=>({...c,description:c.description?.startsWith(N)?c.description:`${N} ${c.description||e}`})),a=[...o,...i].map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${e}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}function S(t,e){if(t===e)return!0;if(typeof t!==typeof e||t===null||e===null)return!1;if(typeof t!=="object")return!1;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;return t.every((s,o)=>S(s,e[o]))}let r=t,n=e;return Object.keys(n).every((s)=>S(r[s],n[s]))}function O(t){let e=(t.content||t.value||"").trim();if(t.weight!==void 0&&t.port!==void 0&&t.priority!==void 0&&e)return{priority:t.priority,weight:t.weight,port:t.port,target:E(e)};let r=e.split(/\s+/);if(r.length<4)return null;let[n,s,o]=r.slice(0,3).map(Number);if(![n,s,o].every(Number.isFinite))return null;return{priority:n,weight:s,port:o,target:E(r.slice(3).join(" "))}}function E(t){return t.replace(/\.$/,"")}var k=new Set(["A","AAAA","CNAME","ALIAS"]);function w(t){let e=t.trim().replace(/^"|"$/g,"").toLowerCase();if(e.startsWith("v=spf1"))return"v=spf1";if(e.startsWith("v=dmarc1"))return"v=dmarc1";return}function f(t){return t.trim().replace(/^"(.*)"$/s,"$1")}function p(t){return t.replace(/\.$/,"").toLowerCase()}function x(t,e){let r=p(e),n=(t??"@").trim();if(!n||n==="@")return r;let s=p(n);if(s===r||s.endsWith(`.${r}`))return s;return`${s}.${r}`}function z(t,e){return t.map((r)=>({...r,name:x(r.name,e),proxied:r.proxied??!1}))}function L(t,e){if(t.type!==e.type)return!1;if(p(t.name)!==p(e.name))return!1;if(k.has(e.type))return!0;if(e.type==="TXT"){let r=w(e.content);if(r)return w(f(t.content))===r;return f(t.content)===f(e.content)}return f(t.content)===f(e.content)}function q(t,e){if(f(t.content)!==f(e.content))return!1;if(e.priority!==void 0&&t.priority!==e.priority)return!1;if(e.proxied!==void 0&&t.proxied!==void 0&&t.proxied!==e.proxied)return!1;return!0}async function U(t){let{provider:e,zone:r,records:n}=t,s={outcomes:[],warnings:[]};if(n.length===0)return s;let o=await e.listRecords(r);if(!o.success)return s.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),s;let i=o.records;for(let a of n){let c=i.filter((u)=>L(u,a));if(c.length>0&&c.every((u)=>q(u,a))){s.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},m=a.type==="TXT"&&w(a.content)!==void 0;if(m)for(let u of c){let T=await e.deleteRecord(r,{name:u.name,type:u.type,content:u.content});if(!T.success)s.warnings.push(`could not remove superseded ${u.type} at ${u.name}: ${T.message||"unknown error"}`)}let g=m||c.length===0?await e.createRecord(r,d):await e.upsertRecord(r,d);if(g.success)s.outcomes.push({record:a,action:c.length>0?"updated":"created"});else s.outcomes.push({record:a,action:"failed",message:g.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>p(d.name)));for(let d of c){let m=new Set(n.filter((u)=>u.type===a&&p(u.name)===d).map((u)=>f(u.content).toLowerCase())),g=i.filter((u)=>u.type===a&&p(u.name)===d&&!m.has(f(u.content).toLowerCase()));for(let u of g)s.warnings.push(`${d} has an undeclared ${a} record (${u.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return s}class A{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(t="us-east-1",e){this.client=new y(t),this.providedHostedZoneId=e}getRootDomain(t){let e=t.replace(/\.$/,"").split(".");if(e.length>=2)return e.slice(-2).join(".");return t}async getHostedZoneId(t){if(this.providedHostedZoneId)return this.providedHostedZoneId;let e=this.getRootDomain(t),r=this.hostedZoneCache.get(e);if(r)return r;let n=await this.client.findHostedZoneForDomain(t);if(n){let s=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(e,s),s}return null}normalizeName(t,e){let r=t.replace(/\.$/,""),n=e.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}async createRecord(t,e){try{let r=await this.getHostedZoneId(t);if(!r)return{success:!1,message:`No hosted zone found for domain: ${t}`};let n=this.normalizeName(t,e.name),s=e.content;if(e.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(e.type==="MX"&&e.priority!==void 0)s=`${e.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:n,Type:e.type,TTL:e.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(t,e){try{let r=await this.getHostedZoneId(t);if(!r)return{success:!1,message:`No hosted zone found for domain: ${t}`};let n=this.normalizeName(t,e.name),s=e.content;if(e.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(e.type==="MX"&&e.priority!==void 0)s=`${e.priority} ${s}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:e.type,TTL:e.ttl||300,ResourceRecords:[{Value:s}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(t,e){try{let r=await this.getHostedZoneId(t);if(!r)return{success:!1,message:`No hosted zone found for domain: ${t}`};let n=this.normalizeName(t,e.name),s=e.content;if(e.type==="TXT"&&!s.startsWith('"'))s=`"${s}"`;if(e.type==="MX"&&e.priority!==void 0)s=`${e.priority} ${s}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:n,Type:e.type,TTL:e.ttl||300,ResourceRecords:[{Value:s}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(t,e){try{let r=await this.getHostedZoneId(t);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${t}`};let n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:e}),s=[];for(let o of n.ResourceRecordSets){if(e&&o.Type!==e)continue;if(o.AliasTarget)continue;for(let i of o.ResourceRecords||[]){let a=i.Value,c;if(o.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(o.Type==="TXT"&&a.startsWith('"')&&a.endsWith('"'))a=a.slice(1,-1);s.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:a,ttl:o.TTL,priority:c})}}return{success:!0,records:s}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(t){return await this.getHostedZoneId(t)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((e)=>e.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(t){try{let e=await this.getHostedZoneId(t.domain);if(!e)return{success:!1,message:`No hosted zone found for domain: ${t.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:e,Name:this.normalizeName(t.domain,t.name),TargetHostedZoneId:t.targetHostedZoneId,TargetDNSName:t.targetDnsName,EvaluateTargetHealth:t.evaluateTargetHealth,Type:t.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(e){return{success:!1,message:e instanceof Error?e.message:"Unknown error"}}}async createCloudFrontAlias(t){return this.createAliasRecord({domain:t.domain,name:t.name,targetHostedZoneId:y.CloudFrontHostedZoneId,targetDnsName:t.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(t){let e=y.ALBHostedZoneIds[t.region];if(!e)return{success:!1,message:`Unknown region for ALB: ${t.region}`};return this.createAliasRecord({domain:t.domain,name:t.name,targetHostedZoneId:e,targetDnsName:t.albDnsName,evaluateTargetHealth:!0})}}async function j(t,e){let r=[],n,s;for(;;){let o=await t.listResourceRecordSets({HostedZoneId:e,StartRecordName:n,StartRecordType:s,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(n=o.NextRecordName,s=o.NextRecordType,!n)break}return r}function l(t){return t.replace(/\.$/,"").toLowerCase()}function F(t){let e=t.match(/"(?:[^"\\]|\\.)*"/g);if(!e)return t;return e.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function G(t,e){let r=l(e),n=[],s=[],o=[],i=new Set;for(let a of t){let c=l(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){s.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){s.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let m=l(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:m,ttl:300,translatedFrom:`${d} ALIAS → ${m}`}),a.AliasTarget.EvaluateTargetHealth)o.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let m of a.ResourceRecords||[]){let g=W(c,d,m.Value,a.TTL);if("reason"in g){s.push({name:c,type:d,reason:g.reason}),o.push(`${d} ${c}: ${g.reason}`);continue}n.push(g)}}return{zone:r,records:n,skipped:s,warnings:o}}function W(t,e,r,n){let s={name:t,ttl:n};switch(e){case"A":case"AAAA":case"CNAME":case"PTR":return{...s,type:e==="PTR"?"CNAME":e,content:l(r)};case"TXT":return{...s,type:"TXT",content:F(r)};case"MX":{let[o,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...s,type:"MX",content:l(i.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=o.slice(0,3).map(Number);return{...s,type:"SRV",content:l(o.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...s,type:"NS",content:l(r)};case"CAA":return{...s,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${e}`}}}async function H(t,e){let r=[],n=[];for(let s of e.records){let o=await t.upsertRecord(e.zone,{...s,proxied:!1});if(o.success)r.push(s);else n.push({record:s,message:o.message||"unknown provider error"})}return{applied:r,failed:n}}async function K(t,e){let r=await t.listRecords(e.zone),n=[],s=[],o=new Map;for(let i of r.records||[]){let a=`${l(i.name)}|${i.type}`,c=o.get(a)??[];c.push(l(String(i.content))),o.set(a,c)}for(let i of e.records){let a=o.get(`${l(i.name)}|${i.type}`),c=l(i.content);if(a?.some((d)=>d===c||d.includes(c)||c.includes(d)))n.push(i);else s.push({record:i,found:a?.join(", ")})}return{matched:n,missing:s,ok:s.length===0}}class V{acm;dnsProvider;constructor(t,e="us-east-1"){if(this.acm=new C(e),"provider"in t)this.dnsProvider=R(t);else this.dnsProvider=t}getProvider(){return this.dnsProvider}async requestAndValidate(t){let{domainName:e,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:s=30}=t,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:e,SubjectAlternativeNames:r.length>0?[e,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let i=await this.acm.getDnsValidationRecords(o);for(let c of i){let d=await this.dnsProvider.upsertRecord(e,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(o,s*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(t){let{certificateArn:e,domain:r}=t,n=[],s=await this.acm.getDnsValidationRecords(e);for(let o of s){let i=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,records:s.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:n}}async deleteValidationRecords(t){let{certificateArn:e,domain:r}=t,n=[],s=await this.acm.getDnsValidationRecords(e);for(let o of s){let i=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!i.success)n.push(`Failed to delete record for ${o.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(t){let{domainName:e,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:s}=t,o=await this.acm.findCertificateByDomain(e);if(o&&o.Status==="ISSUED"){let i=o.SubjectAlternativeNames||[o.DomainName],a=i.some((d)=>d===`*.${e}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:e,subjectAlternativeNames:r,waitForValidation:n,maxWaitMinutes:s})}async requestCertificateWithCommonSans(t){let{domainName:e,includeWww:r=!0,includeWildcard:n=!1,additionalSans:s=[],waitForValidation:o=!1}=t,i=[];if(r)i.push(`www.${e}`);if(n)i.push(`*.${e}`);return i.push(...s),this.requestAndValidate({domainName:e,subjectAlternativeNames:i,waitForValidation:o})}async waitForValidationOptions(t,e=30){for(let r=0;r<e;r++){let n=await this.acm.describeCertificate({CertificateArn:t});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(t){let e=await this.acm.describeCertificate({CertificateArn:t});return{status:e.Status,domainValidations:(e.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function R(t){switch(t.provider){case"route53":return new A(t.region,t.hostedZoneId);case"porkbun":return new h(t.apiKey,t.secretKey);case"godaddy":return new D(t.apiKey,t.apiSecret,t.environment);case"cloudflare":return new v(t.apiToken,{zoneId:t.zoneId,accountId:t.accountId});default:throw Error(`Unknown DNS provider: ${t.provider}`)}}class M{providers=new Map;configs=[];addConfig(t){return this.configs.push(t),this}addRoute53(t,e){return this.configs.push({provider:"route53",region:t,hostedZoneId:e}),this}addPorkbun(t,e){return this.configs.push({provider:"porkbun",apiKey:t,secretKey:e}),this}addGoDaddy(t,e,r){return this.configs.push({provider:"godaddy",apiKey:t,apiSecret:e,environment:r}),this}addCloudflare(t,e={}){return this.configs.push({provider:"cloudflare",apiToken:t,zoneId:e.zoneId,accountId:e.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let t=process.env.PORKBUN_API_KEY,e=process.env.PORKBUN_SECRET_KEY;if(t&&e)this.addPorkbun(t,e);let r=process.env.GODADDY_API_KEY,n=process.env.GODADDY_API_SECRET;if(r&&n){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,o)}let s=process.env.CLOUDFLARE_API_TOKEN;if(s)this.addCloudflare(s,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(t){let e=this.providers.get(t);if(e)return e;let r=this.configs.find((s)=>s.provider===t);if(!r)return null;let n=R(r);return this.providers.set(t,n),n}async getProviderForDomain(t){for(let e of this.configs){let r=R(e);if(await r.canManageDomain(t))return r}return null}getAllProviders(){return this.configs.map((t)=>R(t))}}var pe=new M;class C{client;region;constructor(t="us-east-1"){this.client=new Z,this.region=t}async requestCertificate(t){let e={DomainName:t.DomainName,ValidationMethod:t.ValidationMethod||"DNS"};if(t.SubjectAlternativeNames)e.SubjectAlternativeNames=t.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(e)})).CertificateArn||""}}async describeCertificate(t){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:t.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(t){let e={};if(t?.CertificateStatuses)e.CertificateStatuses=t.CertificateStatuses;if(t?.MaxItems)e.MaxItems=t.MaxItems;if(t?.NextToken)e.NextToken=t.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(e)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((n)=>({CertificateArn:n.CertificateArn,DomainName:n.DomainName})),NextToken:r.NextToken}}async deleteCertificate(t){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:t.CertificateArn})})}async listTagsForCertificate(t){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:t.CertificateArn})})).Tags||[]}}async addTagsToCertificate(t){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:t.CertificateArn,Tags:t.Tags})})}async resendValidationEmail(t){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:t.CertificateArn,Domain:t.Domain,ValidationDomain:t.ValidationDomain})})}async findCertificateByDomain(t){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((n)=>n.DomainName===t||n.DomainName===`*.${t.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(t,e=60,r=30000){for(let n=0;n<e;n++){let s=await this.describeCertificate({CertificateArn:t});if(s.Status==="ISSUED")return s;if(s.Status==="FAILED"||s.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(t){let e=await this.describeCertificate({CertificateArn:t});if(!e.DomainValidationOptions)return[];return e.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(t){let e=new Set;if(e.add(t.DomainName),t.IncludeWww!==!1)e.add(`www.${t.DomainName}`);if(t.IncludeWildcard)e.add(`*.${t.DomainName}`);if(t.AdditionalSans)for(let r of t.AdditionalSans)e.add(r);return this.requestCertificate({DomainName:t.DomainName,SubjectAlternativeNames:Array.from(e),ValidationMethod:"DNS"})}async isCertificateValidForDomain(t,e){let r=await this.describeCertificate({CertificateArn:t});if(r.Status!=="ISSUED")return!1;if(r.DomainName===e)return!0;if(r.DomainName?.startsWith("*.")){let n=r.DomainName.slice(2),s=e.split("."),o=n.split(".");if(s.slice(-o.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===e)return!0;if(n.startsWith("*.")){let s=n.slice(2),o=e.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}}return!1}}class X{acm;route53;dnsProvider;constructor(t="us-east-1",e){if(this.acm=new C(t),this.route53=new y,e&&e.provider!=="route53")this.dnsProvider=R(e)}async requestAndValidate(t){let{domainName:e,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=t;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:e,SubjectAlternativeNames:n.length>0?[e,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(e,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(s){if(!await this.acm.waitForCertificateValidation(i,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(t,e=30){for(let r=0;r<e;r++){let n=await this.acm.describeCertificate({CertificateArn:t});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((s)=>setTimeout(s,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(t){let{certificateArn:e,hostedZoneId:r,domain:n}=t;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.getDnsValidationRecords(e),o=[];if(this.dnsProvider){let i=n||s[0]?.domainName;for(let a of s){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});o.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of s){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});o.push({...i,changeId:a.ChangeInfo?.Id})}return o}async deleteValidationRecords(t){let{certificateArn:e,hostedZoneId:r,domain:n}=t,s=await this.acm.getDnsValidationRecords(e);if(this.dnsProvider){let o=n||s[0]?.domainName;for(let i of s)try{await this.dnsProvider.deleteRecord(o,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let o of s)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(t){let{domainName:e,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s=!0}=t;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(e);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:e,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:s});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
+ export{h as gd,D as hd,v as id,z as jd,U as kd,A as ld,j as md,G as nd,H as od,K as pd,C as qd,X as rd,V as sd,R as td,M as ud};
@@ -0,0 +1,2 @@
1
+ import{bh as d}from"./chunk-ey9fagrr.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let p=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(p,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class C{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new d(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
2
+ export{C as Zd};
@@ -0,0 +1,2 @@
1
+ import{Gg as O}from"./chunk-kybdb0ws.js";import{Ng as E}from"./chunk-1v6bt68w.js";import{$o as j,Vo as I,_o as U,go as R,io as b,so as A}from"./chunk-anm3ae6z.js";import{execFileSync as B}from"node:child_process";import{mkdirSync as v,mkdtempSync as q,rmSync as N,writeFileSync as m}from"node:fs";import{tmpdir as F}from"node:os";import{dirname as T,join as i}from"node:path";function C(n,e){for(let t of e){let c=i(n,t.name);v(T(c),{recursive:!0}),m(c,t.data,t.mode?{mode:t.mode}:void 0)}}async function Q(n){let{app:e,projectRoot:t,region:c,repository:d}=n,w=e.architecture??"x86_64",P=w==="arm64"?"linux/arm64":"linux/amd64",z=e.kind==="php",o=n.onStep??(()=>{}),s=q(i(F(),"tscloud-img-"));try{let g=i(s,"app");v(g,{recursive:!0});let h,f;if(z){U({projectRoot:t,app:e,skipBuild:n.skipBuild,onStep:o}),o("staging application tree");let r=j(t);C(g,r),C(i(s,"runtime"),I().map((p)=>({name:p.path,data:p.contents,mode:p.mode})));let S=e.handlers?.http??"public/index.php";h={http:S,queue:e.handlers?.queue??S,cli:e.handlers?.cli??S},f=R(r.map((p)=>`${p.name}:${p.data.length}`).join("|"))}else{o("bundling application");let r=await b({projectRoot:t,app:e,skipBuild:n.skipBuild,onStep:o});m(i(g,"index.mjs"),r.bundle),h=r.handlers,f=r.sha256}let x=f.slice(0,16);m(i(s,"Dockerfile"),A({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:w}));let y=new O(c),a;try{a=(await y.describeRepositories({repositoryNames:[d]})).repositories?.[0]?.repositoryUri??""}catch{a=""}if(!a)o(`creating ECR repository ${d}`),a=(await y.createRepository({repositoryName:d,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!a)throw Error(`could not resolve ECR repository URI for ${d}`);let u=`${a}:${x}`;o("docker build"),B("docker",["build","--platform",P,"--provenance=false","--sbom=false","-t",u,s],{stdio:"inherit"}),o("ecr auth + push");let l=(await y.getAuthorizationToken()).authorizationData?.[0];if(!l?.authorizationToken||!l.proxyEndpoint)throw Error("failed to get an ECR authorization token");let D=l.proxyEndpoint.replace(/^https?:\/\//,""),k=i(s,".docker");return v(k,{recursive:!0}),m(i(k,"config.json"),JSON.stringify({auths:{[D]:{auth:l.authorizationToken}}})),B("docker",["push",u],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:k}}),E(`Image: ${u}`),{imageUri:u,tag:x,handlers:h}}finally{N(s,{recursive:!0,force:!0})}}
2
+ export{Q as Fg};
@@ -0,0 +1,60 @@
1
+ import{ld as Z,qd as L,rd as Y,sd as _,td as K}from"./chunk-nb0yjkv5.js";import{vd as U}from"./chunk-6zjy949y.js";import{hg as W}from"./chunk-6eat8ezk.js";import{mg as M}from"./chunk-b35989e3.js";import{og as B}from"./chunk-d6zzgvtn.js";import{mp as j}from"./chunk-b2ymh8k0.js";function J(t){let{bucketName:s,domain:l,aliases:e,certificateArn:m,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:b=!1,computeOriginDomain:k,computeOriginPort:R=3008,computeOriginId:P="app-compute",retainOnStackDelete:x=!1}=t,A=x?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=b&&!!k,T=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],F=y?["GET","HEAD"]:["GET","HEAD"],N={},O={};N.S3Bucket={Type:"AWS::S3::Bucket",...A,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},O.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},O.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},N.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...A,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let D;if(a&&y)D="InstallRootRedirectFunction",N[D]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
2
+ var request = event.request;
3
+ if (request.uri === '/' || request.uri === '') {
4
+ return {
5
+ statusCode: 302,
6
+ statusDescription: 'Found',
7
+ headers: {
8
+ location: { value: 'https://' + request.headers.host.value + '/install.sh' }
9
+ }
10
+ };
11
+ }
12
+ return request;
13
+ }`}};if(!a)N.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
14
+ const request = event.request;
15
+ var uri = request.uri;
16
+
17
+ // If URI ends with /, serve index.html
18
+ if (uri.endsWith('/')) {
19
+ request.uri = uri + 'index.html';
20
+ }
21
+ // If URI doesn't have an extension, append .html
22
+ else if (!uri.includes('.')) {
23
+ request.uri = uri + '.html';
24
+ }
25
+
26
+ return request;
27
+ }`}};let w={Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},u=y?{Id:P,DomainName:k,CustomOriginConfig:{HTTPPort:R,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,C=y?P:`S3-${s}`,f={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:u?[u,w]:[w],DefaultCacheBehavior:{TargetOriginId:C,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:T,CachedMethods:F,Compress:!0,...y?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...a&&D?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[D,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!a&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...y&&a?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:d?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(l&&m)f.Aliases=e&&e.length>0?e:[l],f.ViewerCertificate={AcmCertificateArn:m,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else f.ViewerCertificate={CloudFrontDefaultCertificate:!0};return N.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...A,DependsOn:["S3Bucket","CloudFrontOAC",...a&&y&&D?[D]:[],...!a?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:f}},O.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},O.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},N.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...A,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},O.SiteUrl={Description:"Site URL",Value:l?`https://${l}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${l||s} (External DNS)`,Resources:N,Outputs:O}}async function G(t){let s=t.region||"us-east-1",l="us-east-1",e=t.domain,m=t.bucket||e.replace(/\./g,"-"),i=t.stackName||`${t.siteName}-static-site`,r=new W("us-east-1"),a=new L("us-east-1"),d=null;if(!t.skipDnsVerification){d=K(t.dnsProvider),console.log(`Verifying DNS provider can manage ${e}...`);let o=await d.listRecords(e);if(!o.success){let n=o.message||"unknown error — check API credentials and domain ownership";return{success:!1,stackName:i,bucket:m,message:`DNS provider '${d.name}' cannot manage domain ${e}: ${n}`}}console.log(`DNS provider '${d.name}' verified for ${e}`)}else console.log(`Skipping DNS verification for ${e}`);let b=t.certificateArn,P=e.split(".").length===2?`www.${e}`:void 0;if(!b){console.log(`Checking for existing SSL certificate for ${e}...`);let o=await a.findCertificateByDomain(e),n=!1;if(o&&o.Status==="ISSUED"){if(P&&o.SubjectAlternativeNames)n=o.SubjectAlternativeNames.includes(P)||o.SubjectAlternativeNames.some((g)=>g===`*.${e}`);else n=!0;if(n)b=o.CertificateArn,console.log(`Found existing certificate with www coverage: ${b}`);else console.log(`Existing certificate doesn't cover ${P}, requesting new one...`)}if(!b){if(!d)return{success:!1,stackName:i,bucket:m,message:`No DNS provider available to validate SSL certificate for ${e}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${e}${P?` (including ${P})`:""}...`);let p=await new _(d,"us-east-1").findOrCreateCertificate({domainName:e,subjectAlternativeNames:P?[P]:void 0,waitForValidation:!0,maxWaitMinutes:10});if(p.status!=="issued")return{success:!1,stackName:i,bucket:m,message:`SSL certificate validation failed. Status: ${p.status}`};b=p.certificateArn,console.log(`Certificate issued: ${b}`)}}let x=!1,A;try{let o=await r.describeStacks({stackName:i});if(o.Stacks.length>0){let n=o.Stacks[0],g=n.StackStatus;if(g==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),x=!1;else if(g==="DELETE_COMPLETE")x=!1;else x=!0,A=(n.Outputs||[]).find((c)=>c.OutputKey==="BucketName")?.OutputValue}}catch(o){if(o.message?.includes("does not exist")||o.code==="ValidationError")x=!1;else throw o}let y=A||m;if(!x){let o=new B(s),n=new U,g=!1;if(e)try{console.log(`Checking for existing CloudFront distributions with alias ${e}...`);let p=await n.listDistributions();for(let c of p){let S=[];if(c.Aliases?.Items){if(Array.isArray(c.Aliases.Items))S=c.Aliases.Items;else if(typeof c.Aliases.Items==="object"){let I=c.Aliases.Items.CNAME;if(typeof I==="string")S=[I];else if(Array.isArray(I))S=I}}if(S.includes(e)){g=!0,console.log(`Found existing CloudFront distribution ${c.Id} with alias ${e}`),console.log("Reusing existing infrastructure for updates...");let h=(await n.getDistributionConfig(c.Id)).DistributionConfig?.Origins?.Items,v;if(h){let E=[];if(Array.isArray(h))E=h;else if(h.Origin)E=Array.isArray(h.Origin)?h.Origin:[h.Origin];else E=[h];for(let H of E){let V=(H.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){v=V[1];break}}}if(v)return console.log(`Using existing S3 bucket: ${v}`),{success:!0,stackName:`existing-${c.Id}`,bucket:v,distributionId:c.Id,distributionDomain:c.DomainName,domain:e,certificateArn:b,message:"Using existing CloudFront distribution",_existingInfrastructure:!0}}}}catch{}if(!g)try{if((await o.headBucket(m)).exists){console.log(`Found orphaned S3 bucket ${m}, cleaning up...`);try{let c=o.emptyBucket(m).then(()=>o.deleteBucket(m)),S=new Promise((I,h)=>setTimeout(()=>h(Error("Bucket cleanup timeout")),30000));await Promise.race([c,S]),console.log(`Deleted orphaned S3 bucket ${m}`)}catch(c){console.log(`Note: Could not clean up S3 bucket: ${c.message}`);let S=Date.now().toString(36);y=`${m}-${S}`,console.log(`Using alternative bucket name: ${y}`)}}}catch{}}let F=J({bucketName:y,domain:e,aliases:P?[e,P]:[e],certificateArn:b,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,passthroughUrls:t.passthroughUrls,singlePageApp:t.singlePageApp,dynamicApp:t.dynamicApp,computeOriginDomain:t.computeOriginDomain,computeOriginPort:t.computeOriginPort,computeOriginId:t.computeOriginId}),N=Object.entries(t.tags||{}).map(([o,n])=>({Key:o,Value:n}));if(N.push({Key:"ManagedBy",Value:"ts-cloud"}),N.push({Key:"Application",Value:t.siteName}),d)N.push({Key:"DnsProvider",Value:d.name});let O,D=!1;if(x){D=!0,console.log(`Updating CloudFormation stack: ${i}`);try{O=(await r.updateStack({stackName:i,templateBody:JSON.stringify(F),capabilities:["CAPABILITY_IAM"],tags:N})).StackId,console.log(`Update initiated, stack ID: ${O}`)}catch(o){if(o.message?.includes("No updates are to be performed")){let n=await r.describeStacks({stackName:i});O=n.Stacks[0].StackId;let g=n.Stacks[0]?.Outputs||[],p=(S)=>g.find((I)=>I.OutputKey===S)?.OutputValue,c=p("DistributionDomain");if(c)await q(d,e,c);return{success:!0,stackId:O,stackName:i,bucket:p("BucketName")||y,distributionId:p("DistributionId"),distributionDomain:c,domain:e,certificateArn:b,message:"Static site infrastructure is already up to date"}}else throw o}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${y}`),console.log(`Domain: ${e}`),console.log(`Certificate ARN: ${b}`),O=(await r.createStack({stackName:i,templateBody:JSON.stringify(F),capabilities:["CAPABILITY_IAM"],tags:N,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${O}`);console.log(`Waiting for stack to reach ${D?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,D?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(o){if(o.message?.includes("must be verified")||o.message?.includes("Access denied for operation")){console.log("CloudFront account verification required - checking for existing infrastructure...");try{let g=new U,p=await g.listDistributions();for(let c of p){let S=[];if(c.Aliases?.Items){if(Array.isArray(c.Aliases.Items))S=c.Aliases.Items;else if(typeof c.Aliases.Items==="object"){let I=c.Aliases.Items.CNAME;if(typeof I==="string")S=[I];else if(Array.isArray(I))S=I}}if(S.includes(e)){console.log(`Found existing CloudFront distribution ${c.Id} with alias ${e}`),console.log("Using existing infrastructure despite account verification requirement...");let h=(await g.getDistributionConfig(c.Id)).DistributionConfig?.Origins?.Items,v;if(h){let E=[];if(Array.isArray(h))E=h;else if(h.Origin)E=Array.isArray(h.Origin)?h.Origin:[h.Origin];else E=[h];for(let H of E){let V=(H.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){v=V[1];break}}}if(v){console.log(`Using existing S3 bucket: ${v}`);let E=c.DomainName;if(E)await q(d,e,E);return{success:!0,stackName:`existing-${c.Id}`,bucket:v,distributionId:c.Id,distributionDomain:c.DomainName,domain:e,certificateArn:b,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}}catch{}return console.log(`
28
+ ┌─────────────────────────────────────────────────────────────────────────────┐
29
+ │ AWS ACCOUNT VERIFICATION REQUIRED │
30
+ ├─────────────────────────────────────────────────────────────────────────────┤
31
+ │ Your AWS account must be verified before you can create CloudFront │
32
+ │ distributions. This is a one-time requirement for new AWS accounts. │
33
+ │ │
34
+ │ To verify your account: │
35
+ │ │
36
+ │ 1. Go to: https://console.aws.amazon.com/support/home#/ │
37
+ │ 2. Click "Create case" │
38
+ │ 3. Select "Service limit increase" │
39
+ │ 4. For Service: Select "CloudFront" │
40
+ │ 5. For Request: "Please verify my account for CloudFront access" │
41
+ │ 6. Submit the case │
42
+ │ │
43
+ │ Verification typically takes 1-2 business days. │
44
+ │ After verification, re-run: bunx bunpress deploy │
45
+ └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:O,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:O,stackName:i,bucket:y,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],C=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,f=C("DistributionDomain");if(f&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,f);else if(f&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:O,stackName:i,bucket:C("BucketName")||y,distributionId:C("DistributionId"),distributionDomain:f,domain:e,certificateArn:b,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let b of d.records){let k=b.name.replace(/\.$/,"");if(k===s||k==="")console.log(`Removing existing root A record (${b.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:b.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function le(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(b){console.log(`Note: Could not clean bucket: ${b.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-ddmjjstg.js"),a=await r({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(b,k,R)=>{e?.("upload",`${b}/${k}: ${R}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:b}=await import("./chunk-ddmjjstg.js");await b(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Q(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:m,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
46
+ const request = event.request;
47
+ var uri = request.uri;
48
+
49
+ // If URI ends with /, serve index.html
50
+ if (uri.endsWith('/')) {
51
+ request.uri = uri + 'index.html';
52
+ }
53
+ // If URI doesn't have an extension, append .html
54
+ else if (!uri.includes('.')) {
55
+ request.uri = uri + '.html';
56
+ }
57
+
58
+ return request;
59
+ }`}};let b={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(l&&e)b.Aliases=[l],b.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else b.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(a.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:b}},d.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},d.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},a.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},l&&m)a.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:m,Name:l,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},a.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:m,Name:l,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},d.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${l||s}`,Resources:a,Outputs:d}}async function X(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let u=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!u)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return G({siteName:t.siteName,region:t.region,domain:u,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",l="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let m=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new W(l),a=new M,d=new L("us-east-1"),b=new Y("us-east-1"),k=t.hostedZoneId,R=t.certificateArn;if(e&&!k){let u=await a.findHostedZoneForDomain(e);if(u)k=u.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:m,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!R&&k){let u=await d.findCertificateByDomain(e);if(u&&u.Status==="ISSUED")R=u.CertificateArn;else R=(await b.requestAndValidate({domainName:e,hostedZoneId:k,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let P=!1,x;try{let u=await r.describeStacks({stackName:i});if(u.Stacks.length>0){let C=u.Stacks[0],f=C.StackStatus;if(f==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),P=!1;else if(f==="DELETE_COMPLETE")P=!1;else P=!0,x=(C.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(u){if(u.message?.includes("does not exist")||u.code==="ValidationError")P=!1;else throw u}let A=x||m;if(!P){let u=new B(s),C=new U,f=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await C.listDistributions();for(let n of o){let g=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))g=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let p=n.Aliases.Items.CNAME;if(typeof p==="string")g=[p];else if(Array.isArray(p))g=p}}if(g.includes(e)){f=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let c=(await C.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,S;if(c){let I=[];if(Array.isArray(c))I=c;else if(c.Origin)I=Array.isArray(c.Origin)?c.Origin:[c.Origin];else I=[c];for(let h of I){let E=(h.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(E){S=E[1];break}}}if(S){let I=e.replace(/\./g,"-");if(!S.startsWith(I)&&!S.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${S}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${S}`),k&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"A",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"AAAA",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(h){console.log(`Note: Could not update Route53 records: ${h.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:S,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:R,message:"Using existing CloudFront distribution"}}}}}catch{}if(k)try{let n=(await a.listResourceRecordSets({HostedZoneId:k})).ResourceRecordSets||[];for(let g of n)if(g.Name===`${e}.`&&(g.Type==="A"||g.Type==="AAAA")){if(g.AliasTarget){console.log(`Found orphaned Route53 ${g.Type} record for ${e}, cleaning up...`);try{await a.deleteRecord({HostedZoneId:k,RecordSet:g}),console.log(`Deleted orphaned Route53 ${g.Type} record for ${e}`)}catch(p){console.log(`Note: Could not delete Route53 record: ${p.message}`)}}}}catch{}}if(!f)try{if((await u.headBucket(m)).exists){console.log(`Found orphaned S3 bucket ${m}, cleaning up...`);try{let n=u.emptyBucket(m).then(()=>u.deleteBucket(m)),g=new Promise((p,c)=>setTimeout(()=>c(Error("Bucket cleanup timeout")),30000));await Promise.race([n,g]),console.log(`Deleted orphaned S3 bucket ${m}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let g=Date.now().toString(36);A=`${m}-${g}`,console.log(`Using alternative bucket name: ${A}`)}}}catch{}}let y=Q({bucketName:A,domain:e,certificateArn:R,hostedZoneId:k,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),T=Object.entries(t.tags||{}).map(([u,C])=>({Key:u,Value:C}));T.push({Key:"ManagedBy",Value:"ts-cloud"}),T.push({Key:"Application",Value:t.siteName});let F,N=!1;if(P){N=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${A}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${R||"not specified"}`);try{F=(await r.updateStack({stackName:i,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:T})).StackId,console.log(`Update initiated, stack ID: ${F}`)}catch(u){if(u.message?.includes("No updates are to be performed")){let C=await r.describeStacks({stackName:i});F=C.Stacks[0].StackId;let f=C.Stacks[0]?.Outputs||[],o=(n)=>f.find((g)=>g.OutputKey===n)?.OutputValue;return{success:!0,stackId:F,stackName:i,bucket:o("BucketName")||A,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:R,message:"Static site infrastructure is already up to date"}}else throw u}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${A}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${R||"not specified"}`),console.log("Stack does not exist, creating..."),F=(await r.createStack({stackName:i,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:T,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${F}`);console.log(`Waiting for stack to reach ${N?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,N?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(u){if(u.message?.includes("must be verified")||u.message?.includes("Access denied for operation")||u.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let C=new U;if(e)try{let f=await C.listDistributions();for(let o of f){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let g=o.Aliases.Items.CNAME;if(typeof g==="string")n=[g];else if(Array.isArray(g))n=g}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let p=(await C.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,c;if(p){let S=[];if(Array.isArray(p))S=p;else if(p.Origin)S=Array.isArray(p.Origin)?p.Origin:[p.Origin];else S=[p];for(let I of S){let v=(I.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(v){c=v[1];break}}}if(c)return console.log(`Using existing S3 bucket: ${c}`),{success:!0,stackName:`existing-${o.Id}`,bucket:c,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:R,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let f=new B(s);if((await f.headBucket(A)).exists)console.log(`Using existing S3 bucket: ${A}`);else console.log(`Creating S3 bucket: ${A}...`),await f.createBucket(A);await f.putBucketWebsite(A,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await f.putPublicAccessBlock(A,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${A} configured`);let n=`OAC-${A}`;console.log(`Creating Origin Access Control: ${n}...`);let g=await C.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${g.Id} ready`),console.log("Creating CloudFront distribution...");let p=await C.createDistributionForS3({bucketName:A,bucketRegion:s,originAccessControlId:g.Id,aliases:e?[e]:[],certificateArn:R,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||A}`});console.log(`CloudFront distribution ${p.Id} created`),console.log("Updating S3 bucket policy...");let c=U.getS3BucketPolicyForCloudFront(A,p.ARN);if(await f.putBucketPolicy(A,c),console.log("S3 bucket policy updated"),e&&k){console.log(`Creating Route53 records for ${e}...`);try{await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"A",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:p.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"AAAA",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:p.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(S){console.log(`Note: Could not create Route53 records: ${S.message}`)}}return{success:!0,stackName:`direct-${p.Id}`,bucket:A,distributionId:p.Id,distributionDomain:p.DomainName,domain:e,certificateArn:R,message:"Static site infrastructure created via direct API calls"}}catch(f){return console.log(`Direct API creation failed: ${f.message}`),{success:!1,stackId:F,stackName:i,bucket:A,message:`Deployment failed: ${f.message}`}}}return{success:!1,stackId:F,stackName:i,bucket:A,message:`Stack deployment failed: ${u.message}`}}let D=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],w=(u)=>D.find((C)=>C.OutputKey===u)?.OutputValue;return{success:!0,stackId:F,stackName:i,bucket:w("BucketName")||A,distributionId:w("DistributionId"),distributionDomain:w("DistributionDomain"),domain:e,certificateArn:R,message:"Static site infrastructure deployed successfully"}}async function ee(t){let{sourceDir:s,bucket:l,region:e,cacheControl:m="max-age=31536000, public",onProgress:i}=t,r=new B(e),{readdir:a}=await import("node:fs/promises"),{join:d,relative:b}=await import("node:path"),{createHash:k}=await import("node:crypto");async function R(D){let w=[],u=await a(D,{withFileTypes:!0});for(let C of u){let f=d(D,C.name);if(C.isDirectory())w.push(...await R(f));else w.push(f)}return w}function P(D){let w=D.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[w||""]||"application/octet-stream"}function x(D){return k("md5").update(D).digest("hex")}async function A(){let D=new Map,w;do{let u=await r.listObjects({bucket:l,maxKeys:1000,continuationToken:w});for(let C of u.objects){let f=C.ETag?.replace(/"/g,"")||"";D.set(C.Key,f)}w=u.nextContinuationToken}while(w);return D}let y=await R(s),T=[],F=0,N=0,O=await A();for(let D of y){let w=b(s,D),u=P(D),C=D.endsWith(".html")?"max-age=3600, public":m;try{let f=Buffer.from(await Bun.file(D).arrayBuffer()),o=x(f),n=O.get(w);if(n&&n===o){N++,i?.(F+N,y.length,w);continue}await r.putObject({bucket:l,key:w,body:f,contentType:u,cacheControl:C}),F++,i?.(F+N,y.length,w)}catch(f){T.push(`Failed to upload ${w}: ${f.message}`)}}return{uploaded:F,skipped:N,errors:T}}async function te(t){return{invalidationId:(await new U().invalidateAll(t)).Id}}async function Ae(t,s="us-east-1"){let l=new W(s);try{let r=((await l.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((a)=>a.OutputKey==="BucketName")?.OutputValue;if(r)await new B(s).emptyBucket(r)}catch{}await l.deleteStack(t);let e=await l.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function Ce(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await X(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(d){console.log(`Note: Could not clean bucket: ${d.message}`)}}e?.("upload","Uploading files to S3...");let r=await ee({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(d,b,k)=>{e?.("upload",`${d}/${b}: ${k}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await te(i.distributionId);e?.("complete","Deployment complete!");let a=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:a}}
60
+ export{Q as p,X as q,ee as r,te as s,Ae as t,Ce as u,le as v};
@@ -0,0 +1 @@
1
+ import{$b as A,$c as Ba,Ac as aa,Bb as a,Bc as ba,Cb as b,Cc as ca,Db as c,Dc as da,Eb as d,Ec as ea,Fb as e,Fc as fa,Gb as f,Gc as ga,Hb as g,Hc as ha,Ib as h,Ic as ia,Jb as i,Jc as ja,Kb as j,Kc as ka,Lb as k,Lc as la,Mb as l,Mc as ma,Nb as m,Nc as na,Ob as n,Oc as oa,Pb as o,Pc as pa,Qb as p,Qc as qa,Rb as q,Rc as ra,Sb as r,Sc as sa,Tb as s,Tc as ta,Ub as t,Uc as ua,Vb as u,Vc as va,Wb as v,Wc as wa,Xb as w,Xc as xa,Yb as x,Yc as ya,Zb as y,Zc as za,_b as z,_c as Aa,ac as B,bc as C,cc as D,cd as Ca,dc as E,dd as Da,ec as F,fc as G,gc as H,hc as I,ic as J,jc as K,kc as L,lc as M,mc as N,nc as O,oc as P,pc as Q,qc as R,rc as S,sc as T,tc as U,uc as V,vc as W,wc as X,xc as Y,yc as Z,zc as _}from"./chunk-dvkj4k6h.js";import"./chunk-936vp7dx.js";import"./chunk-jnsbzqzz.js";import"./chunk-anm3ae6z.js";import"./chunk-b2ymh8k0.js";export{Z as AnomalyConfigStore,za as AwsSpendTransport,Aa as ComputeSpendTransport,x as CounterTracker,u as DEFAULT_METER_MAPPINGS,l as DEFAULT_PRICE_BOOK,B as DEFAULT_THRESHOLDS,_ as DETECTABLE_SIGNALS,c as ENFORCEMENT_ACTIONS,K as ENFORCEMENT_DESCRIPTIONS,d as ENFORCEMENT_SEVERITY,ea as FOCUS_VERSION,b as METERS,a as METER_KEYS,e as MICRO_CENTS,G as MIN_PROJECTION_CONFIDENCE,pa as RecordingSpendTransport,X as SENSITIVITY_THRESHOLDS,xa as SPEND_CYCLE_SECONDS,ka as SPEND_GATE_SETTING,ua as SPEND_LEASE_SETTING,ba as SignalSource,ma as SpendCapError,la as SpendGate,va as SpendLoopLease,ta as SpendNotificationRouter,wa as SpendRunner,ia as SpendService,C as SpendStore,qa as URGENT_SPEND_EVENTS,L as USER_VISIBLE_ACTIONS,z as aggregateDeltas,W as anomalyOptionsForSignal,na as assertSpendAllows,q as budgetWindow,Ba as compositeSpendTransport,oa as createEnforcementHandlers,U as detectAnomalies,V as detectLatestAnomaly,I as evaluateBudget,T as ewma,v as findMapping,g as findPriceEntry,ra as formatCents,F as formatTimeToExhaustion,H as governingLimitCents,Ca as handleSpendRequest,s as hourBucket,t as hourBucketsBetween,P as isOperationAllowed,m as isValidTimeZone,da as lookbackHoursForSignal,Q as median,R as medianAbsoluteDeviation,J as mergeDecisions,k as mergePriceBooks,y as meterTelemetry,ca as optionsForSignal,E as percentOfLimit,M as planEnforcement,r as previousBudgetWindow,h as priceUsage,i as priceUsageLines,D as projectSpend,S as robustZScore,j as roundCents,Y as routeMatches,N as runEnforcement,A as scopeKey,aa as signalDefinition,sa as spendNotificationText,Da as spendOpenApiPaths,ya as startSpendLoop,ha as streamFocusJsonl,O as strongestActiveAction,f as tieredMicroCents,ga as toFocusJsonl,fa as toFocusRecords,w as usageDeltaKey,p as utcInstantOfLocal,ja as zeroFill,o as zoneOffsetMs,n as zonedParts};
@@ -0,0 +1 @@
1
+ import{kg as a,lg as b}from"./chunk-svyd4v6c.js";import"./chunk-b35989e3.js";import"./chunk-d6zzgvtn.js";import"./chunk-ey9fagrr.js";import"./chunk-b2ymh8k0.js";export{a as EmailClient,b as email};
@@ -0,0 +1,2 @@
1
+ import{bh as u}from"./chunk-ey9fagrr.js";class d{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new u}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[n,g]of Object.entries(e.tags))t[`Tag.${a}.Key`]=n,t[`Tag.${a}.Value`]=g,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{Attributes:t.Attributes||t.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
2
+ export{d as Gd};
@@ -0,0 +1,34 @@
1
+ import{mg as P}from"./chunk-b35989e3.js";import{og as A}from"./chunk-d6zzgvtn.js";import{bh as d}from"./chunk-ey9fagrr.js";import{mp as y}from"./chunk-b2ymh8k0.js";function I(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,c)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))s.push(`${a}.member.${c+1}.${u}=${encodeURIComponent(String(l))}`);else s.push(`${a}.member.${c+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,c]of Object.entries(i))if(c!==void 0&&c!==null)s.push(`${a}.${n}=${encodeURIComponent(String(c))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function o(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let n=[],c=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),u;while((u=c.exec(i[1]))!==null)n.push(u[1]);return n}class g{client;region;constructor(e="us-east-1",t){this.client=new d(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=I(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return o(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",n=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return o(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return o(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return o(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return o(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return o(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return o(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return o(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return o(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=o(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),n=r(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=o(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=o(e,"EvaluationResults","member").map((n)=>{let u=o(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:r(l,"SourcePolicyId"),SourcePolicyType:r(l,"SourcePolicyType")}));return{EvalActionName:r(n,"EvalActionName")||"",EvalResourceName:r(n,"EvalResourceName"),EvalDecision:r(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}class p{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new d(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,c)=>{s[`Destinations.member.${c+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class h{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new p(this.region),this.s3=new A(this.region),this.iam=new g(this.region),this.route53=new P(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-5rv31chh.js"),a=new s,i=(m,S)=>{let f={Action:m,Version:"2010-05-08",...S};return Object.entries(f).map(([b,T])=>`${encodeURIComponent(b)}=${encodeURIComponent(T)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},c=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:c,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let R=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:R,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=y("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
+ `,i+=`To: ${s.join(", ")}\r
3
+ `,e.cc){let n=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${n.join(", ")}\r
4
+ `}if(i+=`Subject: ${e.subject}\r
5
+ `,i+=`MIME-Version: 1.0\r
6
+ `,i+=`Content-Type: multipart/mixed; boundary="${a}"\r
7
+ `,i+=`\r
8
+ `,e.text||e.html)if(i+=`--${a}\r
9
+ `,e.html&&e.text){let n=`----=_Alt_${Date.now()}`;i+=`Content-Type: multipart/alternative; boundary="${n}"\r
10
+ `,i+=`\r
11
+ `,i+=`--${n}\r
12
+ `,i+=`Content-Type: text/plain; charset="UTF-8"\r
13
+ `,i+=`\r
14
+ `,i+=`${e.text}\r
15
+ `,i+=`--${n}\r
16
+ `,i+=`Content-Type: text/html; charset="UTF-8"\r
17
+ `,i+=`\r
18
+ `,i+=`${e.html}\r
19
+ `,i+=`--${n}--\r
20
+ `}else if(e.html)i+=`Content-Type: text/html; charset="UTF-8"\r
21
+ `,i+=`\r
22
+ `,i+=`${e.html}\r
23
+ `;else i+=`Content-Type: text/plain; charset="UTF-8"\r
24
+ `,i+=`\r
25
+ `,i+=`${e.text}\r
26
+ `;if(e.attachments)for(let n of e.attachments)i+=`--${a}\r
27
+ `,i+=`Content-Type: ${n.contentType||"application/octet-stream"}; name="${n.filename}"\r
28
+ `,i+=`Content-Transfer-Encoding: base64\r
29
+ `,i+=`Content-Disposition: attachment; filename="${n.filename}"\r
30
+ `,i+=`\r
31
+ `,i+=`${n.content}\r
32
+ `;return i+=`--${a}--\r
33
+ `,i}}var M=new h;
34
+ export{g as ig,p as jg,h as kg,M as lg};
@@ -0,0 +1 @@
1
+ import{Fg as a}from"./chunk-pkgkfe6s.js";import"./chunk-kybdb0ws.js";import"./chunk-1v6bt68w.js";import"./chunk-ey9fagrr.js";import"./chunk-anm3ae6z.js";import"./chunk-b2ymh8k0.js";export{a as buildAndPushServerlessImage};
@@ -0,0 +1 @@
1
+ import{fd as a}from"./chunk-b0hj9m5e.js";import"./chunk-ey9fagrr.js";import"./chunk-b2ymh8k0.js";export{a as RDSClient};
@@ -0,0 +1 @@
1
+ import{og as a}from"./chunk-d6zzgvtn.js";import"./chunk-ey9fagrr.js";import"./chunk-b2ymh8k0.js";export{a as S3Client};
@@ -0,0 +1 @@
1
+ import{jf as a,kf as b,lf as c,mf as d,nf as e,of as f,pf as g,qf as h,rf as i,sf as j}from"./chunk-mn6j22zn.js";import"./chunk-anm3ae6z.js";import"./chunk-b2ymh8k0.js";export{a as MANAGEMENT_DASHBOARD_SITE,j as buildManagementDashboardArtifact,b as dashboardCredentialsFile,h as ensureManagementDashboard,d as liveStageDir,i as managementDashboardSiteNames,c as resolveDashboardAuth,e as resolveDashboardVersion,g as resolveUiSource,f as stageLiveDashboardRoot};
@@ -0,0 +1 @@
1
+ import{vd as a}from"./chunk-6zjy949y.js";import"./chunk-ey9fagrr.js";import"./chunk-b2ymh8k0.js";export{a as CloudFrontClient};
@@ -0,0 +1 @@
1
+ import{Gd as a}from"./chunk-sbejksrh.js";import"./chunk-ey9fagrr.js";import"./chunk-b2ymh8k0.js";export{a as SQSClient};