@stacksjs/ts-cloud 0.12.14 → 0.12.15

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 (126) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-4w80w3sm.js +1 -0
  3. package/dist/bin/{chunk-ngav845g.js → chunk-5tsxt28g.js} +2 -2
  4. package/dist/bin/{chunk-2paqksap.js → chunk-77qpn2m8.js} +3 -3
  5. package/dist/bin/{chunk-dbmk60r7.js → chunk-7xvm2ygt.js} +2 -2
  6. package/dist/bin/{chunk-bj5nq0kn.js → chunk-8tbj9h2a.js} +26 -26
  7. package/dist/bin/chunk-971tfc6m.js +1 -0
  8. package/dist/bin/{chunk-n6qqa2fr.js → chunk-9e22a51n.js} +31 -31
  9. package/dist/bin/{chunk-z2ez8wn9.js → chunk-9k60q9qz.js} +3 -3
  10. package/dist/bin/{chunk-1rcsm0px.js → chunk-dpw8x3sr.js} +1 -1
  11. package/dist/bin/{chunk-pega3x2x.js → chunk-ejqhbj1h.js} +1 -1
  12. package/dist/bin/{chunk-wr6a423y.js → chunk-gd4w6bht.js} +1 -1
  13. package/dist/bin/chunk-h785hw6a.js +1 -0
  14. package/dist/bin/chunk-jyggrdh2.js +1 -0
  15. package/dist/bin/{chunk-9q8zjavc.js → chunk-kc2e193t.js} +40 -40
  16. package/dist/bin/{chunk-16rs9egs.js → chunk-n7eq4t9a.js} +3 -3
  17. package/dist/bin/{chunk-6vay4ggv.js → chunk-n8cwx54p.js} +5 -5
  18. package/dist/bin/{chunk-d7r6mhyv.js → chunk-ng0949x3.js} +2 -2
  19. package/dist/bin/{chunk-f8mbjwme.js → chunk-pcyywgx7.js} +1 -1
  20. package/dist/bin/{chunk-1x7mm26k.js → chunk-q524s7cx.js} +1 -1
  21. package/dist/bin/{chunk-vwyq2s2k.js → chunk-q9gpw6wv.js} +1 -1
  22. package/dist/bin/{chunk-w637s5q0.js → chunk-r1vtnn8w.js} +2 -2
  23. package/dist/bin/{chunk-nrnq9adz.js → chunk-r1w08y38.js} +1 -1
  24. package/dist/bin/{chunk-1wvrtg42.js → chunk-raj6j2j5.js} +1 -1
  25. package/dist/bin/{chunk-3gwmejhk.js → chunk-s1j941z1.js} +1 -1
  26. package/dist/bin/{chunk-fnr6k11h.js → chunk-sdwr2tnp.js} +1 -1
  27. package/dist/bin/{chunk-y7ece16e.js → chunk-swete552.js} +5 -5
  28. package/dist/bin/{chunk-yn34zgr2.js → chunk-v78r5tx0.js} +1 -1
  29. package/dist/bin/chunk-v7f4c62s.js +1 -0
  30. package/dist/bin/{chunk-4201mvaj.js → chunk-vesvsvdy.js} +1 -1
  31. package/dist/bin/{chunk-yt8rgkqt.js → chunk-w5hzt11d.js} +2 -2
  32. package/dist/bin/{chunk-ydpnsp4x.js → chunk-x42gb7pq.js} +1 -1
  33. package/dist/bin/{chunk-rpg5k3wt.js → chunk-yx1qgp1q.js} +1 -1
  34. package/dist/bin/{chunk-92nng29y.js → chunk-zzsdhhmb.js} +1 -1
  35. package/dist/bin/cli.js +130 -130
  36. package/dist/bin/dashboard-server.js +1 -1
  37. package/dist/{chunk-djd9xgkz.js → chunk-2knc1zyy.js} +74 -74
  38. package/dist/{chunk-7kwha0fw.js → chunk-678rwkz8.js} +60 -60
  39. package/dist/{chunk-pkan6evc.js → chunk-6t9tjvpy.js} +2 -2
  40. package/dist/{chunk-9mhcjht7.js → chunk-6znnde1s.js} +3 -3
  41. package/dist/{chunk-5g1hsrab.js → chunk-83p688yv.js} +2 -2
  42. package/dist/{chunk-5ww7kc5z.js → chunk-88nxsyry.js} +6 -6
  43. package/dist/{chunk-6j8f4ahv.js → chunk-a6k322xc.js} +23 -23
  44. package/dist/chunk-atny1wp9.js +1 -0
  45. package/dist/{chunk-thpce63q.js → chunk-cy6qh4ea.js} +2 -2
  46. package/dist/{chunk-bqaqkmtr.js → chunk-g9mnmddy.js} +1 -1
  47. package/dist/{chunk-ttq6dvft.js → chunk-gd9g0v9w.js} +3 -3
  48. package/dist/chunk-hn2v0b0d.js +1 -0
  49. package/dist/{chunk-e0919h5g.js → chunk-hnkw6pde.js} +2 -2
  50. package/dist/{chunk-xxbvjq8g.js → chunk-jvqcw0b4.js} +39 -39
  51. package/dist/{chunk-e7ds04wb.js → chunk-rbem58rx.js} +1 -1
  52. package/dist/chunk-v46b25w9.js +1 -0
  53. package/dist/{chunk-7hy9p6xr.js → chunk-w495x89g.js} +1 -1
  54. package/dist/{chunk-vva43vnp.js → chunk-x07tpsv0.js} +4 -4
  55. package/dist/{chunk-3kapcdpn.js → chunk-yq3pdbz7.js} +1 -1
  56. package/dist/deploy/index.js +1 -1
  57. package/dist/dns/index.js +1 -1
  58. package/dist/drivers/index.js +1 -1
  59. package/dist/index.d.ts +1 -1
  60. package/dist/index.js +47 -47
  61. package/dist/operations/index.js +1 -1
  62. package/dist/protection/index.js +1 -1
  63. package/dist/spend/index.js +1 -1
  64. package/dist/ui/404.html +1 -1
  65. package/dist/ui/accept-invitation.html +1 -1
  66. package/dist/ui/access-denied.html +1 -1
  67. package/dist/ui/account/automation.html +6 -6
  68. package/dist/ui/account/security.html +2 -2
  69. package/dist/ui/applications/compose.html +5 -5
  70. package/dist/ui/applications/new.html +2 -2
  71. package/dist/ui/data/backups.html +6 -6
  72. package/dist/ui/data/services.html +6 -6
  73. package/dist/ui/data/volumes.html +6 -6
  74. package/dist/ui/index.html +6 -6
  75. package/dist/ui/infrastructure/topology.html +6 -6
  76. package/dist/ui/integrations.html +2 -2
  77. package/dist/ui/operations/alerts.html +6 -6
  78. package/dist/ui/operations/configuration.html +6 -6
  79. package/dist/ui/operations/jobs.html +6 -6
  80. package/dist/ui/operations/maintenance.html +6 -6
  81. package/dist/ui/operations/observability.html +6 -6
  82. package/dist/ui/operations/previews.html +6 -6
  83. package/dist/ui/operations/queue.html +6 -6
  84. package/dist/ui/operations/regions.html +6 -6
  85. package/dist/ui/operations/releases.html +6 -6
  86. package/dist/ui/operations/spend.html +6 -6
  87. package/dist/ui/operations/workloads.html +5 -5
  88. package/dist/ui/security.html +2 -2
  89. package/dist/ui/server/actions.html +5 -5
  90. package/dist/ui/server/activity.html +1 -1
  91. package/dist/ui/server/capacity.html +5 -5
  92. package/dist/ui/server/database.html +6 -6
  93. package/dist/ui/server/deployments.html +5 -5
  94. package/dist/ui/server/diagnostics.html +2 -2
  95. package/dist/ui/server/firewall.html +6 -6
  96. package/dist/ui/server/fleet.html +6 -6
  97. package/dist/ui/server/logs.html +6 -6
  98. package/dist/ui/server/metrics.html +5 -5
  99. package/dist/ui/server/security.html +2 -2
  100. package/dist/ui/server/services.html +2 -2
  101. package/dist/ui/server/sites.html +6 -6
  102. package/dist/ui/server/ssh-keys.html +5 -5
  103. package/dist/ui/server/team.html +6 -6
  104. package/dist/ui/server/terminal.html +2 -2
  105. package/dist/ui/serverless/alarms.html +6 -6
  106. package/dist/ui/serverless/assets.html +2 -2
  107. package/dist/ui/serverless/cost.html +2 -2
  108. package/dist/ui/serverless/data.html +6 -6
  109. package/dist/ui/serverless/deployments.html +2 -2
  110. package/dist/ui/serverless/firewall.html +2 -2
  111. package/dist/ui/serverless/functions.html +6 -6
  112. package/dist/ui/serverless/logs.html +5 -5
  113. package/dist/ui/serverless/metrics.html +2 -2
  114. package/dist/ui/serverless/queues.html +6 -6
  115. package/dist/ui/serverless/secrets.html +6 -6
  116. package/dist/ui/serverless/traces.html +6 -6
  117. package/dist/ui/serverless.html +5 -5
  118. package/package.json +3 -3
  119. package/dist/bin/chunk-61ysn56t.js +0 -1
  120. package/dist/bin/chunk-f1ke4ygp.js +0 -1
  121. package/dist/bin/chunk-mzfct5en.js +0 -1
  122. package/dist/bin/chunk-p36ns96s.js +0 -1
  123. package/dist/bin/chunk-q5aj280b.js +0 -1
  124. package/dist/chunk-5qqb671d.js +0 -1
  125. package/dist/chunk-vpy3zjqv.js +0 -1
  126. package/dist/chunk-wrnhbb13.js +0 -1
@@ -1,16 +1,16 @@
1
- import{createRequire as qa}from"node:module";import{isAbsolute as $t,join as gt,relative as tr}from"node:path";import{existsSync as Ke,readdirSync as or}from"node:fs";import{join as ve}from"node:path";import{createHash as br}from"node:crypto";import{copyFileSync as Ar,existsSync as Et,readdirSync as Cr,readFileSync as nt,statSync as Tr,writeFileSync as it}from"node:fs";import{basename as vr,dirname as ia,extname as sa,join as He}from"node:path";import{existsSync as Ia,readFileSync as Wt}from"node:fs";import{homedir as Ra}from"node:os";import{join as Na}from"node:path";import{createHash as ka}from"node:crypto";import{existsSync as ot,mkdirSync as Tn,readdirSync as ua,readFileSync as da,unlinkSync as qe,writeFileSync as vn}from"node:fs";import{join as It}from"node:path";import{createHash as Vt}from"node:crypto";import{createReadStream as wn,readdirSync as En,statSync as ht}from"node:fs";import{join as Pn,relative as In}from"node:path";import{deflateRawSync as Bn}from"node:zlib";import{execSync as Fn}from"node:child_process";import{createHash as Vn}from"node:crypto";import{cpSync as jn,mkdtempSync as Kn,rmSync as Hn,writeFileSync as qn}from"node:fs";import{tmpdir as zn}from"node:os";import{dirname as Qn,isAbsolute as Jn,join as Le,resolve as Yn}from"node:path";import{fileURLToPath as Zn}from"node:url";import{execFileSync as bt}from"node:child_process";import{mkdtempSync as Ma,readFileSync as At,rmSync as xa}from"node:fs";import{tmpdir as Oa}from"node:os";import{dirname as ai,join as Pe}from"node:path";import{fileURLToPath as ri}from"node:url";import{AsyncLocalStorage as ii}from"node:async_hooks";import{createHash as si}from"node:crypto";import{readFileSync as Si}from"node:fs";import{dirname as bi,join as Ua}from"node:path";import{fileURLToPath as Ci}from"node:url";import{execFileSync as lt}from"node:child_process";import{existsSync as vi,mkdirSync as wi,mkdtempSync as Ei,readdirSync as Pi,readFileSync as Ii,rmSync as Ri,statSync as Fa,writeFileSync as Ni}from"node:fs";import{tmpdir as Di}from"node:os";import{join as xe,relative as ki}from"node:path";import{execSync as $i}from"node:child_process";import{createHash as Li}from"node:crypto";import{readdirSync as Mi,readFileSync as xi,statSync as ja}from"node:fs";import{join as Oi,relative as Ka,resolve as na}from"node:path";var za=Object.defineProperty,Qa=(a)=>a;function Ja(a,n){this[a]=Qa.bind(null,n)}var _e=(a,n)=>{for(var i in n)za(a,i,{get:n[i],enumerable:!0,configurable:!0,set:Ja.bind(n,i)})},Ya=(a,n,i)=>()=>{if(a)try{n=a(a=0)}catch(s){i=[s]}if(i)throw i[0];return n},Za=qa(import.meta.url);function Sp(a){let n=typeof a==="string"?new URL(a):a,{hostname:i,pathname:s}=n;if(i.endsWith(".on.aws")){let h=i.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(h)return{service:"lambda",region:h[1]};return{service:"",region:""}}if(i.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(i.endsWith(".backblazeb2.com")){let h=i.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(h)return{service:"s3",region:h[1]};return{service:"",region:""}}let c=i.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!c)return{service:"",region:""};let l=c[1],u=c[2]||"";if(u==="us-gov")u="us-gov-west-1";else if(u==="s3"||u==="s3-accelerate")u="us-east-1",l="s3";else if(l==="iot")if(i.startsWith("iot."))l="execute-api";else if(i.startsWith("data.jobs.iot."))l="iot-jobs-data";else l=s==="/mqtt"?"iotdevicegateway":"iotdata";else if(l==="autoscaling");else if(!u&&l.startsWith("s3-"))u=l.slice(3).replace(/^fips-|^external-1/,""),l="s3";else if(l.endsWith("-fips"))l=l.slice(0,-5);else if(u&&/-\d$/.test(l)&&!/-\d$/.test(u))[l,u]=[u,l];return l=Ca[l]||l,{service:l,region:u||"us-east-1"}}function x(a){let{method:n,url:i,body:s="",accessKeyId:c,secretAccessKey:l,sessionToken:u,signQuery:h=!1,expiresIn:y=86400,datetime:f}=a,S=new URL(i),b=S.hostname,C=Sp(S),T=a.service||C.service,v=a.region||C.region;if(!T)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!v)throw Error("Could not detect region from URL. Please provide region explicitly.");let w=f||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),R=w.substring(0,8),k=[R,v,T,"aws4_request"].join("/"),W="AWS4-HMAC-SHA256";if(h)return Xa({urlObj:S,method:n,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:T,region:v,timestamp:w,date:R,credentialScope:k,algorithm:W,expiresIn:y,cache:a.cache});let P=S.pathname||"/",V=ft(S.searchParams),B={host:b,"x-amz-date":w,...a.headers};if(u)B["x-amz-security-token"]=u;let j=Object.keys(B).some((Ie)=>Ie.toLowerCase()==="content-type");if(s&&!j)B["content-type"]="application/x-amz-json-1.0";if(T==="s3"&&!B["x-amz-content-sha256"])B["x-amz-content-sha256"]=Je(s);let Z=ga(B),K=ha(B),ee=B["x-amz-content-sha256"]||Je(s),te=[n,St(P),V,Z,K,ee].join(`
2
- `),ie=Je(te),me=[W,w,k,ie].join(`
3
- `),ce=a.cache??ke,ue=fa(l,R,v,T,me,ce),se=[`${W} Credential=${c}/${k}`,`SignedHeaders=${K}`,`Signature=${ue}`].join(", ");return B.authorization=se,{url:i,method:n,headers:B,body:s||void 0}}async function Cp(a){let{method:n,url:i,body:s="",accessKeyId:c,secretAccessKey:l,sessionToken:u,signQuery:h=!1,expiresIn:y=86400,datetime:f}=a,S=new URL(i),b=S.hostname,C=Sp(S),T=a.service||C.service,v=a.region||C.region;if(!T)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!v)throw Error("Could not detect region from URL. Please provide region explicitly.");let w=f||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),R=w.substring(0,8),k=[R,v,T,"aws4_request"].join("/"),W="AWS4-HMAC-SHA256";if(h)return er({urlObj:S,method:n,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:T,region:v,timestamp:w,date:R,credentialScope:k,algorithm:W,expiresIn:y,cache:a.cache});let P=S.pathname||"/",V=ft(S.searchParams),B={host:b,"x-amz-date":w,...a.headers};if(u)B["x-amz-security-token"]=u;let j=Object.keys(B).some((We)=>We.toLowerCase()==="content-type");if(s&&!j)B["content-type"]="application/x-amz-json-1.0";let Z=await dt(s);if(T==="s3"&&!B["x-amz-content-sha256"])B["x-amz-content-sha256"]=Z;let K=ga(B),ee=ha(B),te=B["x-amz-content-sha256"]||Z,ie=[n,St(P),V,K,ee,te].join(`
4
- `),me=await dt(ie),ce=[W,w,k,me].join(`
5
- `),ue=a.cache??ke,se=await Sa(l,R,v,T,ce,ue),Ie=[`${W} Credential=${c}/${k}`,`SignedHeaders=${ee}`,`Signature=${se}`].join(", ");return B.authorization=Ie,{url:i,method:n,headers:B,body:s||void 0}}function Xa(a){let{urlObj:n,method:i,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:h,region:y,timestamp:f,date:S,credentialScope:b,algorithm:C,expiresIn:T,cache:v}=a,w=new URL(n.toString());w.searchParams.set("X-Amz-Algorithm",C),w.searchParams.set("X-Amz-Credential",`${c}/${b}`),w.searchParams.set("X-Amz-Date",f),w.searchParams.set("X-Amz-Expires",String(T));let R=h==="s3"?"UNSIGNED-PAYLOAD":Je(s);if(h==="s3")w.searchParams.set("X-Amz-Content-Sha256",R);let k="host";if(w.searchParams.set("X-Amz-SignedHeaders",k),u)w.searchParams.set("X-Amz-Security-Token",u);let W=St(w.pathname||"/"),P=`host:${w.hostname}
1
+ import{createRequire as qa}from"node:module";import{isAbsolute as $t,join as gt,relative as tr}from"node:path";import{existsSync as je,readdirSync as or}from"node:fs";import{join as ve}from"node:path";import{createHash as br}from"node:crypto";import{copyFileSync as Ar,existsSync as Et,readdirSync as Cr,readFileSync as rt,statSync as Tr,writeFileSync as nt}from"node:fs";import{basename as vr,dirname as ia,extname as sa,join as Ke}from"node:path";import{existsSync as Ia,readFileSync as Wt}from"node:fs";import{homedir as Ra}from"node:os";import{join as Na}from"node:path";import{createHash as ka}from"node:crypto";import{existsSync as st,mkdirSync as Tn,readdirSync as ua,readFileSync as da,unlinkSync as qe,writeFileSync as vn}from"node:fs";import{join as It}from"node:path";import{createHash as Vt}from"node:crypto";import{createReadStream as wn,readdirSync as En,statSync as ht}from"node:fs";import{join as Pn,relative as In}from"node:path";import{deflateRawSync as Bn}from"node:zlib";import{execSync as Fn}from"node:child_process";import{createHash as Vn}from"node:crypto";import{cpSync as jn,mkdtempSync as Kn,rmSync as Hn,writeFileSync as qn}from"node:fs";import{tmpdir as zn}from"node:os";import{dirname as Qn,isAbsolute as Jn,join as Le,resolve as Yn}from"node:path";import{fileURLToPath as Zn}from"node:url";import{execFileSync as bt}from"node:child_process";import{mkdtempSync as Ma,readFileSync as At,rmSync as xa}from"node:fs";import{tmpdir as Oa}from"node:os";import{dirname as ai,join as Pe}from"node:path";import{fileURLToPath as ri}from"node:url";import{AsyncLocalStorage as ii}from"node:async_hooks";import{createHash as si}from"node:crypto";import{readFileSync as Si}from"node:fs";import{dirname as bi,join as Ua}from"node:path";import{fileURLToPath as Ci}from"node:url";import{execFileSync as ot}from"node:child_process";import{existsSync as vi,mkdirSync as wi,mkdtempSync as Ei,readdirSync as Pi,readFileSync as Ii,rmSync as Ri,statSync as Fa,writeFileSync as Ni}from"node:fs";import{tmpdir as Di}from"node:os";import{join as Me,relative as ki}from"node:path";import{execSync as $i}from"node:child_process";import{createHash as Li}from"node:crypto";import{readdirSync as Mi,readFileSync as xi,statSync as ja}from"node:fs";import{join as Oi,relative as Ka,resolve as na}from"node:path";var za=Object.defineProperty,Qa=(a)=>a;function Ja(a,n){this[a]=Qa.bind(null,n)}var Be=(a,n)=>{for(var i in n)za(a,i,{get:n[i],enumerable:!0,configurable:!0,set:Ja.bind(n,i)})},Ya=(a,n,i)=>()=>{if(a)try{n=a(a=0)}catch(s){i=[s]}if(i)throw i[0];return n},Za=qa(import.meta.url);function Sp(a){let n=typeof a==="string"?new URL(a):a,{hostname:i,pathname:s}=n;if(i.endsWith(".on.aws")){let h=i.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(h)return{service:"lambda",region:h[1]};return{service:"",region:""}}if(i.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(i.endsWith(".backblazeb2.com")){let h=i.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(h)return{service:"s3",region:h[1]};return{service:"",region:""}}let c=i.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!c)return{service:"",region:""};let l=c[1],u=c[2]||"";if(u==="us-gov")u="us-gov-west-1";else if(u==="s3"||u==="s3-accelerate")u="us-east-1",l="s3";else if(l==="iot")if(i.startsWith("iot."))l="execute-api";else if(i.startsWith("data.jobs.iot."))l="iot-jobs-data";else l=s==="/mqtt"?"iotdevicegateway":"iotdata";else if(l==="autoscaling");else if(!u&&l.startsWith("s3-"))u=l.slice(3).replace(/^fips-|^external-1/,""),l="s3";else if(l.endsWith("-fips"))l=l.slice(0,-5);else if(u&&/-\d$/.test(l)&&!/-\d$/.test(u))[l,u]=[u,l];return l=Ca[l]||l,{service:l,region:u||"us-east-1"}}function x(a){let{method:n,url:i,body:s="",accessKeyId:c,secretAccessKey:l,sessionToken:u,signQuery:h=!1,expiresIn:y=86400,datetime:f}=a,S=new URL(i),b=S.hostname,C=Sp(S),T=a.service||C.service,v=a.region||C.region;if(!T)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!v)throw Error("Could not detect region from URL. Please provide region explicitly.");let w=f||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),R=w.substring(0,8),k=[R,v,T,"aws4_request"].join("/"),W="AWS4-HMAC-SHA256";if(h)return Xa({urlObj:S,method:n,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:T,region:v,timestamp:w,date:R,credentialScope:k,algorithm:W,expiresIn:y,cache:a.cache});let P=S.pathname||"/",V=ft(S.searchParams),B={host:b,"x-amz-date":w,...a.headers};if(u)B["x-amz-security-token"]=u;let j=Object.keys(B).some((Ie)=>Ie.toLowerCase()==="content-type");if(s&&!j)B["content-type"]="application/x-amz-json-1.0";if(T==="s3"&&!B["x-amz-content-sha256"])B["x-amz-content-sha256"]=Je(s);let J=ga(B),K=ha(B),ee=B["x-amz-content-sha256"]||Je(s),te=[n,St(P),V,J,K,ee].join(`
2
+ `),ne=Je(te),me=[W,w,k,ne].join(`
3
+ `),oe=a.cache??ke,ue=fa(l,R,v,T,me,oe),ie=[`${W} Credential=${c}/${k}`,`SignedHeaders=${K}`,`Signature=${ue}`].join(", ");return B.authorization=ie,{url:i,method:n,headers:B,body:s||void 0}}async function Cp(a){let{method:n,url:i,body:s="",accessKeyId:c,secretAccessKey:l,sessionToken:u,signQuery:h=!1,expiresIn:y=86400,datetime:f}=a,S=new URL(i),b=S.hostname,C=Sp(S),T=a.service||C.service,v=a.region||C.region;if(!T)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!v)throw Error("Could not detect region from URL. Please provide region explicitly.");let w=f||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),R=w.substring(0,8),k=[R,v,T,"aws4_request"].join("/"),W="AWS4-HMAC-SHA256";if(h)return er({urlObj:S,method:n,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:T,region:v,timestamp:w,date:R,credentialScope:k,algorithm:W,expiresIn:y,cache:a.cache});let P=S.pathname||"/",V=ft(S.searchParams),B={host:b,"x-amz-date":w,...a.headers};if(u)B["x-amz-security-token"]=u;let j=Object.keys(B).some((_e)=>_e.toLowerCase()==="content-type");if(s&&!j)B["content-type"]="application/x-amz-json-1.0";let J=await ut(s);if(T==="s3"&&!B["x-amz-content-sha256"])B["x-amz-content-sha256"]=J;let K=ga(B),ee=ha(B),te=B["x-amz-content-sha256"]||J,ne=[n,St(P),V,K,ee,te].join(`
4
+ `),me=await ut(ne),oe=[W,w,k,me].join(`
5
+ `),ue=a.cache??ke,ie=await Sa(l,R,v,T,oe,ue),Ie=[`${W} Credential=${c}/${k}`,`SignedHeaders=${ee}`,`Signature=${ie}`].join(", ");return B.authorization=Ie,{url:i,method:n,headers:B,body:s||void 0}}function Xa(a){let{urlObj:n,method:i,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:h,region:y,timestamp:f,date:S,credentialScope:b,algorithm:C,expiresIn:T,cache:v}=a,w=new URL(n.toString());w.searchParams.set("X-Amz-Algorithm",C),w.searchParams.set("X-Amz-Credential",`${c}/${b}`),w.searchParams.set("X-Amz-Date",f),w.searchParams.set("X-Amz-Expires",String(T));let R=h==="s3"?"UNSIGNED-PAYLOAD":Je(s);if(h==="s3")w.searchParams.set("X-Amz-Content-Sha256",R);let k="host";if(w.searchParams.set("X-Amz-SignedHeaders",k),u)w.searchParams.set("X-Amz-Security-Token",u);let W=St(w.pathname||"/"),P=`host:${w.hostname}
6
6
  `,V=ft(w.searchParams),B=[i,W,V,P,k,R].join(`
7
7
  `),j=[C,f,b,Je(B)].join(`
8
- `),Z=fa(l,S,y,h,j,v??ke);return w.searchParams.set("X-Amz-Signature",Z),{url:w.toString(),method:i,headers:{},body:s||void 0}}async function er(a){let{urlObj:n,method:i,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:h,region:y,timestamp:f,date:S,credentialScope:b,algorithm:C,expiresIn:T,cache:v}=a,w=new URL(n.toString());w.searchParams.set("X-Amz-Algorithm",C),w.searchParams.set("X-Amz-Credential",`${c}/${b}`),w.searchParams.set("X-Amz-Date",f),w.searchParams.set("X-Amz-Expires",String(T));let R=h==="s3"?"UNSIGNED-PAYLOAD":await dt(s);if(h==="s3")w.searchParams.set("X-Amz-Content-Sha256",R);let k="host";if(w.searchParams.set("X-Amz-SignedHeaders",k),u)w.searchParams.set("X-Amz-Security-Token",u);let W=St(w.pathname||"/"),P=`host:${w.hostname}
8
+ `),J=fa(l,S,y,h,j,v??ke);return w.searchParams.set("X-Amz-Signature",J),{url:w.toString(),method:i,headers:{},body:s||void 0}}async function er(a){let{urlObj:n,method:i,body:s,accessKeyId:c,secretAccessKey:l,sessionToken:u,service:h,region:y,timestamp:f,date:S,credentialScope:b,algorithm:C,expiresIn:T,cache:v}=a,w=new URL(n.toString());w.searchParams.set("X-Amz-Algorithm",C),w.searchParams.set("X-Amz-Credential",`${c}/${b}`),w.searchParams.set("X-Amz-Date",f),w.searchParams.set("X-Amz-Expires",String(T));let R=h==="s3"?"UNSIGNED-PAYLOAD":await ut(s);if(h==="s3")w.searchParams.set("X-Amz-Content-Sha256",R);let k="host";if(w.searchParams.set("X-Amz-SignedHeaders",k),u)w.searchParams.set("X-Amz-Security-Token",u);let W=St(w.pathname||"/"),P=`host:${w.hostname}
9
9
  `,V=ft(w.searchParams),B=[i,W,V,P,k,R].join(`
10
- `),j=[C,f,b,await dt(B)].join(`
11
- `),Z=await Sa(l,S,y,h,j,v??ke);return w.searchParams.set("X-Amz-Signature",Z),{url:w.toString(),method:i,headers:{},body:s||void 0}}function rf(a){let{url:n,method:i="GET",expiresIn:s=3600,...c}=a,l=Math.min(s,604800);return x({...c,url:n,method:i,signQuery:!0,expiresIn:l}).url}async function uy(a){let{url:n,method:i="GET",expiresIn:s=3600,...c}=a,l=Math.min(s,604800);return(await Cp({...c,url:n,method:i,signQuery:!0,expiresIn:l})).url}function ga(a){return Object.keys(a).sort().map((n)=>`${n.toLowerCase()}:${a[n].trim().replace(/\s+/g," ")}`).join(`
10
+ `),j=[C,f,b,await ut(B)].join(`
11
+ `),J=await Sa(l,S,y,h,j,v??ke);return w.searchParams.set("X-Amz-Signature",J),{url:w.toString(),method:i,headers:{},body:s||void 0}}function rf(a){let{url:n,method:i="GET",expiresIn:s=3600,...c}=a,l=Math.min(s,604800);return x({...c,url:n,method:i,signQuery:!0,expiresIn:l}).url}async function uy(a){let{url:n,method:i="GET",expiresIn:s=3600,...c}=a,l=Math.min(s,604800);return(await Cp({...c,url:n,method:i,signQuery:!0,expiresIn:l})).url}function ga(a){return Object.keys(a).sort().map((n)=>`${n.toLowerCase()}:${a[n].trim().replace(/\s+/g," ")}`).join(`
12
12
  `)+`
13
- `}function ha(a){return Object.keys(a).sort().map((n)=>n.toLowerCase()).join(";")}function ft(a){let n=[];return a.forEach((i,s)=>{n.push([kt(s),kt(i)])}),n.sort((i,s)=>{if(i[0]<s[0])return-1;if(i[0]>s[0])return 1;if(i[1]<s[1])return-1;if(i[1]>s[1])return 1;return 0}),n.map(([i,s])=>`${i}=${s}`).join("&")}function St(a){return a.split("/").map((n)=>kt(n)).join("/")}function kt(a){return encodeURIComponent(a).replace(/[!'()*]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}function Je(a){if(!Be)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return Be.createHash("sha256").update(a,"utf8").digest("hex")}function Ve(a,n){if(!Be)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return Be.createHmac("sha256",a).update(n,"utf8").digest()}async function dt(a){let n=new TextEncoder().encode(a),i=await crypto.subtle.digest("SHA-256",n);return ya(new Uint8Array(i))}async function je(a,n){let i=new TextEncoder,s=typeof a==="string"?i.encode(a):a,c=i.encode(n),l=await crypto.subtle.importKey("raw",s.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),u=await crypto.subtle.sign("HMAC",l,c.buffer);return new Uint8Array(u)}function ya(a){return Array.from(a).map((n)=>n.toString(16).padStart(2,"0")).join("")}function fa(a,n,i,s,c,l){let u=`${a}:${n}:${i}:${s}`,h=l.get(u);if(!h){let y=Ve(`AWS4${a}`,n),f=Ve(y,i),S=Ve(f,s);if(h=Ve(S,"aws4_request"),l.size>=Aa){let b=l.keys().next().value;if(b)l.delete(b)}l.set(u,h)}return Ve(h,c).toString("hex")}async function Sa(a,n,i,s,c,l){let u=`${a}:${n}:${i}:${s}`,h=l.get(u);if(!h){let f=await je(`AWS4${a}`,n),S=await je(f,i),b=await je(S,s);if(h=await je(b,"aws4_request"),l.size>=Aa){let C=l.keys().next().value;if(C)l.delete(C)}l.set(u,h)}let y=await je(h,c);return ya(y)}function ba(a,n){return n.includes(a)}function mt(a,n,i){let s=n*Math.pow(2,a),c=Math.random()*0.3*s;return Math.min(s+c,i)}function pt(a){return new Promise((n)=>setTimeout(n,a))}async function nf(a,n){let{maxRetries:i=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:l=[429,500,502,503,504],timeoutMs:u=30000}=n??{},h,y;for(let f=0;f<=i;f++){let S=x(a),b={method:S.method,headers:S.headers};if(S.body)b.body=S.body;let C=new AbortController,T=setTimeout(()=>C.abort(),u);b.signal=C.signal;try{let v=await fetch(S.url,b);if(clearTimeout(T),y=v,v.ok)return v;if(f<i&&ba(v.status,l)){let R=mt(f,s,c);await pt(R);continue}let w=await v.text();throw Error(`AWS API request failed (${v.status}): ${w}`)}catch(v){if(clearTimeout(T),h=v,v instanceof Error&&v.name==="AbortError")h=Error(`Request timed out after ${u}ms`);if(f<i&&!(v instanceof Error&&v.message.includes("AWS API request failed"))){let w=mt(f,s,c);await pt(w);continue}throw h}}throw h??Error("Request failed after retries")}async function py(a){return nf(a,{maxRetries:0})}async function gy(a,n){let{maxRetries:i=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:l=[429,500,502,503,504],timeoutMs:u=30000}=n??{},h;for(let y=0;y<=i;y++){let f=await Cp(a),S={method:f.method,headers:f.headers};if(f.body)S.body=f.body;let b=new AbortController,C=setTimeout(()=>b.abort(),u);S.signal=b.signal;try{let T=await fetch(f.url,S);if(clearTimeout(C),T.ok)return T;if(y<i&&ba(T.status,l)){let w=mt(y,s,c);await pt(w);continue}let v=await T.text();throw Error(`AWS API request failed (${T.status}): ${v}`)}catch(T){if(clearTimeout(C),h=T,T instanceof Error&&T.name==="AbortError")h=Error(`Request timed out after ${u}ms`);if(y<i&&!(T instanceof Error&&T.message.includes("AWS API request failed"))){let v=mt(y,s,c);await pt(v);continue}throw h}}throw h??Error("Request failed after retries")}async function my(a){let n=await a.text(),i={},s=/<(\w+)>([^<]+)<\/\1>/g,c;while((c=s.exec(n))!==null){let[,l,u]=c;i[l]=u}return i}async function hy(a){return await a.json()}function fy(){ke.clear()}function Ay(){return ke.size}function yy(){return Be!==void 0}function Iy(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}var Be,ke,Aa=100,Ca,et=Ya(async()=>{try{Be=await import("node:crypto")}catch{}ke=new Map,Ca={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"}}),Sy={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},Cy={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}},bp=".ts-cloud",Ep="TS_CLOUD_STATE_DIR",Ot=null;function Wc(a){Ot=a?.trim()||null}function Jc(){return Boolean(process.env[Ep]?.trim()||Ot)}function Qs(){return process.env[Ep]?.trim()||Ot||bp}function _(...a){return gt(Qs(),...a)}function d(a,...n){let i=Qs();return $t(i)?gt(i,...n):gt(a,i,...n)}function Xc(a,n=process.cwd()){let i=(c,l)=>{let u=tr(c,l);return u===""||!u.startsWith("..")&&!$t(u)},s=$t(a)?a:gt(n,a);return i(d(n),s)}function vp(a){let n=a.infrastructure?.compute!=null,i=Object.values(a.environments??{}).some((s)=>s?.app!=null);return{server:n,serverless:i}}function O(a){if(a.mode==="server"||a.mode==="serverless")return a.mode;let{serverless:n}=vp(a);return n?"serverless":"server"}function Yc(a){let{server:n,serverless:i}=vp(a);if(n&&i)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(a.mode==="server"&&i&&!n)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(a.mode==="serverless"&&n&&!i)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function p(a){return a.infrastructure?.appDatabase??a.infrastructure?.compute?.database}function ar(a){return typeof a==="object"&&a!==null?a:{}}function sf(a){return a===!0||typeof a==="object"&&a!==null}function rr(a,n){let i=n?a.environments?.[n]:void 0;if(i?.domain)return i.domain;let s=Object.values(a.sites??{}),c=a.sites?.main?.domain??s.find((l)=>l.domain)?.domain;if(c)return c;return`${a.project?.slug??"app"}.local`}function nr(a){let n=a.indexOf(".");return n>0?a.slice(n+1):void 0}function ui(a,n={}){let i=a.infrastructure?.compute?.managedServices?.mail,s=ar(i),c=n.environmentType??(n.environment?a.environments?.[n.environment]?.type:void 0),l=s.mode??(c==="production"?"server":"catcher"),u=l==="server",h=rr(a,n.environment),y=s.hostname??(u?`mail.${h}`:"localhost"),f=s.ports??{},S=u?{smtp:f.smtp??25,submission:f.submission??587,submissions:f.submissions??465,imap:f.imap??143,imaps:f.imaps??993,webmail:f.webmail??8080,managesieve:f.managesieve}:{smtp:f.smtp??1025,submission:f.submission,submissions:f.submissions,imap:f.imap,imaps:f.imaps,webmail:f.webmail??8025,managesieve:f.managesieve},b=s.tls??{},C=b.enabled??u,T=!!(b.certPath&&b.keyPath),v=(s.accounts??[]).map((K)=>({address:K.address,password:K.password})),w=typeof s.dkim==="object"&&s.dkim!==null?s.dkim:{},R=s.dkim===!1?!1:s.dkim===!0||u,k=typeof s.webmail==="object"&&s.webmail!==null?s.webmail:{},W=s.webmail===!1?!1:k.enabled??!0,P=s.spam??{},V=s.delivery??(u?"direct":"none"),B=s.expose??u,j=nr(y),Z=[...new Set([y,...j?[j]:[],...s.domains??[]])];return{enabled:sf(i),mode:l,version:s.version,hostname:y,domains:Z,ports:S,tls:{enabled:C,acme:C&&!T&&(b.acme??!0),certPath:b.certPath,keyPath:b.keyPath,requireForAuth:b.requireForAuth??(C&&u),acmeEmail:b.acmeEmail??v[0]?.address},dkim:{enabled:R,selector:w.selector??"default",rotate:w.rotate??!1,rotateIntervalDays:w.rotateIntervalDays??90},webmail:{enabled:W,port:k.port??S.webmail,domain:k.domain},delivery:V,sesRegion:s.sesRegion??"us-east-1",accounts:v,storagePath:s.storagePath??"/var/lib/mail",maxMessageSize:s.maxMessageSize??26214400,spam:{enabled:P.enabled??u,enforce:P.enforce??!1,junkScore:P.junkScore??5,rejectScore:P.rejectScore??12,dnsbl:P.dnsbl??u,greylist:P.greylist??!1},webhookUrl:s.webhookUrl,expose:B,bindAddress:B?"0.0.0.0":"127.0.0.1"}}function Zc(a){if(!a.enabled||!a.expose)return[];let n=[a.ports.smtp,a.ports.submission,a.ports.submissions,a.ports.imap,a.ports.imaps,a.ports.managesieve].filter((i)=>typeof i==="number");if(a.webmail.enabled&&!a.webmail.domain)n.push(a.webmail.port);return[...new Set(n)].sort((i,s)=>i-s)}function ed(a){if(!a.enabled)return{};let n=a.ports.submission??a.ports.smtp,i={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(n)};if(a.mode==="server"){i.MAIL_ENCRYPTION=a.tls.enabled?"tls":"null";let s=a.accounts[0];if(s)i.MAIL_USERNAME=s.address,i.MAIL_PASSWORD=s.password}else i.MAIL_ENCRYPTION="null",i.MAIL_USERNAME="null",i.MAIL_PASSWORD="null";return i}function ae(a){if(a.cloud?.provider)return a.cloud.provider;if(a.ssh?.hosts?.length)return"ssh";if(a.hetzner?.apiToken)return"hetzner";return"aws"}class td{template;constructor(a){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:a,Resources:{}}}addResource(a,n){return this.template.Resources[a]=n,this}addResources(a){return Object.assign(this.template.Resources,a),this}addParameter(a,n){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[a]=n,this}addOutput(a,n){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[a]=n,this}hasResource(a){return a in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(a=!0){return JSON.stringify(this.template,null,a?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(a,n=0){let i=" ".repeat(n),s="";for(let[c,l]of Object.entries(a)){if(l===null||l===void 0)continue;if(typeof l==="object"&&!Array.isArray(l))s+=`${i}${c}:
13
+ `}function ha(a){return Object.keys(a).sort().map((n)=>n.toLowerCase()).join(";")}function ft(a){let n=[];return a.forEach((i,s)=>{n.push([kt(s),kt(i)])}),n.sort((i,s)=>{if(i[0]<s[0])return-1;if(i[0]>s[0])return 1;if(i[1]<s[1])return-1;if(i[1]>s[1])return 1;return 0}),n.map(([i,s])=>`${i}=${s}`).join("&")}function St(a){return a.split("/").map((n)=>kt(n)).join("/")}function kt(a){return encodeURIComponent(a).replace(/[!'()*]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}function Je(a){if(!Oe)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return Oe.createHash("sha256").update(a,"utf8").digest("hex")}function Ge(a,n){if(!Oe)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return Oe.createHmac("sha256",a).update(n,"utf8").digest()}async function ut(a){let n=new TextEncoder().encode(a),i=await crypto.subtle.digest("SHA-256",n);return ya(new Uint8Array(i))}async function Ve(a,n){let i=new TextEncoder,s=typeof a==="string"?i.encode(a):a,c=i.encode(n),l=await crypto.subtle.importKey("raw",s.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),u=await crypto.subtle.sign("HMAC",l,c.buffer);return new Uint8Array(u)}function ya(a){return Array.from(a).map((n)=>n.toString(16).padStart(2,"0")).join("")}function fa(a,n,i,s,c,l){let u=`${a}:${n}:${i}:${s}`,h=l.get(u);if(!h){let y=Ge(`AWS4${a}`,n),f=Ge(y,i),S=Ge(f,s);if(h=Ge(S,"aws4_request"),l.size>=Aa){let b=l.keys().next().value;if(b)l.delete(b)}l.set(u,h)}return Ge(h,c).toString("hex")}async function Sa(a,n,i,s,c,l){let u=`${a}:${n}:${i}:${s}`,h=l.get(u);if(!h){let f=await Ve(`AWS4${a}`,n),S=await Ve(f,i),b=await Ve(S,s);if(h=await Ve(b,"aws4_request"),l.size>=Aa){let C=l.keys().next().value;if(C)l.delete(C)}l.set(u,h)}let y=await Ve(h,c);return ya(y)}function ba(a,n){return n.includes(a)}function mt(a,n,i){let s=n*Math.pow(2,a),c=Math.random()*0.3*s;return Math.min(s+c,i)}function pt(a){return new Promise((n)=>setTimeout(n,a))}async function nf(a,n){let{maxRetries:i=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:l=[429,500,502,503,504],timeoutMs:u=30000}=n??{},h,y;for(let f=0;f<=i;f++){let S=x(a),b={method:S.method,headers:S.headers};if(S.body)b.body=S.body;let C=new AbortController,T=setTimeout(()=>C.abort(),u);b.signal=C.signal;try{let v=await fetch(S.url,b);if(clearTimeout(T),y=v,v.ok)return v;if(f<i&&ba(v.status,l)){let R=mt(f,s,c);await pt(R);continue}let w=await v.text();throw Error(`AWS API request failed (${v.status}): ${w}`)}catch(v){if(clearTimeout(T),h=v,v instanceof Error&&v.name==="AbortError")h=Error(`Request timed out after ${u}ms`);if(f<i&&!(v instanceof Error&&v.message.includes("AWS API request failed"))){let w=mt(f,s,c);await pt(w);continue}throw h}}throw h??Error("Request failed after retries")}async function py(a){return nf(a,{maxRetries:0})}async function gy(a,n){let{maxRetries:i=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:l=[429,500,502,503,504],timeoutMs:u=30000}=n??{},h;for(let y=0;y<=i;y++){let f=await Cp(a),S={method:f.method,headers:f.headers};if(f.body)S.body=f.body;let b=new AbortController,C=setTimeout(()=>b.abort(),u);S.signal=b.signal;try{let T=await fetch(f.url,S);if(clearTimeout(C),T.ok)return T;if(y<i&&ba(T.status,l)){let w=mt(y,s,c);await pt(w);continue}let v=await T.text();throw Error(`AWS API request failed (${T.status}): ${v}`)}catch(T){if(clearTimeout(C),h=T,T instanceof Error&&T.name==="AbortError")h=Error(`Request timed out after ${u}ms`);if(y<i&&!(T instanceof Error&&T.message.includes("AWS API request failed"))){let v=mt(y,s,c);await pt(v);continue}throw h}}throw h??Error("Request failed after retries")}async function my(a){let n=await a.text(),i={},s=/<(\w+)>([^<]+)<\/\1>/g,c;while((c=s.exec(n))!==null){let[,l,u]=c;i[l]=u}return i}async function hy(a){return await a.json()}function fy(){ke.clear()}function Ay(){return ke.size}function yy(){return Oe!==void 0}function Iy(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}var Oe,ke,Aa=100,Ca,et=Ya(async()=>{try{Oe=await import("node:crypto")}catch{}ke=new Map,Ca={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"}}),Sy={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},Cy={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}},bp=".ts-cloud",Ep="TS_CLOUD_STATE_DIR",Ot=null;function Wc(a){Ot=a?.trim()||null}function Jc(){return Boolean(process.env[Ep]?.trim()||Ot)}function Qs(){return process.env[Ep]?.trim()||Ot||bp}function _(...a){return gt(Qs(),...a)}function d(a,...n){let i=Qs();return $t(i)?gt(i,...n):gt(a,i,...n)}function Xc(a,n=process.cwd()){let i=(c,l)=>{let u=tr(c,l);return u===""||!u.startsWith("..")&&!$t(u)},s=$t(a)?a:gt(n,a);return i(d(n),s)}function vp(a){let n=a.infrastructure?.compute!=null,i=Object.values(a.environments??{}).some((s)=>s?.app!=null);return{server:n,serverless:i}}function O(a){if(a.mode==="server"||a.mode==="serverless")return a.mode;let{serverless:n}=vp(a);return n?"serverless":"server"}function Yc(a){let{server:n,serverless:i}=vp(a);if(n&&i)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(a.mode==="server"&&i&&!n)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(a.mode==="serverless"&&n&&!i)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function p(a){return a.infrastructure?.appDatabase??a.infrastructure?.compute?.database}function ar(a){return typeof a==="object"&&a!==null?a:{}}function sf(a){return a===!0||typeof a==="object"&&a!==null}function rr(a,n){let i=n?a.environments?.[n]:void 0;if(i?.domain)return i.domain;let s=Object.values(a.sites??{}),c=a.sites?.main?.domain??s.find((l)=>l.domain)?.domain;if(c)return c;return`${a.project?.slug??"app"}.local`}function nr(a){let n=a.indexOf(".");return n>0?a.slice(n+1):void 0}function ui(a,n={}){let i=a.infrastructure?.compute?.managedServices?.mail,s=ar(i),c=n.environmentType??(n.environment?a.environments?.[n.environment]?.type:void 0),l=s.mode??(c==="production"?"server":"catcher"),u=l==="server",h=rr(a,n.environment),y=s.hostname??(u?`mail.${h}`:"localhost"),f=s.ports??{},S=u?{smtp:f.smtp??25,submission:f.submission??587,submissions:f.submissions??465,imap:f.imap??143,imaps:f.imaps??993,webmail:f.webmail??8080,managesieve:f.managesieve}:{smtp:f.smtp??1025,submission:f.submission,submissions:f.submissions,imap:f.imap,imaps:f.imaps,webmail:f.webmail??8025,managesieve:f.managesieve},b=s.tls??{},C=b.enabled??u,T=!!(b.certPath&&b.keyPath),v=(s.accounts??[]).map((K)=>({address:K.address,password:K.password})),w=typeof s.dkim==="object"&&s.dkim!==null?s.dkim:{},R=s.dkim===!1?!1:s.dkim===!0||u,k=typeof s.webmail==="object"&&s.webmail!==null?s.webmail:{},W=s.webmail===!1?!1:k.enabled??!0,P=s.spam??{},V=s.delivery??(u?"direct":"none"),B=s.expose??u,j=nr(y),J=[...new Set([y,...j?[j]:[],...s.domains??[]])];return{enabled:sf(i),mode:l,version:s.version,hostname:y,domains:J,ports:S,tls:{enabled:C,acme:C&&!T&&(b.acme??!0),certPath:b.certPath,keyPath:b.keyPath,requireForAuth:b.requireForAuth??(C&&u),acmeEmail:b.acmeEmail??v[0]?.address},dkim:{enabled:R,selector:w.selector??"default",rotate:w.rotate??!1,rotateIntervalDays:w.rotateIntervalDays??90},webmail:{enabled:W,port:k.port??S.webmail,domain:k.domain},delivery:V,sesRegion:s.sesRegion??"us-east-1",accounts:v,storagePath:s.storagePath??"/var/lib/mail",maxMessageSize:s.maxMessageSize??26214400,spam:{enabled:P.enabled??u,enforce:P.enforce??!1,junkScore:P.junkScore??5,rejectScore:P.rejectScore??12,dnsbl:P.dnsbl??u,greylist:P.greylist??!1},webhookUrl:s.webhookUrl,expose:B,bindAddress:B?"0.0.0.0":"127.0.0.1"}}function Zc(a){if(!a.enabled||!a.expose)return[];let n=[a.ports.smtp,a.ports.submission,a.ports.submissions,a.ports.imap,a.ports.imaps,a.ports.managesieve].filter((i)=>typeof i==="number");if(a.webmail.enabled&&!a.webmail.domain)n.push(a.webmail.port);return[...new Set(n)].sort((i,s)=>i-s)}function ed(a){if(!a.enabled)return{};let n=a.ports.submission??a.ports.smtp,i={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(n)};if(a.mode==="server"){i.MAIL_ENCRYPTION=a.tls.enabled?"tls":"null";let s=a.accounts[0];if(s)i.MAIL_USERNAME=s.address,i.MAIL_PASSWORD=s.password}else i.MAIL_ENCRYPTION="null",i.MAIL_USERNAME="null",i.MAIL_PASSWORD="null";return i}function ce(a){if(a.cloud?.provider)return a.cloud.provider;if(a.ssh?.hosts?.length)return"ssh";if(a.hetzner?.apiToken)return"hetzner";return"aws"}class td{template;constructor(a){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:a,Resources:{}}}addResource(a,n){return this.template.Resources[a]=n,this}addResources(a){return Object.assign(this.template.Resources,a),this}addParameter(a,n){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[a]=n,this}addOutput(a,n){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[a]=n,this}hasResource(a){return a in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(a=!0){return JSON.stringify(this.template,null,a?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(a,n=0){let i=" ".repeat(n),s="";for(let[c,l]of Object.entries(a)){if(l===null||l===void 0)continue;if(typeof l==="object"&&!Array.isArray(l))s+=`${i}${c}:
14
14
  ${this.convertToYAML(l,n+1)}`;else if(Array.isArray(l)){s+=`${i}${c}:
15
15
  `;for(let u of l)if(typeof u==="object")s+=`${i} -
16
16
  ${this.convertToYAML(u,n+2)}`;else s+=`${i} - ${u}
@@ -20,7 +20,7 @@ ${this.convertToYAML(u,n+2)}`;else s+=`${i} - ${u}
20
20
  `),n.join(`
21
21
  `);if(n.push(`Total changes: ${a.summary.totalChanges}`),n.push(`Requires replacement: ${a.summary.requiresReplacement?"Yes":"No"}
22
22
  `),a.summary.dangerousChanges.length>0){n.push("⚠️ DANGEROUS CHANGES DETECTED:");for(let i of a.summary.dangerousChanges)n.push(` • ${i}`);n.push("")}if(a.added.length>0){n.push(`✅ Resources to Add (${a.added.length}):`);for(let i of a.added)n.push(` + ${i.logicalId} (${i.resourceType})`);n.push("")}if(a.removed.length>0){n.push(`❌ Resources to Remove (${a.removed.length}):`);for(let i of a.removed)n.push(` - ${i.logicalId} (${i.resourceType})`);n.push("")}if(a.replaced.length>0){n.push(`\uD83D\uDD04 Resources to Replace (${a.replaced.length}):`);for(let i of a.replaced){if(n.push(` ~ ${i.logicalId} (${i.resourceType})`),i.reason)n.push(` Reason: ${i.reason}`);if(i.changes){for(let s of i.changes.slice(0,3))n.push(` • ${s.path}: ${JSON.stringify(s.oldValue)} → ${JSON.stringify(s.newValue)}`);if(i.changes.length>3)n.push(` ... and ${i.changes.length-3} more changes`)}}n.push("")}if(a.updated.length>0){n.push(`\uD83D\uDCDD Resources to Update (${a.updated.length}):`);for(let i of a.updated)if(n.push(` ~ ${i.logicalId} (${i.resourceType})`),i.changes){for(let s of i.changes.slice(0,3))n.push(` • ${s.path}: ${JSON.stringify(s.oldValue)} → ${JSON.stringify(s.newValue)}`);if(i.changes.length>3)n.push(` ... and ${i.changes.length-3} more changes`)}n.push("")}if(a.unchanged.length>0)n.push(`⚪ Unchanged Resources (${a.unchanged.length})`);return n.join(`
23
- `)}class Se{static createBucket(a){let{name:n,bucketName:i,slug:s,environment:c,public:l=!1,versioning:u=!1,website:h=!1,encryption:y=!0,intelligentTiering:f=!1,cors:S,lifecycleRules:b}=a,C=i??r({slug:s,environment:c,resourceType:"s3",suffix:n}),T=t(C),v={Type:"AWS::S3::Bucket",Properties:{BucketName:C}};if(y)v.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(u)v.Properties.VersioningConfiguration={Status:"Enabled"};if(h)v.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!l)v.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(S&&S.length>0)v.Properties.CorsConfiguration={CorsRules:S.map((R)=>({AllowedOrigins:R.allowedOrigins,AllowedMethods:R.allowedMethods,AllowedHeaders:R.allowedHeaders,MaxAge:R.maxAge}))};if(b&&b.length>0)v.Properties.LifecycleConfiguration={Rules:b.map((R)=>({Id:R.id,Status:R.enabled?"Enabled":"Disabled",ExpirationInDays:R.expirationDays,Transitions:R.transitions?.map((k)=>({TransitionInDays:k.days,StorageClass:k.storageClass}))}))};if(f&&b){let R={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!v.Properties.LifecycleConfiguration)v.Properties.LifecycleConfiguration={Rules:[]};v.Properties.LifecycleConfiguration.Rules.push({Id:R.id,Status:"Enabled",Transitions:R.transitions?.map((k)=>({TransitionInDays:k.days,StorageClass:k.storageClass}))})}let w;if(l)w={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(T),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[N.Join("",[N.GetAtt(T,"Arn"),"/*"])]}]}}};return{bucket:v,bucketPolicy:w,logicalId:T}}static enableVersioning(a){if(!a.Properties)a.Properties={};return a.Properties.VersioningConfiguration={Status:"Enabled"},a}static enableWebsiteHosting(a,n="index.html",i="error.html"){if(!a.Properties)a.Properties={};return a.Properties.WebsiteConfiguration={IndexDocument:n,ErrorDocument:i},a}static setLifecycleRules(a,n){if(!a.Properties)a.Properties={};return a.Properties.LifecycleConfiguration={Rules:n.map((i)=>({Id:i.id,Status:i.enabled?"Enabled":"Disabled",ExpirationInDays:i.expirationDays,Transitions:i.transitions?.map((s)=>({TransitionInDays:s.days,StorageClass:s.storageClass}))}))},a}static enableIntelligentTiering(a){if(!a.Properties)a.Properties={};if(!a.Properties.LifecycleConfiguration)a.Properties.LifecycleConfiguration={Rules:[]};return a.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),a}static addLambdaNotification(a,n){if(!a.Properties)a.Properties={};if(!a.Properties.NotificationConfiguration)a.Properties.NotificationConfiguration={};if(!a.Properties.NotificationConfiguration.LambdaConfigurations)a.Properties.NotificationConfiguration.LambdaConfigurations=[];let i={Event:n.events[0],Function:n.functionArn};if(n.filter)i.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};for(let s of n.events){let c={...i,Event:s};a.Properties.NotificationConfiguration.LambdaConfigurations.push(c)}return a}static Notifications={onObjectCreated:(a)=>({functionArn:a,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(a)=>({functionArn:a,events:["s3:ObjectRemoved:*"]}),onImageUpload:(a,n)=>({functionArn:a,events:["s3:ObjectCreated:*"],filter:{prefix:n,suffix:".jpg"}}),onFileType:(a,n,i)=>({functionArn:a,events:["s3:ObjectCreated:*"],filter:{prefix:i,suffix:n}}),onFolderUpload:(a,n)=>({functionArn:a,events:["s3:ObjectCreated:*"],filter:{prefix:n.endsWith("/")?n:`${n}/`}})};static createBackupPlan(a){let{name:n,slug:i,environment:s,bucketLogicalIds:c,retentionDays:l,schedule:u="cron(0 5 * * ? *)",vaultName:h,enableContinuousBackup:y=!1,moveToColdStorageAfterDays:f}=a,S=h||r({slug:i,environment:s,resourceType:"backup-vault",suffix:n}),b=t(S),C={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:S}},T=r({slug:i,environment:s,resourceType:"backup-role",suffix:n}),v=t(T),w={Type:"AWS::IAM::Role",Properties:{RoleName:T,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},R=r({slug:i,environment:s,resourceType:"backup-plan",suffix:n}),k=t(R),W={DeleteAfterDays:l};if(f&&f<l)W.MoveToColdStorageAfterDays=f;let P={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:R,BackupPlanRule:[{RuleName:`${n}-daily-backup`,TargetBackupVault:N.Ref(b),ScheduleExpression:u,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:W,EnableContinuousBackup:y}]}}},V=r({slug:i,environment:s,resourceType:"backup-selection",suffix:n}),B=t(V),j=c.map((K)=>N.GetAtt(K,"Arn")),Z={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:N.Ref(k),BackupSelection:{SelectionName:V,IamRoleArn:N.GetAtt(v,"Arn"),Resources:j}}};return{vault:C,plan:P,selection:Z,role:w,vaultLogicalId:b,planLogicalId:k,selectionLogicalId:B,roleLogicalId:v}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(a){let{slug:n,environment:i,sourceDomain:s,targetDomain:c,protocol:l="https"}=a,u=r({slug:n,environment:i,resourceType:"s3",suffix:"www-redirect"}),h=t(u),y={Type:"AWS::S3::Bucket",Properties:{BucketName:s,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:l}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},f={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(h),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[N.Join("",[N.GetAtt(h,"Arn"),"/*"])]}]}}};return{bucket:y,bucketPolicy:f,logicalId:h}}static createDocsBucket(a){let{slug:n,environment:i,domain:s}=a,c=s||r({slug:n,environment:i,resourceType:"s3",suffix:"docs"}),l=t(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:l}}static createEmailBucket(a){let{slug:n,environment:i}=a,s=r({slug:n,environment:i,resourceType:"s3",suffix:"email"}),c=t(s),l={Type:"AWS::S3::Bucket",Properties:{BucketName:s,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},u={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(c),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:N.Join("",[N.GetAtt(c,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":N.Ref("AWS::AccountId")}}}]}}};return{bucket:l,bucketPolicy:u,logicalId:c}}static docsExist(a={}){let{projectRoot:n=process.cwd(),docsPaths:i=["docs","documentation","doc"]}=a;for(let s of i){let c=ve(n,s);if(Ke(c)){let l=["dist","build",".bunpress/dist","_site","out","public"];for(let u of l){let h=ve(c,u);if(Ke(h))try{if(or(h).length>0)return{exists:!0,path:c,hasDistFolder:!0,distPath:h}}catch{}}return{exists:!0,path:c,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(a){let n=Se.docsExist({projectRoot:a.projectRoot,docsPaths:a.docsPaths});if(!n.exists)return{bucket:null,logicalId:null,docsInfo:n};let i=Se.createDocsBucket({slug:a.slug,environment:a.environment,domain:a.domain});return{bucket:i.bucket,bucketPolicy:i.bucketPolicy,logicalId:i.logicalId,docsInfo:n}}static createPrivateBucket(a){let{slug:n,environment:i,enableVersioning:s=!0,retentionDays:c,encryptionKeyArn:l}=a,u=r({slug:n,environment:i,resourceType:"s3",suffix:"private"}),h=t(u);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:u,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:l?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:l}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:s?{Status:"Enabled"}:void 0,LifecycleConfiguration:c?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:c}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:h}}static checkSourcePaths(a={}){let{projectRoot:n=process.cwd(),paths:i={}}=a,s=i.web||"views/web/dist",c=i.docs||"docs/dist",l=i.private||"private";return{web:{exists:Ke(ve(n,s)),path:ve(n,s)},docs:{exists:Ke(ve(n,c)),path:ve(n,c)},private:{exists:Ke(ve(n,l)),path:ve(n,l)}}}static createDeploymentBuckets(a){let{slug:n,environment:i,domain:s,projectRoot:c,paths:l}=a,u=Se.checkSourcePaths({projectRoot:c,paths:l}),h={},y={web:!1,docs:!1,private:!1},f=Se.createBucket({name:"web",slug:n,environment:i,public:!1,versioning:!1,encryption:!0});if(h[f.logicalId]=f.bucket,y.web=!0,u.docs.exists){let S=Se.createDocsBucket({slug:n,environment:i,domain:s?`docs.${s}`:void 0});if(h[S.logicalId]=S.bucket,S.bucketPolicy)h[`${S.logicalId}Policy`]=S.bucketPolicy;y.docs=!0}if(u.private.exists){let S=Se.createPrivateBucket({slug:n,environment:i,enableVersioning:!0});h[S.logicalId]=S.bucket,y.private=!0}return{resources:h,created:y,sourcePaths:u}}}class Me{static createRepository(a){let{name:n,slug:i,environment:s,scanOnPush:c=!0,imageMutability:l="MUTABLE",encryption:u="AES256",kmsKey:h,lifecyclePolicy:y,tags:f}=a,S=r({slug:i,environment:s,resourceType:"ecr",suffix:n}),b=t(S),C={Type:"AWS::ECR::Repository",Properties:{RepositoryName:S,ImageTagMutability:l,ImageScanningConfiguration:{ScanOnPush:c},EncryptionConfiguration:{EncryptionType:u,...h&&u==="KMS"?{KmsKey:h}:{}}}};if(y)C.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Me.generateLifecyclePolicy(y))};if(f)C.Properties.Tags=Object.entries(f).map(([T,v])=>({Key:T,Value:v}));return{repository:C,logicalId:b}}static generateLifecyclePolicy(a){let n=[];if(a.untaggedImageExpireDays!==void 0)n.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:a.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(a.maxImageCount!==void 0)n.push({rulePriority:n.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:a.maxImageCount},action:{type:"expire"}});if(a.maxImageAgeDays!==void 0)n.push({rulePriority:n.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:a.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:n}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(a){if(!a.Properties)a.Properties={};return a.Properties.ImageTagMutability="IMMUTABLE",a}static enableScanOnPush(a){if(!a.Properties)a.Properties={};return a.Properties.ImageScanningConfiguration={ScanOnPush:!0},a}static setLifecyclePolicy(a,n){if(!a.Properties)a.Properties={};return a.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Me.generateLifecyclePolicy(n))},a}static addCrossAccountAccess(a,n){if(!a.Properties)a.Properties={};return a.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:n.map((i)=>`arn:aws:iam::${i}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},a}static addLambdaAccess(a){if(!a.Properties)a.Properties={};return a.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},a}static generateBunDockerfile(a){let{baseImage:n="oven/bun:1-debian",serverPath:i,port:s=3000,additionalDirs:c=[],healthCheckEndpoint:l="/health",nodeCompatible:u=!1,envVars:h={},buildCommands:y=[],runCommand:f}=a,S=["app","config",...c],b=f||`bun run ${i}`,C=`# Multi-stage build for Bun application
23
+ `)}class Se{static createBucket(a){let{name:n,bucketName:i,slug:s,environment:c,public:l=!1,versioning:u=!1,website:h=!1,encryption:y=!0,intelligentTiering:f=!1,cors:S,lifecycleRules:b}=a,C=i??r({slug:s,environment:c,resourceType:"s3",suffix:n}),T=t(C),v={Type:"AWS::S3::Bucket",Properties:{BucketName:C}};if(y)v.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(u)v.Properties.VersioningConfiguration={Status:"Enabled"};if(h)v.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!l)v.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(S&&S.length>0)v.Properties.CorsConfiguration={CorsRules:S.map((R)=>({AllowedOrigins:R.allowedOrigins,AllowedMethods:R.allowedMethods,AllowedHeaders:R.allowedHeaders,MaxAge:R.maxAge}))};if(b&&b.length>0)v.Properties.LifecycleConfiguration={Rules:b.map((R)=>({Id:R.id,Status:R.enabled?"Enabled":"Disabled",ExpirationInDays:R.expirationDays,Transitions:R.transitions?.map((k)=>({TransitionInDays:k.days,StorageClass:k.storageClass}))}))};if(f&&b){let R={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!v.Properties.LifecycleConfiguration)v.Properties.LifecycleConfiguration={Rules:[]};v.Properties.LifecycleConfiguration.Rules.push({Id:R.id,Status:"Enabled",Transitions:R.transitions?.map((k)=>({TransitionInDays:k.days,StorageClass:k.storageClass}))})}let w;if(l)w={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(T),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[N.Join("",[N.GetAtt(T,"Arn"),"/*"])]}]}}};return{bucket:v,bucketPolicy:w,logicalId:T}}static enableVersioning(a){if(!a.Properties)a.Properties={};return a.Properties.VersioningConfiguration={Status:"Enabled"},a}static enableWebsiteHosting(a,n="index.html",i="error.html"){if(!a.Properties)a.Properties={};return a.Properties.WebsiteConfiguration={IndexDocument:n,ErrorDocument:i},a}static setLifecycleRules(a,n){if(!a.Properties)a.Properties={};return a.Properties.LifecycleConfiguration={Rules:n.map((i)=>({Id:i.id,Status:i.enabled?"Enabled":"Disabled",ExpirationInDays:i.expirationDays,Transitions:i.transitions?.map((s)=>({TransitionInDays:s.days,StorageClass:s.storageClass}))}))},a}static enableIntelligentTiering(a){if(!a.Properties)a.Properties={};if(!a.Properties.LifecycleConfiguration)a.Properties.LifecycleConfiguration={Rules:[]};return a.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),a}static addLambdaNotification(a,n){if(!a.Properties)a.Properties={};if(!a.Properties.NotificationConfiguration)a.Properties.NotificationConfiguration={};if(!a.Properties.NotificationConfiguration.LambdaConfigurations)a.Properties.NotificationConfiguration.LambdaConfigurations=[];let i={Event:n.events[0],Function:n.functionArn};if(n.filter)i.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};for(let s of n.events){let c={...i,Event:s};a.Properties.NotificationConfiguration.LambdaConfigurations.push(c)}return a}static Notifications={onObjectCreated:(a)=>({functionArn:a,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(a)=>({functionArn:a,events:["s3:ObjectRemoved:*"]}),onImageUpload:(a,n)=>({functionArn:a,events:["s3:ObjectCreated:*"],filter:{prefix:n,suffix:".jpg"}}),onFileType:(a,n,i)=>({functionArn:a,events:["s3:ObjectCreated:*"],filter:{prefix:i,suffix:n}}),onFolderUpload:(a,n)=>({functionArn:a,events:["s3:ObjectCreated:*"],filter:{prefix:n.endsWith("/")?n:`${n}/`}})};static createBackupPlan(a){let{name:n,slug:i,environment:s,bucketLogicalIds:c,retentionDays:l,schedule:u="cron(0 5 * * ? *)",vaultName:h,enableContinuousBackup:y=!1,moveToColdStorageAfterDays:f}=a,S=h||r({slug:i,environment:s,resourceType:"backup-vault",suffix:n}),b=t(S),C={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:S}},T=r({slug:i,environment:s,resourceType:"backup-role",suffix:n}),v=t(T),w={Type:"AWS::IAM::Role",Properties:{RoleName:T,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},R=r({slug:i,environment:s,resourceType:"backup-plan",suffix:n}),k=t(R),W={DeleteAfterDays:l};if(f&&f<l)W.MoveToColdStorageAfterDays=f;let P={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:R,BackupPlanRule:[{RuleName:`${n}-daily-backup`,TargetBackupVault:N.Ref(b),ScheduleExpression:u,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:W,EnableContinuousBackup:y}]}}},V=r({slug:i,environment:s,resourceType:"backup-selection",suffix:n}),B=t(V),j=c.map((K)=>N.GetAtt(K,"Arn")),J={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:N.Ref(k),BackupSelection:{SelectionName:V,IamRoleArn:N.GetAtt(v,"Arn"),Resources:j}}};return{vault:C,plan:P,selection:J,role:w,vaultLogicalId:b,planLogicalId:k,selectionLogicalId:B,roleLogicalId:v}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(a){let{slug:n,environment:i,sourceDomain:s,targetDomain:c,protocol:l="https"}=a,u=r({slug:n,environment:i,resourceType:"s3",suffix:"www-redirect"}),h=t(u),y={Type:"AWS::S3::Bucket",Properties:{BucketName:s,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:l}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},f={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(h),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[N.Join("",[N.GetAtt(h,"Arn"),"/*"])]}]}}};return{bucket:y,bucketPolicy:f,logicalId:h}}static createDocsBucket(a){let{slug:n,environment:i,domain:s}=a,c=s||r({slug:n,environment:i,resourceType:"s3",suffix:"docs"}),l=t(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:l}}static createEmailBucket(a){let{slug:n,environment:i}=a,s=r({slug:n,environment:i,resourceType:"s3",suffix:"email"}),c=t(s),l={Type:"AWS::S3::Bucket",Properties:{BucketName:s,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},u={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(c),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:N.Join("",[N.GetAtt(c,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":N.Ref("AWS::AccountId")}}}]}}};return{bucket:l,bucketPolicy:u,logicalId:c}}static docsExist(a={}){let{projectRoot:n=process.cwd(),docsPaths:i=["docs","documentation","doc"]}=a;for(let s of i){let c=ve(n,s);if(je(c)){let l=["dist","build",".bunpress/dist","_site","out","public"];for(let u of l){let h=ve(c,u);if(je(h))try{if(or(h).length>0)return{exists:!0,path:c,hasDistFolder:!0,distPath:h}}catch{}}return{exists:!0,path:c,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(a){let n=Se.docsExist({projectRoot:a.projectRoot,docsPaths:a.docsPaths});if(!n.exists)return{bucket:null,logicalId:null,docsInfo:n};let i=Se.createDocsBucket({slug:a.slug,environment:a.environment,domain:a.domain});return{bucket:i.bucket,bucketPolicy:i.bucketPolicy,logicalId:i.logicalId,docsInfo:n}}static createPrivateBucket(a){let{slug:n,environment:i,enableVersioning:s=!0,retentionDays:c,encryptionKeyArn:l}=a,u=r({slug:n,environment:i,resourceType:"s3",suffix:"private"}),h=t(u);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:u,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:l?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:l}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:s?{Status:"Enabled"}:void 0,LifecycleConfiguration:c?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:c}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:h}}static checkSourcePaths(a={}){let{projectRoot:n=process.cwd(),paths:i={}}=a,s=i.web||"views/web/dist",c=i.docs||"docs/dist",l=i.private||"private";return{web:{exists:je(ve(n,s)),path:ve(n,s)},docs:{exists:je(ve(n,c)),path:ve(n,c)},private:{exists:je(ve(n,l)),path:ve(n,l)}}}static createDeploymentBuckets(a){let{slug:n,environment:i,domain:s,projectRoot:c,paths:l}=a,u=Se.checkSourcePaths({projectRoot:c,paths:l}),h={},y={web:!1,docs:!1,private:!1},f=Se.createBucket({name:"web",slug:n,environment:i,public:!1,versioning:!1,encryption:!0});if(h[f.logicalId]=f.bucket,y.web=!0,u.docs.exists){let S=Se.createDocsBucket({slug:n,environment:i,domain:s?`docs.${s}`:void 0});if(h[S.logicalId]=S.bucket,S.bucketPolicy)h[`${S.logicalId}Policy`]=S.bucketPolicy;y.docs=!0}if(u.private.exists){let S=Se.createPrivateBucket({slug:n,environment:i,enableVersioning:!0});h[S.logicalId]=S.bucket,y.private=!0}return{resources:h,created:y,sourcePaths:u}}}class Fe{static createRepository(a){let{name:n,slug:i,environment:s,scanOnPush:c=!0,imageMutability:l="MUTABLE",encryption:u="AES256",kmsKey:h,lifecyclePolicy:y,tags:f}=a,S=r({slug:i,environment:s,resourceType:"ecr",suffix:n}),b=t(S),C={Type:"AWS::ECR::Repository",Properties:{RepositoryName:S,ImageTagMutability:l,ImageScanningConfiguration:{ScanOnPush:c},EncryptionConfiguration:{EncryptionType:u,...h&&u==="KMS"?{KmsKey:h}:{}}}};if(y)C.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Fe.generateLifecyclePolicy(y))};if(f)C.Properties.Tags=Object.entries(f).map(([T,v])=>({Key:T,Value:v}));return{repository:C,logicalId:b}}static generateLifecyclePolicy(a){let n=[];if(a.untaggedImageExpireDays!==void 0)n.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:a.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(a.maxImageCount!==void 0)n.push({rulePriority:n.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:a.maxImageCount},action:{type:"expire"}});if(a.maxImageAgeDays!==void 0)n.push({rulePriority:n.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:a.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:n}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(a){if(!a.Properties)a.Properties={};return a.Properties.ImageTagMutability="IMMUTABLE",a}static enableScanOnPush(a){if(!a.Properties)a.Properties={};return a.Properties.ImageScanningConfiguration={ScanOnPush:!0},a}static setLifecyclePolicy(a,n){if(!a.Properties)a.Properties={};return a.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Fe.generateLifecyclePolicy(n))},a}static addCrossAccountAccess(a,n){if(!a.Properties)a.Properties={};return a.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:n.map((i)=>`arn:aws:iam::${i}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},a}static addLambdaAccess(a){if(!a.Properties)a.Properties={};return a.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},a}static generateBunDockerfile(a){let{baseImage:n="oven/bun:1-debian",serverPath:i,port:s=3000,additionalDirs:c=[],healthCheckEndpoint:l="/health",nodeCompatible:u=!1,envVars:h={},buildCommands:y=[],runCommand:f}=a,S=["app","config",...c],b=f||`bun run ${i}`,C=`# Multi-stage build for Bun application
24
24
  # Generated by ts-cloud
25
25
 
26
26
  # Builder stage
@@ -74,7 +74,7 @@ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \\
74
74
 
75
75
  # Start application
76
76
  CMD ["bun", "run", "${i}"]
77
- `,C}static generateDockerBuildCommands(a){let{repositoryUri:n,tag:i="latest",dockerfilePath:s="Dockerfile",context:c=".",additionalTags:l=[],buildArgs:u={},platform:h="linux/amd64",noCache:y=!1}=a,f=`${n}:${i}`,S=[i,...l],b=`docker build -f ${s} -t ${f}`;if(h)b+=` --platform ${h}`;if(y)b+=" --no-cache";for(let[v,w]of Object.entries(u))b+=` --build-arg ${v}=${w}`;b+=` ${c}`;let C=S.slice(1).map((v)=>`docker tag ${f} ${n}:${v}`),T=S.map((v)=>`docker push ${n}:${v}`);return{build:b,tag:C,push:T,all:[b,...C,...T]}}static generateEcrLoginCommand(a,n){return`aws ecr get-login-password --region ${a} | docker login --username AWS --password-stdin ${n}.dkr.ecr.${a}.amazonaws.com`}static buildRepositoryUri(a){return`${a.accountId}.dkr.ecr.${a.region}.amazonaws.com/${a.repositoryName}`}static generateImageTags(a){let n=["latest"];if(a.version){n.push(a.version);let i=a.version.split(".");if(i.length>=2)n.push(`${i[0]}.${i[1]}`);if(i.length>=1)n.push(i[0])}if(a.gitSha)n.push(a.gitSha.substring(0,7)),n.push(a.gitSha);if(a.gitBranch){let i=a.gitBranch.replace(/[^a-zA-Z0-9.-]/g,"-").replace(/^-+|-+$/g,"");n.push(i)}if(a.environment)n.push(a.environment);if(a.timestamp){let i=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19);n.push(i)}return[...new Set(n)]}static DeploymentWorkflow={generateDeployScript:(a)=>{let n=Me.buildRepositoryUri({accountId:a.accountId,region:a.region,repositoryName:a.repositoryName}),i=a.tags||["latest"],s=i[0];return`#!/bin/bash
77
+ `,C}static generateDockerBuildCommands(a){let{repositoryUri:n,tag:i="latest",dockerfilePath:s="Dockerfile",context:c=".",additionalTags:l=[],buildArgs:u={},platform:h="linux/amd64",noCache:y=!1}=a,f=`${n}:${i}`,S=[i,...l],b=`docker build -f ${s} -t ${f}`;if(h)b+=` --platform ${h}`;if(y)b+=" --no-cache";for(let[v,w]of Object.entries(u))b+=` --build-arg ${v}=${w}`;b+=` ${c}`;let C=S.slice(1).map((v)=>`docker tag ${f} ${n}:${v}`),T=S.map((v)=>`docker push ${n}:${v}`);return{build:b,tag:C,push:T,all:[b,...C,...T]}}static generateEcrLoginCommand(a,n){return`aws ecr get-login-password --region ${a} | docker login --username AWS --password-stdin ${n}.dkr.ecr.${a}.amazonaws.com`}static buildRepositoryUri(a){return`${a.accountId}.dkr.ecr.${a.region}.amazonaws.com/${a.repositoryName}`}static generateImageTags(a){let n=["latest"];if(a.version){n.push(a.version);let i=a.version.split(".");if(i.length>=2)n.push(`${i[0]}.${i[1]}`);if(i.length>=1)n.push(i[0])}if(a.gitSha)n.push(a.gitSha.substring(0,7)),n.push(a.gitSha);if(a.gitBranch){let i=a.gitBranch.replace(/[^a-zA-Z0-9.-]/g,"-").replace(/^-+|-+$/g,"");n.push(i)}if(a.environment)n.push(a.environment);if(a.timestamp){let i=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19);n.push(i)}return[...new Set(n)]}static DeploymentWorkflow={generateDeployScript:(a)=>{let n=Fe.buildRepositoryUri({accountId:a.accountId,region:a.region,repositoryName:a.repositoryName}),i=a.tags||["latest"],s=i[0];return`#!/bin/bash
78
78
  set -e
79
79
 
80
80
  # Configuration
@@ -85,7 +85,7 @@ IMAGE_URI="${n}"
85
85
  DOCKERFILE="${a.dockerfilePath||"Dockerfile"}"
86
86
 
87
87
  echo "=== ECR Login ==="
88
- ${Me.generateEcrLoginCommand(a.region,a.accountId)}
88
+ ${Fe.generateEcrLoginCommand(a.region,a.accountId)}
89
89
 
90
90
  echo "=== Building Image ==="
91
91
  docker build -f $DOCKERFILE -t $IMAGE_URI:${s} --platform linux/amd64 .
@@ -103,7 +103,7 @@ echo "Image: $IMAGE_URI:${s}"
103
103
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
104
104
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest`},...a.ecsCluster&&a.ecsService?[{name:"Deploy to ECS",run:`aws ecs update-service --cluster ${a.ecsCluster} --service ${a.ecsService} --force-new-deployment`}]:[]]}}};return`# Generated by ts-cloud
105
105
  ${JSON.stringify(n,null,2).replace(/"/g,"").replace(/,\n/g,`
106
- `)}`}};static DockerfileTemplates={bunServer:(a,n=3000)=>Me.generateBunDockerfile({serverPath:a,port:n}),bunWithBuild:(a,n,i=3000)=>Me.generateBunDockerfile({serverPath:a,port:i,buildCommands:[n]}),bunFullStack:(a,n=3000)=>Me.generateBunDockerfile({serverPath:a,port:n,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(a,n=3000)=>Me.generateBunDockerfile({serverPath:a,port:n,healthCheckEndpoint:"/api/health"})}}class Ce{static createDistribution(a){let{slug:n,environment:i,origin:s,customDomain:c,certificateArn:l,errorPages:u,cachePolicy:h,edgeFunctions:y,http3:f=!1,comment:S}=a,b=r({slug:n,environment:i,resourceType:"cdn"}),C=t(b),T={Id:"DefaultOrigin",DomainName:s.domainName,OriginPath:s.originPath||""},v;if(s.type==="s3"){let R=`${C}OAC`;v={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${b}-oac`,Description:`Origin Access Control for ${b}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},T.OriginAccessControlId=N.Ref(R)}else if(s.type==="alb"||s.type==="custom")T.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let w={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:S||`CDN for ${b}`,DefaultRootObject:"index.html",Origins:[T],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:f?"http2and3":"http2"}}};if(c&&l)w.Properties.DistributionConfig.Aliases=[c],w.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:l,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(u&&u.length>0)w.Properties.DistributionConfig.CustomErrorResponses=u.map((R)=>({ErrorCode:R.errorCode,ResponseCode:R.responseCode,ResponsePagePath:R.responsePagePath}));if(y&&y.length>0)w.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=y.map((R)=>({EventType:R.event,LambdaFunctionARN:R.functionArn}));return{distribution:w,originAccessControl:v,logicalId:C}}static setCustomDomain(a,n,i){return a.Properties.DistributionConfig.Aliases=[n],a.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:i,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},a}static setErrorPages(a,n){return a.Properties.DistributionConfig.CustomErrorResponses=n.map((i)=>({ErrorCode:i.errorCode,ResponseCode:i.responseCode,ResponsePagePath:i.responsePagePath})),a}static enableHttp3(a){return a.Properties.DistributionConfig.HttpVersion="http2and3",a}static addEdgeFunction(a,n,i){if(!a.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)a.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return a.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:n,LambdaFunctionARN:i}),a}static setCachePolicy(a,n){return a.Properties.DistributionConfig.Comment=`${a.Properties.DistributionConfig.Comment||""} (TTL: ${n.default||86400}s)`,a}static createSpaDistribution(a){return Ce.createDistribution({...a,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(a){let{slug:n,environment:i}=a,s=r({slug:n,environment:i,resourceType:"edge-docs"}),c=t(s),l=t(`${s}-role`),u=t(`${s}-version`),h={Type:"AWS::IAM::Role",Properties:{RoleName:`${s}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},y=`
106
+ `)}`}};static DockerfileTemplates={bunServer:(a,n=3000)=>Fe.generateBunDockerfile({serverPath:a,port:n}),bunWithBuild:(a,n,i=3000)=>Fe.generateBunDockerfile({serverPath:a,port:i,buildCommands:[n]}),bunFullStack:(a,n=3000)=>Fe.generateBunDockerfile({serverPath:a,port:n,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(a,n=3000)=>Fe.generateBunDockerfile({serverPath:a,port:n,healthCheckEndpoint:"/api/health"})}}class Ce{static createDistribution(a){let{slug:n,environment:i,origin:s,customDomain:c,certificateArn:l,errorPages:u,cachePolicy:h,edgeFunctions:y,http3:f=!1,comment:S}=a,b=r({slug:n,environment:i,resourceType:"cdn"}),C=t(b),T={Id:"DefaultOrigin",DomainName:s.domainName,OriginPath:s.originPath||""},v;if(s.type==="s3"){let R=`${C}OAC`;v={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${b}-oac`,Description:`Origin Access Control for ${b}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},T.OriginAccessControlId=N.Ref(R)}else if(s.type==="alb"||s.type==="custom")T.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let w={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:S||`CDN for ${b}`,DefaultRootObject:"index.html",Origins:[T],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:f?"http2and3":"http2"}}};if(c&&l)w.Properties.DistributionConfig.Aliases=[c],w.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:l,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(u&&u.length>0)w.Properties.DistributionConfig.CustomErrorResponses=u.map((R)=>({ErrorCode:R.errorCode,ResponseCode:R.responseCode,ResponsePagePath:R.responsePagePath}));if(y&&y.length>0)w.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=y.map((R)=>({EventType:R.event,LambdaFunctionARN:R.functionArn}));return{distribution:w,originAccessControl:v,logicalId:C}}static setCustomDomain(a,n,i){return a.Properties.DistributionConfig.Aliases=[n],a.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:i,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},a}static setErrorPages(a,n){return a.Properties.DistributionConfig.CustomErrorResponses=n.map((i)=>({ErrorCode:i.errorCode,ResponseCode:i.responseCode,ResponsePagePath:i.responsePagePath})),a}static enableHttp3(a){return a.Properties.DistributionConfig.HttpVersion="http2and3",a}static addEdgeFunction(a,n,i){if(!a.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)a.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return a.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:n,LambdaFunctionARN:i}),a}static setCachePolicy(a,n){return a.Properties.DistributionConfig.Comment=`${a.Properties.DistributionConfig.Comment||""} (TTL: ${n.default||86400}s)`,a}static createSpaDistribution(a){return Ce.createDistribution({...a,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(a){let{slug:n,environment:i}=a,s=r({slug:n,environment:i,resourceType:"edge-docs"}),c=t(s),l=t(`${s}-role`),u=t(`${s}-version`),h={Type:"AWS::IAM::Role",Properties:{RoleName:`${s}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},y=`
107
107
  'use strict';
108
108
 
109
109
  exports.handler = async (event) => {
@@ -209,7 +209,7 @@ exports.handler = async (event) => {
209
209
 
210
210
  return request;
211
211
  };
212
- `.trim()};static Config={ttl:(a)=>{let{min:n=0,max:i=86400,default:s=86400}=a;return{MinTTL:n,MaxTTL:i,DefaultTTL:s}},cookies:(a,n)=>{let i={Forward:a==="allowList"?"whitelist":a};if(a==="allowList"&&n)i.WhitelistedNames=n;return i},allowedMethods:(a)=>{let n={ALL:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return n[a]||n.GET_HEAD},cachedMethods:(a)=>{let n={GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return n[a]||n.GET_HEAD},ttlPresets:{static:{min:0,max:31536000,default:31536000},dynamic:{min:0,max:0,default:0},api:{min:0,max:3600,default:60},html:{min:0,max:86400,default:86400},images:{min:0,max:604800,default:604800}},cacheBehavior:(a)=>{let{ttl:n={min:0,max:86400,default:86400},cookies:i="none",allowedCookies:s,allowedMethods:c="GET_HEAD",cachedMethods:l="GET_HEAD",compress:u=!0,forwardQueryString:h=!0,forwardHeaders:y=[]}=a;return{MinTTL:n.min,MaxTTL:n.max,DefaultTTL:n.default,Compress:u,AllowedMethods:Ce.Config.allowedMethods(c),CachedMethods:Ce.Config.cachedMethods(l),ForwardedValues:{QueryString:h,Headers:y,Cookies:Ce.Config.cookies(i,s)}}}};static applyConfig(a,n){let i=a.Properties.DistributionConfig.DefaultCacheBehavior;if(n.ttl)i.MinTTL=n.ttl.min,i.MaxTTL=n.ttl.max,i.DefaultTTL=n.ttl.default;if(n.compress!==void 0)i.Compress=n.compress;if(n.allowedMethods)i.AllowedMethods=Ce.Config.allowedMethods(n.allowedMethods);if(n.cachedMethods)i.CachedMethods=Ce.Config.cachedMethods(n.cachedMethods);if(n.cookies){if(!i.ForwardedValues)i.ForwardedValues={QueryString:!0};i.ForwardedValues.Cookies=Ce.Config.cookies(n.cookies,n.allowedCookies)}return a}}class L{static createHostedZone(a){let{domain:n,slug:i,environment:s,comment:c}=a,l=r({slug:i,environment:s,resourceType:"hostedzone"}),u=t(`${l}-${n.replace(/\./g,"")}`);return{zone:{Type:"AWS::Route53::HostedZone",Properties:{Name:n,HostedZoneConfig:{Comment:c||`Hosted zone for ${n}`}}},logicalId:u}}static createRecord(a){let{hostedZoneId:n,hostedZoneName:i,name:s,type:c,ttl:l,values:u,aliasTarget:h}=a,y=t(`record-${s.replace(/\./g,"")}-${c}`),f={Type:"AWS::Route53::RecordSet",Properties:{Name:s,Type:c}};if(n)f.Properties.HostedZoneId=n;else if(i)f.Properties.HostedZoneName=i;if(h)f.Properties.AliasTarget={DNSName:h.dnsName,HostedZoneId:h.hostedZoneId,EvaluateTargetHealth:h.evaluateTargetHealth??!1};else f.Properties.TTL=l||300,f.Properties.ResourceRecords=u||[];return{record:f,logicalId:y}}static createCloudFrontAlias(a,n,i){return L.createRecord({hostedZoneId:i,name:a,type:"A",aliasTarget:{dnsName:n,hostedZoneId:"Z2FDTNDATAQYW2",evaluateTargetHealth:!1}})}static createAlbAlias(a,n,i,s){return L.createRecord({hostedZoneId:s,name:a,type:"A",aliasTarget:{dnsName:n,hostedZoneId:i,evaluateTargetHealth:!0}})}static createCname(a,n,i,s=300){return L.createRecord({hostedZoneId:i,name:a,type:"CNAME",ttl:s,values:[n]})}static createWwwRedirect(a,n){return L.createRecord({hostedZoneId:n,name:`www.${a}`,type:"CNAME",ttl:300,values:[a]})}static createMxRecords(a,n,i,s=300){return L.createRecord({hostedZoneId:i,name:a,type:"MX",ttl:s,values:n.map((c)=>`${c.priority} ${c.server}`)})}static createTxtRecord(a,n,i,s=300){return L.createRecord({hostedZoneId:i,name:a,type:"TXT",ttl:s,values:[`"${n}"`]})}static createSpfRecord(a,n,i){return L.createTxtRecord(a,n,i)}static createDmarcRecord(a,n,i,s){let c=`v=DMARC1; p=${n}; rua=mailto:${i}`;return L.createTxtRecord(`_dmarc.${a}`,c,s)}static createS3WebsiteAlias(a,n,i,s){return L.createRecord({hostedZoneId:s,name:a,type:"A",aliasTarget:{dnsName:n,hostedZoneId:i,evaluateTargetHealth:!1}})}static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","af-south-1":"Z83WF9RJE8B12","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-south-2":"Z02976202B4EZMXIPMXF7","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIBER6CPFUU","ap-southeast-3":"Z01613992JD795ZI93075","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-central-2":"Z030506016YDQGETNASS","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","eu-south-1":"Z30OZKI7KPW7MI","eu-south-2":"Z0081959F7139GRJC19J","me-south-1":"Z1MPMWCPA7YB62","me-central-1":"Z06143092I8HRBER9VXCO","sa-east-1":"Z7KQH4QJS55SO"};static getS3WebsiteEndpoint(a,n){return`${a}.s3-website-${n}.amazonaws.com`}static createStoreRecord(a,n,i){return L.createCname(`store.${a}`,n,i)}static createApiRecord(a,n,i){return L.createCname(`api.${a}`,n,i)}static createDocsRecord(a,n,i){return L.createCname(`docs.${a}`,n,i)}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2"}class I{static createCertificate(a){let{domain:n,subdomains:i=[],slug:s,environment:c,validationMethod:l="DNS",hostedZoneId:u}=a,h=r({slug:s,environment:c,resourceType:"acm"}),y=t(`${h}-${n.replace(/\./g,"")}`),f=[n];for(let b of i)if(b==="*")f.push(`*.${n}`);else f.push(`${b}.${n}`);let S={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:n,SubjectAlternativeNames:f,ValidationMethod:l}};if(l==="DNS"&&u)S.Properties.DomainValidationOptions=f.map((b)=>({DomainName:b,HostedZoneId:u}));return{certificate:S,logicalId:y}}static createKmsKey(a){let{description:n,slug:i,environment:s,enableRotation:c=!0,multiRegion:l=!1}=a,u=r({slug:i,environment:s,resourceType:"kms"}),h=t(u),y={Version:"2012-10-17",Statement:[{Sid:"Enable IAM User Permissions",Effect:"Allow",Principal:{AWS:N.Sub("arn:aws:iam::${AWS::AccountId}:root")},Action:"kms:*",Resource:"*"},{Sid:"Allow services to use the key",Effect:"Allow",Principal:{Service:["s3.amazonaws.com","cloudfront.amazonaws.com","logs.amazonaws.com","secretsmanager.amazonaws.com"]},Action:["kms:Decrypt","kms:GenerateDataKey"],Resource:"*"}]},f={Type:"AWS::KMS::Key",Properties:{Description:n,Enabled:!0,EnableKeyRotation:c,KeyPolicy:y,KeySpec:"SYMMETRIC_DEFAULT",KeyUsage:"ENCRYPT_DECRYPT",MultiRegion:l}},S=t(`${u}-alias`),b={Type:"AWS::KMS::Alias",Properties:{AliasName:`alias/${i}-${s}`,TargetKeyId:N.Ref(h)}};return{key:f,alias:b,logicalId:h,aliasId:S}}static createFirewall(a){let{slug:n,environment:i,scope:s="CLOUDFRONT",defaultAction:c="allow"}=a,l=r({slug:n,environment:i,resourceType:"waf"}),u=t(l);return{webAcl:{Type:"AWS::WAFv2::WebACL",Properties:{Name:l,Scope:s,DefaultAction:c==="allow"?{Allow:{}}:{Block:{}},Description:`WAF for ${n} ${i}`,Rules:[],VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${l}-metric`}}},logicalId:u}}static setRateLimit(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{RateBasedStatement:{Limit:n.requestsPerWindow,AggregateKeyType:n.aggregateKeyType||"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static blockCountries(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{GeoMatchStatement:{CountryCodes:n.countryCodes}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static blockIpAddresses(a,n,i,s){let c=r({slug:i,environment:s,resourceType:"ipset"}),l=t(`${c}-${n.name}`),u={Type:"AWS::WAFv2::IPSet",Properties:{Name:`${c}-${n.name}`,Scope:a.Properties.Scope,IPAddressVersion:n.ipVersion||"IPV4",Addresses:n.ipAddresses,Description:`Blocked IPs for ${n.name}`}};if(!a.Properties.Rules)a.Properties.Rules=[];return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{IPSetReferenceStatement:{Arn:N.GetAtt(l,"Arn")}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),{webAcl:a,ipSet:u,ipSetLogicalId:l}}static addManagedRules(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];let i={ManagedRuleGroupStatement:{VendorName:n.vendorName,Name:n.ruleName}};if(n.excludedRules&&n.excludedRules.length>0)i.ManagedRuleGroupStatement.ExcludedRules=n.excludedRules.map((s)=>({Name:s}));return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:i,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static ManagedRuleGroups={CoreRuleSet:{vendorName:"AWS",ruleName:"AWSManagedRulesCommonRuleSet"},KnownBadInputs:{vendorName:"AWS",ruleName:"AWSManagedRulesKnownBadInputsRuleSet"},SqlDatabase:{vendorName:"AWS",ruleName:"AWSManagedRulesSQLiRuleSet"},LinuxOS:{vendorName:"AWS",ruleName:"AWSManagedRulesLinuxRuleSet"},PosixOS:{vendorName:"AWS",ruleName:"AWSManagedRulesUnixRuleSet"},AmazonIpReputation:{vendorName:"AWS",ruleName:"AWSManagedRulesAmazonIpReputationList"},AnonymousIpList:{vendorName:"AWS",ruleName:"AWSManagedRulesAnonymousIpList"},BotControl:{vendorName:"AWS",ruleName:"AWSManagedRulesBotControlRuleSet"}};static setPathRateLimit(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];let i=n.paths.map((s)=>({SearchString:s,FieldToMatch:{UriPath:{}},TextTransformation:[{Priority:0,Type:"LOWERCASE"}],PositionalConstraint:"STARTS_WITH"}));return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{RateBasedStatement:{Limit:n.requestsPerWindow,AggregateKeyType:n.aggregateKeyType||"IP",ScopeDownStatement:{OrStatement:{Statements:i.map((s)=>({ByteMatchStatement:s}))}}}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static setHeaderRateLimit(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];let i={RateBasedStatement:{Limit:n.requestsPerWindow,AggregateKeyType:"CUSTOM_KEYS",CustomKeys:[{Header:{Name:n.headerName,TextTransformations:[{Priority:0,Type:"NONE"}]}}]}};if(n.headerValue)i.RateBasedStatement.ScopeDownStatement={ByteMatchStatement:{SearchString:n.headerValue,FieldToMatch:{SingleHeader:{Name:n.headerName}},TextTransformation:[{Priority:0,Type:"NONE"}],PositionalConstraint:"EXACTLY"}};return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:i,Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static protectLoginEndpoint(a,n){let{loginPaths:i,priority:s,requestsPerMinute:c=10}=n;return I.setPathRateLimit(a,{name:"LoginRateLimit",priority:s,requestsPerWindow:c*5,paths:i}),a}static protectApiEndpoints(a,n){let{apiPaths:i,priority:s,requestsPerMinute:c=100}=n;return I.setPathRateLimit(a,{name:"ApiRateLimit",priority:s,requestsPerWindow:c*5,paths:i}),a}static createProtectedFirewall(a){let{slug:n,environment:i,scope:s="CLOUDFRONT",enableBotControl:c=!1,enableRateLimiting:l=!0,rateLimitPerMinute:u=2000}=a,{webAcl:h,logicalId:y}=I.createFirewall({slug:n,environment:i,scope:s,defaultAction:"allow"}),f=0;if(h=I.addManagedRules(h,{name:"AWSIPReputationList",priority:f++,...I.ManagedRuleGroups.AmazonIpReputation}),h=I.addManagedRules(h,{name:"AWSAnonymousIPList",priority:f++,...I.ManagedRuleGroups.AnonymousIpList}),h=I.addManagedRules(h,{name:"AWSCoreRuleSet",priority:f++,...I.ManagedRuleGroups.CoreRuleSet}),h=I.addManagedRules(h,{name:"AWSKnownBadInputs",priority:f++,...I.ManagedRuleGroups.KnownBadInputs}),h=I.addManagedRules(h,{name:"AWSSQLi",priority:f++,...I.ManagedRuleGroups.SqlDatabase}),c)h=I.addManagedRules(h,{name:"AWSBotControl",priority:f++,...I.ManagedRuleGroups.BotControl});if(l)h=I.setRateLimit(h,{name:"GlobalRateLimit",priority:f++,requestsPerWindow:u*5});return{webAcl:h,logicalId:y}}static RateLimitPresets={STANDARD:2000,HIGH_TRAFFIC:1e4,STRICT:100,LOGIN:10,API:100}}class o{static createServer(a){let{slug:n,environment:i,instanceType:s="t3.micro",imageId:c="ami-0f3caa1cf4417e51b",keyName:l,securityGroupIds:u,subnetId:h,userData:y,volumeSize:f=20,volumeType:S="gp3",encrypted:b=!0}=a,C=r({slug:n,environment:i,resourceType:"ec2"}),T=t(C),v={Type:"AWS::EC2::Instance",Properties:{ImageId:c,InstanceType:s,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:i}]}};if(l)v.Properties.KeyName=l;if(u)v.Properties.SecurityGroupIds=u;if(h)v.Properties.SubnetId=h;if(y)v.Properties.UserData=N.Base64(y);return v.Properties.BlockDeviceMappings=[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:f,VolumeType:S,Encrypted:b,DeleteOnTermination:!0}}],{instance:v,logicalId:T}}static createSecurityGroup(a){let{slug:n,environment:i,vpcId:s,description:c,ingress:l=[],egress:u=[]}=a,h=r({slug:n,environment:i,resourceType:"sg"}),y=t(h),f={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:c||`Security group for ${n} ${i}`,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(s)f.Properties.VpcId=s;if(l.length>0)f.Properties.SecurityGroupIngress=l.map((S)=>({IpProtocol:S.protocol,FromPort:S.fromPort,ToPort:S.toPort,CidrIp:S.cidr,SourceSecurityGroupId:S.sourceSecurityGroupId}));if(u.length>0)f.Properties.SecurityGroupEgress=u.map((S)=>({IpProtocol:S.protocol,FromPort:S.fromPort,ToPort:S.toPort,CidrIp:S.cidr,DestinationSecurityGroupId:S.sourceSecurityGroupId}));return{securityGroup:f,logicalId:y}}static createWebServerSecurityGroup(a,n,i){return o.createSecurityGroup({slug:a,environment:n,vpcId:i,description:"Security group for web servers - HTTP, HTTPS, SSH",ingress:[{protocol:"tcp",fromPort:80,toPort:80,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:443,toPort:443,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:22,toPort:22,cidr:"0.0.0.0/0"}],egress:[{protocol:"-1",fromPort:0,toPort:0,cidr:"0.0.0.0/0"}]})}static createLoadBalancer(a){let{slug:n,environment:i,scheme:s="internet-facing",subnets:c,securityGroups:l,type:u="application"}=a,h=r({slug:n,environment:i,resourceType:"alb"}),y=t(h),f={Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:h,Scheme:s,Type:u,Subnets:c,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(l)f.Properties.SecurityGroups=l;return{loadBalancer:f,logicalId:y}}static createTargetGroup(a){let{slug:n,environment:i,port:s,protocol:c="HTTP",vpcId:l,targetType:u="ip",healthCheckPath:h="/",healthCheckInterval:y=30,healthCheckTimeout:f=5,healthyThreshold:S=2,unhealthyThreshold:b=3}=a,C=r({slug:n,environment:i,resourceType:"tg"}),T=t(C);return{targetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:C,Port:s,Protocol:c,VpcId:l,TargetType:u,HealthCheckEnabled:!0,HealthCheckProtocol:c,HealthCheckPath:h,HealthCheckIntervalSeconds:y,HealthCheckTimeoutSeconds:f,HealthyThresholdCount:S,UnhealthyThresholdCount:b,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:i}]}},logicalId:T}}static createListener(a,n){let{port:i,protocol:s="HTTP",certificateArn:c,defaultTargetGroupArn:l}=n,u=t(`listener-${a}-${i}`),h={Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:N.Ref(a),Port:i,Protocol:s,DefaultActions:[{Type:"forward",TargetGroupArn:l}]}};if(s==="HTTPS"&&c)h.Properties.Certificates=[{CertificateArn:c}],h.Properties.SslPolicy="ELBSecurityPolicy-TLS13-1-2-2021-06";return{listener:h,logicalId:u}}static createEcsCluster(a,n){let i=r({slug:a,environment:n,resourceType:"ecs-cluster"}),s=t(i);return{cluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:i,Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:n}]}},logicalId:s}}static createFargateService(a){let{slug:n,environment:i,image:s,cpu:c="256",memory:l="512",desiredCount:u=1,containerPort:h=8080,environmentVariables:y={},secrets:f=[],healthCheck:S,logGroup:b,subnets:C,securityGroups:T,targetGroupArn:v}=a,{cluster:w,logicalId:R}=o.createEcsCluster(n,i),k=r({slug:n,environment:i,resourceType:"fargate"}),W=t(`${k}-execution-role`),P={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"]}},V=t(`${k}-task-role`),B={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]}}},j=t(`${k}-task`),Z={Type:"AWS::ECS::TaskDefinition",Properties:{Family:k,TaskRoleArn:N.GetAtt(V,"Arn"),ExecutionRoleArn:N.GetAtt(W,"Arn"),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:c,Memory:l,ContainerDefinitions:[{Name:n,Image:s,Essential:!0,PortMappings:[{ContainerPort:h,Protocol:"tcp"}],Environment:Object.entries(y).map(([te,ie])=>({Name:te,Value:ie})),Secrets:f.map((te)=>({Name:te.name,ValueFrom:te.valueFrom}))}],Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:i}]}};if(S)Z.Properties.ContainerDefinitions[0].HealthCheck={Command:S.command,Interval:S.interval||30,Timeout:S.timeout||5,Retries:S.retries||3,StartPeriod:60};if(b)Z.Properties.ContainerDefinitions[0].LogConfiguration={LogDriver:"awslogs",Options:{"awslogs-group":b,"awslogs-region":N.Ref("AWS::Region"),"awslogs-stream-prefix":n}};let K=t(`${k}-service`),ee={Type:"AWS::ECS::Service",Properties:{ServiceName:k,Cluster:N.Ref(R),TaskDefinition:N.Ref(j),DesiredCount:u,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{Subnets:C,SecurityGroups:T,AssignPublicIp:"ENABLED"}},Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:i}]}};if(v)ee.Properties.LoadBalancers=[{TargetGroupArn:v,ContainerName:n,ContainerPort:h}];return{cluster:w,taskDefinition:Z,service:ee,taskRole:B,executionRole:P,clusterLogicalId:R,taskDefinitionLogicalId:j,serviceLogicalId:K,taskRoleLogicalId:V,executionRoleLogicalId:W}}static createLambdaFunction(a){let{slug:n,environment:i,runtime:s,handler:c,code:l,timeout:u=30,memorySize:h=128,environmentVariables:y={},vpcConfig:f}=a,S=r({slug:n,environment:i,resourceType:"lambda"}),b=t(S),C=t(`${S}-role`),T={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}};if(f)T.Properties.ManagedPolicyArns.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");let v={Type:"AWS::Lambda::Function",Properties:{FunctionName:S,Runtime:s,Role:N.GetAtt(C,"Arn"),Handler:c,Code:{...l.s3Bucket&&{S3Bucket:l.s3Bucket},...l.s3Key&&{S3Key:l.s3Key},...l.zipFile&&{ZipFile:l.zipFile}},Timeout:u,MemorySize:h,Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:i}]}};if(Object.keys(y).length>0)v.Properties.Environment={Variables:y};if(f)v.Properties.VpcConfig={SecurityGroupIds:f.securityGroupIds,SubnetIds:f.subnetIds};return{lambdaFunction:v,role:T,logicalId:b,roleLogicalId:C}}static generateNodeServerUserData(a={}){let{nodeVersion:n="20",appRepo:i,environment:s={}}=a,c=Object.entries(s).map(([l,u])=>`echo "export ${l}='${u}'" >> /etc/environment`).join(`
212
+ `.trim()};static Config={ttl:(a)=>{let{min:n=0,max:i=86400,default:s=86400}=a;return{MinTTL:n,MaxTTL:i,DefaultTTL:s}},cookies:(a,n)=>{let i={Forward:a==="allowList"?"whitelist":a};if(a==="allowList"&&n)i.WhitelistedNames=n;return i},allowedMethods:(a)=>{let n={ALL:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return n[a]||n.GET_HEAD},cachedMethods:(a)=>{let n={GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return n[a]||n.GET_HEAD},ttlPresets:{static:{min:0,max:31536000,default:31536000},dynamic:{min:0,max:0,default:0},api:{min:0,max:3600,default:60},html:{min:0,max:86400,default:86400},images:{min:0,max:604800,default:604800}},cacheBehavior:(a)=>{let{ttl:n={min:0,max:86400,default:86400},cookies:i="none",allowedCookies:s,allowedMethods:c="GET_HEAD",cachedMethods:l="GET_HEAD",compress:u=!0,forwardQueryString:h=!0,forwardHeaders:y=[]}=a;return{MinTTL:n.min,MaxTTL:n.max,DefaultTTL:n.default,Compress:u,AllowedMethods:Ce.Config.allowedMethods(c),CachedMethods:Ce.Config.cachedMethods(l),ForwardedValues:{QueryString:h,Headers:y,Cookies:Ce.Config.cookies(i,s)}}}};static applyConfig(a,n){let i=a.Properties.DistributionConfig.DefaultCacheBehavior;if(n.ttl)i.MinTTL=n.ttl.min,i.MaxTTL=n.ttl.max,i.DefaultTTL=n.ttl.default;if(n.compress!==void 0)i.Compress=n.compress;if(n.allowedMethods)i.AllowedMethods=Ce.Config.allowedMethods(n.allowedMethods);if(n.cachedMethods)i.CachedMethods=Ce.Config.cachedMethods(n.cachedMethods);if(n.cookies){if(!i.ForwardedValues)i.ForwardedValues={QueryString:!0};i.ForwardedValues.Cookies=Ce.Config.cookies(n.cookies,n.allowedCookies)}return a}}class L{static createHostedZone(a){let{domain:n,slug:i,environment:s,comment:c}=a,l=r({slug:i,environment:s,resourceType:"hostedzone"}),u=t(`${l}-${n.replace(/\./g,"")}`);return{zone:{Type:"AWS::Route53::HostedZone",Properties:{Name:n,HostedZoneConfig:{Comment:c||`Hosted zone for ${n}`}}},logicalId:u}}static createRecord(a){let{hostedZoneId:n,hostedZoneName:i,name:s,type:c,ttl:l,values:u,aliasTarget:h}=a,y=t(`record-${s.replace(/\./g,"")}-${c}`),f={Type:"AWS::Route53::RecordSet",Properties:{Name:s,Type:c}};if(n)f.Properties.HostedZoneId=n;else if(i)f.Properties.HostedZoneName=i;if(h)f.Properties.AliasTarget={DNSName:h.dnsName,HostedZoneId:h.hostedZoneId,EvaluateTargetHealth:h.evaluateTargetHealth??!1};else f.Properties.TTL=l||300,f.Properties.ResourceRecords=u||[];return{record:f,logicalId:y}}static createCloudFrontAlias(a,n,i){return L.createRecord({hostedZoneId:i,name:a,type:"A",aliasTarget:{dnsName:n,hostedZoneId:"Z2FDTNDATAQYW2",evaluateTargetHealth:!1}})}static createAlbAlias(a,n,i,s){return L.createRecord({hostedZoneId:s,name:a,type:"A",aliasTarget:{dnsName:n,hostedZoneId:i,evaluateTargetHealth:!0}})}static createCname(a,n,i,s=300){return L.createRecord({hostedZoneId:i,name:a,type:"CNAME",ttl:s,values:[n]})}static createWwwRedirect(a,n){return L.createRecord({hostedZoneId:n,name:`www.${a}`,type:"CNAME",ttl:300,values:[a]})}static createMxRecords(a,n,i,s=300){return L.createRecord({hostedZoneId:i,name:a,type:"MX",ttl:s,values:n.map((c)=>`${c.priority} ${c.server}`)})}static createTxtRecord(a,n,i,s=300){return L.createRecord({hostedZoneId:i,name:a,type:"TXT",ttl:s,values:[`"${n}"`]})}static createSpfRecord(a,n,i){return L.createTxtRecord(a,n,i)}static createDmarcRecord(a,n,i,s){let c=`v=DMARC1; p=${n}; rua=mailto:${i}`;return L.createTxtRecord(`_dmarc.${a}`,c,s)}static createS3WebsiteAlias(a,n,i,s){return L.createRecord({hostedZoneId:s,name:a,type:"A",aliasTarget:{dnsName:n,hostedZoneId:i,evaluateTargetHealth:!1}})}static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","af-south-1":"Z83WF9RJE8B12","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-south-2":"Z02976202B4EZMXIPMXF7","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIBER6CPFUU","ap-southeast-3":"Z01613992JD795ZI93075","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-central-2":"Z030506016YDQGETNASS","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","eu-south-1":"Z30OZKI7KPW7MI","eu-south-2":"Z0081959F7139GRJC19J","me-south-1":"Z1MPMWCPA7YB62","me-central-1":"Z06143092I8HRBER9VXCO","sa-east-1":"Z7KQH4QJS55SO"};static getS3WebsiteEndpoint(a,n){return`${a}.s3-website-${n}.amazonaws.com`}static createStoreRecord(a,n,i){return L.createCname(`store.${a}`,n,i)}static createApiRecord(a,n,i){return L.createCname(`api.${a}`,n,i)}static createDocsRecord(a,n,i){return L.createCname(`docs.${a}`,n,i)}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2"}class I{static createCertificate(a){let{domain:n,subdomains:i=[],slug:s,environment:c,validationMethod:l="DNS",hostedZoneId:u}=a,h=r({slug:s,environment:c,resourceType:"acm"}),y=t(`${h}-${n.replace(/\./g,"")}`),f=[n];for(let b of i)if(b==="*")f.push(`*.${n}`);else f.push(`${b}.${n}`);let S={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:n,SubjectAlternativeNames:f,ValidationMethod:l}};if(l==="DNS"&&u)S.Properties.DomainValidationOptions=f.map((b)=>({DomainName:b,HostedZoneId:u}));return{certificate:S,logicalId:y}}static createKmsKey(a){let{description:n,slug:i,environment:s,enableRotation:c=!0,multiRegion:l=!1}=a,u=r({slug:i,environment:s,resourceType:"kms"}),h=t(u),y={Version:"2012-10-17",Statement:[{Sid:"Enable IAM User Permissions",Effect:"Allow",Principal:{AWS:N.Sub("arn:aws:iam::${AWS::AccountId}:root")},Action:"kms:*",Resource:"*"},{Sid:"Allow services to use the key",Effect:"Allow",Principal:{Service:["s3.amazonaws.com","cloudfront.amazonaws.com","logs.amazonaws.com","secretsmanager.amazonaws.com"]},Action:["kms:Decrypt","kms:GenerateDataKey"],Resource:"*"}]},f={Type:"AWS::KMS::Key",Properties:{Description:n,Enabled:!0,EnableKeyRotation:c,KeyPolicy:y,KeySpec:"SYMMETRIC_DEFAULT",KeyUsage:"ENCRYPT_DECRYPT",MultiRegion:l}},S=t(`${u}-alias`),b={Type:"AWS::KMS::Alias",Properties:{AliasName:`alias/${i}-${s}`,TargetKeyId:N.Ref(h)}};return{key:f,alias:b,logicalId:h,aliasId:S}}static createFirewall(a){let{slug:n,environment:i,scope:s="CLOUDFRONT",defaultAction:c="allow"}=a,l=r({slug:n,environment:i,resourceType:"waf"}),u=t(l);return{webAcl:{Type:"AWS::WAFv2::WebACL",Properties:{Name:l,Scope:s,DefaultAction:c==="allow"?{Allow:{}}:{Block:{}},Description:`WAF for ${n} ${i}`,Rules:[],VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${l}-metric`}}},logicalId:u}}static setRateLimit(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{RateBasedStatement:{Limit:n.requestsPerWindow,AggregateKeyType:n.aggregateKeyType||"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static blockCountries(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{GeoMatchStatement:{CountryCodes:n.countryCodes}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static blockIpAddresses(a,n,i,s){let c=r({slug:i,environment:s,resourceType:"ipset"}),l=t(`${c}-${n.name}`),u={Type:"AWS::WAFv2::IPSet",Properties:{Name:`${c}-${n.name}`,Scope:a.Properties.Scope,IPAddressVersion:n.ipVersion||"IPV4",Addresses:n.ipAddresses,Description:`Blocked IPs for ${n.name}`}};if(!a.Properties.Rules)a.Properties.Rules=[];return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{IPSetReferenceStatement:{Arn:N.GetAtt(l,"Arn")}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),{webAcl:a,ipSet:u,ipSetLogicalId:l}}static addManagedRules(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];let i={ManagedRuleGroupStatement:{VendorName:n.vendorName,Name:n.ruleName}};if(n.excludedRules&&n.excludedRules.length>0)i.ManagedRuleGroupStatement.ExcludedRules=n.excludedRules.map((s)=>({Name:s}));return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:i,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static ManagedRuleGroups={CoreRuleSet:{vendorName:"AWS",ruleName:"AWSManagedRulesCommonRuleSet"},KnownBadInputs:{vendorName:"AWS",ruleName:"AWSManagedRulesKnownBadInputsRuleSet"},SqlDatabase:{vendorName:"AWS",ruleName:"AWSManagedRulesSQLiRuleSet"},LinuxOS:{vendorName:"AWS",ruleName:"AWSManagedRulesLinuxRuleSet"},PosixOS:{vendorName:"AWS",ruleName:"AWSManagedRulesUnixRuleSet"},AmazonIpReputation:{vendorName:"AWS",ruleName:"AWSManagedRulesAmazonIpReputationList"},AnonymousIpList:{vendorName:"AWS",ruleName:"AWSManagedRulesAnonymousIpList"},BotControl:{vendorName:"AWS",ruleName:"AWSManagedRulesBotControlRuleSet"}};static setPathRateLimit(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];let i=n.paths.map((s)=>({SearchString:s,FieldToMatch:{UriPath:{}},TextTransformation:[{Priority:0,Type:"LOWERCASE"}],PositionalConstraint:"STARTS_WITH"}));return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:{RateBasedStatement:{Limit:n.requestsPerWindow,AggregateKeyType:n.aggregateKeyType||"IP",ScopeDownStatement:{OrStatement:{Statements:i.map((s)=>({ByteMatchStatement:s}))}}}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static setHeaderRateLimit(a,n){if(!a.Properties.Rules)a.Properties.Rules=[];let i={RateBasedStatement:{Limit:n.requestsPerWindow,AggregateKeyType:"CUSTOM_KEYS",CustomKeys:[{Header:{Name:n.headerName,TextTransformations:[{Priority:0,Type:"NONE"}]}}]}};if(n.headerValue)i.RateBasedStatement.ScopeDownStatement={ByteMatchStatement:{SearchString:n.headerValue,FieldToMatch:{SingleHeader:{Name:n.headerName}},TextTransformation:[{Priority:0,Type:"NONE"}],PositionalConstraint:"EXACTLY"}};return a.Properties.Rules.push({Name:n.name,Priority:n.priority,Statement:i,Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${n.name}-metric`}}),a}static protectLoginEndpoint(a,n){let{loginPaths:i,priority:s,requestsPerMinute:c=10}=n;return I.setPathRateLimit(a,{name:"LoginRateLimit",priority:s,requestsPerWindow:c*5,paths:i}),a}static protectApiEndpoints(a,n){let{apiPaths:i,priority:s,requestsPerMinute:c=100}=n;return I.setPathRateLimit(a,{name:"ApiRateLimit",priority:s,requestsPerWindow:c*5,paths:i}),a}static createProtectedFirewall(a){let{slug:n,environment:i,scope:s="CLOUDFRONT",enableBotControl:c=!1,enableRateLimiting:l=!0,rateLimitPerMinute:u=2000}=a,{webAcl:h,logicalId:y}=I.createFirewall({slug:n,environment:i,scope:s,defaultAction:"allow"}),f=0;if(h=I.addManagedRules(h,{name:"AWSIPReputationList",priority:f++,...I.ManagedRuleGroups.AmazonIpReputation}),h=I.addManagedRules(h,{name:"AWSAnonymousIPList",priority:f++,...I.ManagedRuleGroups.AnonymousIpList}),h=I.addManagedRules(h,{name:"AWSCoreRuleSet",priority:f++,...I.ManagedRuleGroups.CoreRuleSet}),h=I.addManagedRules(h,{name:"AWSKnownBadInputs",priority:f++,...I.ManagedRuleGroups.KnownBadInputs}),h=I.addManagedRules(h,{name:"AWSSQLi",priority:f++,...I.ManagedRuleGroups.SqlDatabase}),c)h=I.addManagedRules(h,{name:"AWSBotControl",priority:f++,...I.ManagedRuleGroups.BotControl});if(l)h=I.setRateLimit(h,{name:"GlobalRateLimit",priority:f++,requestsPerWindow:u*5});return{webAcl:h,logicalId:y}}static RateLimitPresets={STANDARD:2000,HIGH_TRAFFIC:1e4,STRICT:100,LOGIN:10,API:100}}class o{static createServer(a){let{slug:n,environment:i,instanceType:s="t3.micro",imageId:c="ami-0f3caa1cf4417e51b",keyName:l,securityGroupIds:u,subnetId:h,userData:y,volumeSize:f=20,volumeType:S="gp3",encrypted:b=!0}=a,C=r({slug:n,environment:i,resourceType:"ec2"}),T=t(C),v={Type:"AWS::EC2::Instance",Properties:{ImageId:c,InstanceType:s,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:i}]}};if(l)v.Properties.KeyName=l;if(u)v.Properties.SecurityGroupIds=u;if(h)v.Properties.SubnetId=h;if(y)v.Properties.UserData=N.Base64(y);return v.Properties.BlockDeviceMappings=[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:f,VolumeType:S,Encrypted:b,DeleteOnTermination:!0}}],{instance:v,logicalId:T}}static createSecurityGroup(a){let{slug:n,environment:i,vpcId:s,description:c,ingress:l=[],egress:u=[]}=a,h=r({slug:n,environment:i,resourceType:"sg"}),y=t(h),f={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:c||`Security group for ${n} ${i}`,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(s)f.Properties.VpcId=s;if(l.length>0)f.Properties.SecurityGroupIngress=l.map((S)=>({IpProtocol:S.protocol,FromPort:S.fromPort,ToPort:S.toPort,CidrIp:S.cidr,SourceSecurityGroupId:S.sourceSecurityGroupId}));if(u.length>0)f.Properties.SecurityGroupEgress=u.map((S)=>({IpProtocol:S.protocol,FromPort:S.fromPort,ToPort:S.toPort,CidrIp:S.cidr,DestinationSecurityGroupId:S.sourceSecurityGroupId}));return{securityGroup:f,logicalId:y}}static createWebServerSecurityGroup(a,n,i){return o.createSecurityGroup({slug:a,environment:n,vpcId:i,description:"Security group for web servers - HTTP, HTTPS, SSH",ingress:[{protocol:"tcp",fromPort:80,toPort:80,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:443,toPort:443,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:22,toPort:22,cidr:"0.0.0.0/0"}],egress:[{protocol:"-1",fromPort:0,toPort:0,cidr:"0.0.0.0/0"}]})}static createLoadBalancer(a){let{slug:n,environment:i,scheme:s="internet-facing",subnets:c,securityGroups:l,type:u="application"}=a,h=r({slug:n,environment:i,resourceType:"alb"}),y=t(h),f={Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:h,Scheme:s,Type:u,Subnets:c,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(l)f.Properties.SecurityGroups=l;return{loadBalancer:f,logicalId:y}}static createTargetGroup(a){let{slug:n,environment:i,port:s,protocol:c="HTTP",vpcId:l,targetType:u="ip",healthCheckPath:h="/",healthCheckInterval:y=30,healthCheckTimeout:f=5,healthyThreshold:S=2,unhealthyThreshold:b=3}=a,C=r({slug:n,environment:i,resourceType:"tg"}),T=t(C);return{targetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:C,Port:s,Protocol:c,VpcId:l,TargetType:u,HealthCheckEnabled:!0,HealthCheckProtocol:c,HealthCheckPath:h,HealthCheckIntervalSeconds:y,HealthCheckTimeoutSeconds:f,HealthyThresholdCount:S,UnhealthyThresholdCount:b,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:i}]}},logicalId:T}}static createListener(a,n){let{port:i,protocol:s="HTTP",certificateArn:c,defaultTargetGroupArn:l}=n,u=t(`listener-${a}-${i}`),h={Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:N.Ref(a),Port:i,Protocol:s,DefaultActions:[{Type:"forward",TargetGroupArn:l}]}};if(s==="HTTPS"&&c)h.Properties.Certificates=[{CertificateArn:c}],h.Properties.SslPolicy="ELBSecurityPolicy-TLS13-1-2-2021-06";return{listener:h,logicalId:u}}static createEcsCluster(a,n){let i=r({slug:a,environment:n,resourceType:"ecs-cluster"}),s=t(i);return{cluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:i,Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:n}]}},logicalId:s}}static createFargateService(a){let{slug:n,environment:i,image:s,cpu:c="256",memory:l="512",desiredCount:u=1,containerPort:h=8080,environmentVariables:y={},secrets:f=[],healthCheck:S,logGroup:b,subnets:C,securityGroups:T,targetGroupArn:v}=a,{cluster:w,logicalId:R}=o.createEcsCluster(n,i),k=r({slug:n,environment:i,resourceType:"fargate"}),W=t(`${k}-execution-role`),P={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"]}},V=t(`${k}-task-role`),B={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]}}},j=t(`${k}-task`),J={Type:"AWS::ECS::TaskDefinition",Properties:{Family:k,TaskRoleArn:N.GetAtt(V,"Arn"),ExecutionRoleArn:N.GetAtt(W,"Arn"),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:c,Memory:l,ContainerDefinitions:[{Name:n,Image:s,Essential:!0,PortMappings:[{ContainerPort:h,Protocol:"tcp"}],Environment:Object.entries(y).map(([te,ne])=>({Name:te,Value:ne})),Secrets:f.map((te)=>({Name:te.name,ValueFrom:te.valueFrom}))}],Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:i}]}};if(S)J.Properties.ContainerDefinitions[0].HealthCheck={Command:S.command,Interval:S.interval||30,Timeout:S.timeout||5,Retries:S.retries||3,StartPeriod:60};if(b)J.Properties.ContainerDefinitions[0].LogConfiguration={LogDriver:"awslogs",Options:{"awslogs-group":b,"awslogs-region":N.Ref("AWS::Region"),"awslogs-stream-prefix":n}};let K=t(`${k}-service`),ee={Type:"AWS::ECS::Service",Properties:{ServiceName:k,Cluster:N.Ref(R),TaskDefinition:N.Ref(j),DesiredCount:u,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{Subnets:C,SecurityGroups:T,AssignPublicIp:"ENABLED"}},Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:i}]}};if(v)ee.Properties.LoadBalancers=[{TargetGroupArn:v,ContainerName:n,ContainerPort:h}];return{cluster:w,taskDefinition:J,service:ee,taskRole:B,executionRole:P,clusterLogicalId:R,taskDefinitionLogicalId:j,serviceLogicalId:K,taskRoleLogicalId:V,executionRoleLogicalId:W}}static createLambdaFunction(a){let{slug:n,environment:i,runtime:s,handler:c,code:l,timeout:u=30,memorySize:h=128,environmentVariables:y={},vpcConfig:f}=a,S=r({slug:n,environment:i,resourceType:"lambda"}),b=t(S),C=t(`${S}-role`),T={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}};if(f)T.Properties.ManagedPolicyArns.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");let v={Type:"AWS::Lambda::Function",Properties:{FunctionName:S,Runtime:s,Role:N.GetAtt(C,"Arn"),Handler:c,Code:{...l.s3Bucket&&{S3Bucket:l.s3Bucket},...l.s3Key&&{S3Key:l.s3Key},...l.zipFile&&{ZipFile:l.zipFile}},Timeout:u,MemorySize:h,Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:i}]}};if(Object.keys(y).length>0)v.Properties.Environment={Variables:y};if(f)v.Properties.VpcConfig={SecurityGroupIds:f.securityGroupIds,SubnetIds:f.subnetIds};return{lambdaFunction:v,role:T,logicalId:b,roleLogicalId:C}}static generateNodeServerUserData(a={}){let{nodeVersion:n="20",appRepo:i,environment:s={}}=a,c=Object.entries(s).map(([l,u])=>`echo "export ${l}='${u}'" >> /etc/environment`).join(`
213
213
  `);return`#!/bin/bash
214
214
  # Update system
215
215
  yum update -y
@@ -604,7 +604,7 @@ ufw default allow outgoing
604
604
  ${a.map((n)=>`ufw allow ${n}`).join(`
605
605
  `)}
606
606
  ufw --force enable
607
- `},Presets:{bunWithNginx:(a,n=3000)=>o.UserData.generateAppServerScript({runtime:"bun",webServer:"nginx",processManager:"systemd",domain:a,appPort:n,enableSsl:!0}),bunWithCaddy:(a,n=3000)=>o.UserData.generateAppServerScript({runtime:"bun",webServer:"caddy",processManager:"systemd",domain:a,appPort:n,enableSsl:!1}),nodeWithPm2:(a,n=3000)=>o.UserData.generateAppServerScript({runtime:"node",webServer:"nginx",processManager:"pm2",domain:a,appPort:n,enableSsl:!0}),worker:(a="bun")=>o.UserData.generateAppServerScript({runtime:a,webServer:"none",processManager:"systemd",enableSsl:!1})}};static createElasticIp(a){let{slug:n,environment:i,domain:s,instanceLogicalId:c}=a,l=r({slug:n,environment:i,resourceType:"eip"}),u=t(l),h={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:i},...s?[{Key:"Domain",Value:s}]:[]]}},y={[u]:h},f,S;if(c)S=t(`${l}-assoc`),f={Type:"AWS::EC2::EIPAssociation",Properties:{AllocationId:N.GetAtt(u,"AllocationId"),InstanceId:N.Ref(c)}},y[S]=f;return{eip:h,eipAssociation:f,eipLogicalId:u,associationLogicalId:S,resources:y}}static createServerModeStack(a){let{slug:n,environment:i,vpcId:s,subnetId:c,instanceType:l="t3.small",imageId:u="ami-0f3caa1cf4417e51b",keyName:h,domain:y,userData:f,allowedPorts:S=[22,80,443],volumeSize:b=20,volumeType:C="gp3"}=a,T={},v=r({slug:n,environment:i,resourceType:"server-sg"}),w=t(v),R={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:v,GroupDescription:`Security group for ${n} server`,VpcId:s,SecurityGroupIngress:S.map((se)=>({IpProtocol:"tcp",FromPort:se,ToPort:se,CidrIp:"0.0.0.0/0",Description:`Port ${se}`})),SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:i}]}};T[w]=R;let k=r({slug:n,environment:i,resourceType:"server-role"}),W=t(k),P={Type:"AWS::IAM::Role",Properties:{RoleName:k,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Policies:[{PolicyName:"StacksServerPermissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:SendBulkEmail","ses:VerifyDomainIdentity","ses:VerifyDomainDkim","ses:GetIdentityDkimAttributes","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["route53:ChangeResourceRecordSets","route53:ListResourceRecordSets","route53:GetHostedZone"],Resource:"*"},{Effect:"Allow",Action:["ssm:GetParameter","ssm:GetParameters"],Resource:"*"}]}}]}};T[W]=P;let V=r({slug:n,environment:i,resourceType:"server-profile"}),B=t(V),j={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:V,Roles:[N.Ref(W)]}};T[B]=j;let Z=r({slug:n,environment:i,resourceType:"server"}),K=t(Z),ee={Type:"AWS::EC2::Instance",DependsOn:[B],Properties:{ImageId:u,InstanceType:l,KeyName:h,SubnetId:c,SecurityGroupIds:[N.Ref(w)],IamInstanceProfile:N.Ref(B),BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:b,VolumeType:C,Encrypted:!0,DeleteOnTermination:!0}}],Tags:[{Key:"Name",Value:Z},{Key:"Environment",Value:i},...y?[{Key:"Domain",Value:y}]:[]]}};if(f)ee.Properties.UserData=N.Base64(f);T[K]=ee;let{eip:te,eipAssociation:ie,eipLogicalId:me,associationLogicalId:ce,resources:ue}=o.createElasticIp({slug:n,environment:i,domain:y,instanceLogicalId:K});return Object.assign(T,ue),{instance:ee,securityGroup:R,eip:te,eipAssociation:ie,instanceRole:P,instanceProfile:j,resources:T,outputs:{instanceLogicalId:K,securityGroupLogicalId:w,eipLogicalId:me,associationLogicalId:ce,roleLogicalId:W,profileLogicalId:B}}}static ServerMode={webServer:(a)=>{let n=o.UserData.generateAppServerScript({runtime:a.runtime||"bun",webServer:a.webServer||"nginx",domain:a.domain,enableSsl:!0});return o.createServerModeStack({...a,userData:n,instanceType:"t3.small",allowedPorts:[22,80,443]})},workerServer:(a)=>{let n=o.UserData.generateAppServerScript({runtime:a.runtime||"bun",webServer:"none",installRedis:a.installRedis});return o.createServerModeStack({...a,userData:n,instanceType:"t3.medium",allowedPorts:[22]})},cacheServer:(a)=>o.createServerModeStack({...a,userData:`#!/bin/bash
607
+ `},Presets:{bunWithNginx:(a,n=3000)=>o.UserData.generateAppServerScript({runtime:"bun",webServer:"nginx",processManager:"systemd",domain:a,appPort:n,enableSsl:!0}),bunWithCaddy:(a,n=3000)=>o.UserData.generateAppServerScript({runtime:"bun",webServer:"caddy",processManager:"systemd",domain:a,appPort:n,enableSsl:!1}),nodeWithPm2:(a,n=3000)=>o.UserData.generateAppServerScript({runtime:"node",webServer:"nginx",processManager:"pm2",domain:a,appPort:n,enableSsl:!0}),worker:(a="bun")=>o.UserData.generateAppServerScript({runtime:a,webServer:"none",processManager:"systemd",enableSsl:!1})}};static createElasticIp(a){let{slug:n,environment:i,domain:s,instanceLogicalId:c}=a,l=r({slug:n,environment:i,resourceType:"eip"}),u=t(l),h={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:i},...s?[{Key:"Domain",Value:s}]:[]]}},y={[u]:h},f,S;if(c)S=t(`${l}-assoc`),f={Type:"AWS::EC2::EIPAssociation",Properties:{AllocationId:N.GetAtt(u,"AllocationId"),InstanceId:N.Ref(c)}},y[S]=f;return{eip:h,eipAssociation:f,eipLogicalId:u,associationLogicalId:S,resources:y}}static createServerModeStack(a){let{slug:n,environment:i,vpcId:s,subnetId:c,instanceType:l="t3.small",imageId:u="ami-0f3caa1cf4417e51b",keyName:h,domain:y,userData:f,allowedPorts:S=[22,80,443],volumeSize:b=20,volumeType:C="gp3"}=a,T={},v=r({slug:n,environment:i,resourceType:"server-sg"}),w=t(v),R={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:v,GroupDescription:`Security group for ${n} server`,VpcId:s,SecurityGroupIngress:S.map((ie)=>({IpProtocol:"tcp",FromPort:ie,ToPort:ie,CidrIp:"0.0.0.0/0",Description:`Port ${ie}`})),SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:i}]}};T[w]=R;let k=r({slug:n,environment:i,resourceType:"server-role"}),W=t(k),P={Type:"AWS::IAM::Role",Properties:{RoleName:k,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Policies:[{PolicyName:"StacksServerPermissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:SendBulkEmail","ses:VerifyDomainIdentity","ses:VerifyDomainDkim","ses:GetIdentityDkimAttributes","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["route53:ChangeResourceRecordSets","route53:ListResourceRecordSets","route53:GetHostedZone"],Resource:"*"},{Effect:"Allow",Action:["ssm:GetParameter","ssm:GetParameters"],Resource:"*"}]}}]}};T[W]=P;let V=r({slug:n,environment:i,resourceType:"server-profile"}),B=t(V),j={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:V,Roles:[N.Ref(W)]}};T[B]=j;let J=r({slug:n,environment:i,resourceType:"server"}),K=t(J),ee={Type:"AWS::EC2::Instance",DependsOn:[B],Properties:{ImageId:u,InstanceType:l,KeyName:h,SubnetId:c,SecurityGroupIds:[N.Ref(w)],IamInstanceProfile:N.Ref(B),BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:b,VolumeType:C,Encrypted:!0,DeleteOnTermination:!0}}],Tags:[{Key:"Name",Value:J},{Key:"Environment",Value:i},...y?[{Key:"Domain",Value:y}]:[]]}};if(f)ee.Properties.UserData=N.Base64(f);T[K]=ee;let{eip:te,eipAssociation:ne,eipLogicalId:me,associationLogicalId:oe,resources:ue}=o.createElasticIp({slug:n,environment:i,domain:y,instanceLogicalId:K});return Object.assign(T,ue),{instance:ee,securityGroup:R,eip:te,eipAssociation:ne,instanceRole:P,instanceProfile:j,resources:T,outputs:{instanceLogicalId:K,securityGroupLogicalId:w,eipLogicalId:me,associationLogicalId:oe,roleLogicalId:W,profileLogicalId:B}}}static ServerMode={webServer:(a)=>{let n=o.UserData.generateAppServerScript({runtime:a.runtime||"bun",webServer:a.webServer||"nginx",domain:a.domain,enableSsl:!0});return o.createServerModeStack({...a,userData:n,instanceType:"t3.small",allowedPorts:[22,80,443]})},workerServer:(a)=>{let n=o.UserData.generateAppServerScript({runtime:a.runtime||"bun",webServer:"none",installRedis:a.installRedis});return o.createServerModeStack({...a,userData:n,instanceType:"t3.medium",allowedPorts:[22]})},cacheServer:(a)=>o.createServerModeStack({...a,userData:`#!/bin/bash
608
608
  set -e
609
609
  apt-get update && apt-get upgrade -y
610
610
  apt-get install -y redis-server
@@ -612,7 +612,7 @@ sed -i 's/bind 127.0.0.1/bind 0.0.0.0/' /etc/redis/redis.conf
612
612
  systemctl enable redis-server
613
613
  systemctl restart redis-server
614
614
  echo "Redis server setup complete!"
615
- `,instanceType:"t3.medium",allowedPorts:[22,6379]})}}class A{static createVpc(a){let{slug:n,environment:i,cidr:s="10.0.0.0/16",enableDnsHostnames:c=!0,enableDnsSupport:l=!0}=a,u=r({slug:n,environment:i,resourceType:"vpc"}),h=t(u);return{vpc:{Type:"AWS::EC2::VPC",Properties:{CidrBlock:s,EnableDnsHostnames:c,EnableDnsSupport:l,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i}]}},logicalId:h}}static createSubnet(a){let{slug:n,environment:i,vpcId:s,type:c,cidr:l,availabilityZone:u,mapPublicIp:h=c==="public"}=a,y=r({slug:n,environment:i,resourceType:`subnet-${c}`}),f=t(`${y}-${u}`);return{subnet:{Type:"AWS::EC2::Subnet",Properties:{VpcId:s,CidrBlock:l,AvailabilityZone:u,MapPublicIpOnLaunch:h,Tags:[{Key:"Name",Value:`${y}-${u}`},{Key:"Environment",Value:i},{Key:"Type",Value:c}]}},logicalId:f}}static createInternetGateway(a,n){let i=r({slug:a,environment:n,resourceType:"igw"}),s=t(i);return{internetGateway:{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:n}]}},logicalId:s}}static attachInternetGateway(a,n){let i=t(`${a}-igw-attachment`);return{attachment:{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:N.Ref(a),InternetGatewayId:N.Ref(n)}},logicalId:i}}static createEip(a,n){let i=r({slug:a,environment:n,resourceType:"eip"}),s=t(i);return{eip:{Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:n}]}},logicalId:s}}static createNatGateway(a,n){let{slug:i,environment:s,subnetId:c}=a,l=r({slug:i,environment:s,resourceType:"nat"}),u=t(l);return{natGateway:{Type:"AWS::EC2::NatGateway",Properties:{AllocationId:N.GetAtt(n,"AllocationId"),SubnetId:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s},{Key:"Warning",Value:"NAT Gateway incurs hourly charges"}]}},logicalId:u}}static createRouteTable(a,n,i,s){let c=r({slug:a,environment:n,resourceType:`rt-${s}`}),l=t(c);return{routeTable:{Type:"AWS::EC2::RouteTable",Properties:{VpcId:N.Ref(i),Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:n},{Key:"Type",Value:s}]}},logicalId:l}}static createRoute(a,n,i){let s=t(`${a}-route-${i.type}`),c={Type:"AWS::EC2::Route",Properties:{RouteTableId:N.Ref(a),DestinationCidrBlock:n}};if(i.type==="igw")c.Properties.GatewayId=N.Ref(i.logicalId);else if(i.type==="nat")c.Properties.NatGatewayId=N.Ref(i.logicalId);else if(i.type==="instance")c.Properties.InstanceId=N.Ref(i.logicalId);return{route:c,logicalId:s}}static associateSubnetWithRouteTable(a,n){let i=t(`${a}-rt-assoc`);return{association:{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:N.Ref(a),RouteTableId:N.Ref(n)}},logicalId:i}}static enableFlowLogs(a){let{slug:n,environment:i,resourceId:s,resourceType:c,trafficType:l="ALL",logGroupName:u}=a,h=r({slug:n,environment:i,resourceType:"flowlog"}),y=t(h);return{flowLog:{Type:"AWS::EC2::FlowLog",Properties:{ResourceType:c,ResourceIds:[s],TrafficType:l,LogDestinationType:"cloud-watch-logs",LogGroupName:u||`/aws/vpc/${n}-${i}`,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}},logicalId:y}}static calculateSubnetCidrs(a,n,i=3){let[s,c]=a.split("/"),l=Number.parseInt(c,10),u=Math.ceil(Math.log2(n*i)),h=l+u;if(h>28)throw Error("VPC CIDR is too small to accommodate requested subnets");let[y,f,S,b]=s.split(".").map(Number),C=(y<<24)+(f<<16)+(S<<8)+b,T=2**(32-h),v=[];for(let w=0;w<n*i;w++){let R=C+w*T,k=[R>>>24&255,R>>>16&255,R>>>8&255,R&255].join(".");v.push(`${k}/${h}`)}return v}static getAvailabilityZones(a,n){return["a","b","c","d","e","f"].slice(0,n).map((i)=>`${a}${i}`)}static createMultiAzNetwork(a){let{slug:n,environment:i,region:s,cidr:c="10.0.0.0/16",zones:l=3,enableNatGateway:u=!1,singleNatGateway:h=!1,enableFlowLogs:y=!1}=a,f={},S=[],b=[],C=[],{vpc:T,logicalId:v}=A.createVpc({slug:n,environment:i,cidr:c});f[v]=T;let{internetGateway:w,logicalId:R}=A.createInternetGateway(n,i);f[R]=w;let{attachment:k,logicalId:W}=A.attachInternetGateway(v,R);f[W]=k;let{routeTable:P,logicalId:V}=A.createRouteTable(n,i,v,"public");f[V]=P;let{route:B,logicalId:j}=A.createRoute(V,"0.0.0.0/0",{type:"igw",logicalId:R});B.DependsOn=W,f[j]=B;let Z=A.calculateSubnetCidrs(c,l,2),K=A.getAvailabilityZones(s,l),ee=[];for(let te=0;te<l;te++){let ie=K[te],me=Z[te*2],ce=Z[te*2+1],{subnet:ue,logicalId:se}=A.createSubnet({slug:n,environment:i,vpcId:N.Ref(v),type:"public",cidr:me,availabilityZone:ie});f[se]=ue,S.push(se);let{association:Ie,logicalId:We}=A.associateSubnetWithRouteTable(se,V);f[We]=Ie;let{subnet:Ct,logicalId:pe}=A.createSubnet({slug:n,environment:i,vpcId:N.Ref(v),type:"private",cidr:ce,availabilityZone:ie});if(f[pe]=Ct,b.push(pe),u&&(!h||te===0)){let{eip:de,logicalId:ge}=A.createEip(`${n}-${ie}`,i);f[ge]=de;let{natGateway:Re,logicalId:he}=A.createNatGateway({slug:`${n}-${ie}`,environment:i,subnetId:N.Ref(se)},ge);Re.DependsOn=W,f[he]=Re,C.push(he);let{routeTable:Ae,logicalId:$e}=A.createRouteTable(`${n}-${ie}`,i,v,"private");f[$e]=Ae,ee.push($e);let{route:Ge,logicalId:z}=A.createRoute($e,"0.0.0.0/0",{type:"nat",logicalId:he});f[z]=Ge;let{association:ne,logicalId:re}=A.associateSubnetWithRouteTable(pe,$e);f[re]=ne}else if(u&&h&&te>0){let{association:de,logicalId:ge}=A.associateSubnetWithRouteTable(pe,ee[0]);f[ge]=de}else{let{routeTable:de,logicalId:ge}=A.createRouteTable(`${n}-${ie}-isolated`,i,v,"private");f[ge]=de;let{association:Re,logicalId:he}=A.associateSubnetWithRouteTable(pe,ge);f[he]=Re}}if(y){let{flowLog:te,logicalId:ie}=A.enableFlowLogs({slug:n,environment:i,resourceId:N.Ref(v),resourceType:"VPC"});f[ie]=te}return{resources:f,outputs:{vpcId:v,publicSubnetIds:S,privateSubnetIds:b,natGatewayIds:C.length>0?C:void 0}}}static NatGatewayCostWarning=`
615
+ `,instanceType:"t3.medium",allowedPorts:[22,6379]})}}class A{static createVpc(a){let{slug:n,environment:i,cidr:s="10.0.0.0/16",enableDnsHostnames:c=!0,enableDnsSupport:l=!0}=a,u=r({slug:n,environment:i,resourceType:"vpc"}),h=t(u);return{vpc:{Type:"AWS::EC2::VPC",Properties:{CidrBlock:s,EnableDnsHostnames:c,EnableDnsSupport:l,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i}]}},logicalId:h}}static createSubnet(a){let{slug:n,environment:i,vpcId:s,type:c,cidr:l,availabilityZone:u,mapPublicIp:h=c==="public"}=a,y=r({slug:n,environment:i,resourceType:`subnet-${c}`}),f=t(`${y}-${u}`);return{subnet:{Type:"AWS::EC2::Subnet",Properties:{VpcId:s,CidrBlock:l,AvailabilityZone:u,MapPublicIpOnLaunch:h,Tags:[{Key:"Name",Value:`${y}-${u}`},{Key:"Environment",Value:i},{Key:"Type",Value:c}]}},logicalId:f}}static createInternetGateway(a,n){let i=r({slug:a,environment:n,resourceType:"igw"}),s=t(i);return{internetGateway:{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:n}]}},logicalId:s}}static attachInternetGateway(a,n){let i=t(`${a}-igw-attachment`);return{attachment:{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:N.Ref(a),InternetGatewayId:N.Ref(n)}},logicalId:i}}static createEip(a,n){let i=r({slug:a,environment:n,resourceType:"eip"}),s=t(i);return{eip:{Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:n}]}},logicalId:s}}static createNatGateway(a,n){let{slug:i,environment:s,subnetId:c}=a,l=r({slug:i,environment:s,resourceType:"nat"}),u=t(l);return{natGateway:{Type:"AWS::EC2::NatGateway",Properties:{AllocationId:N.GetAtt(n,"AllocationId"),SubnetId:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s},{Key:"Warning",Value:"NAT Gateway incurs hourly charges"}]}},logicalId:u}}static createRouteTable(a,n,i,s){let c=r({slug:a,environment:n,resourceType:`rt-${s}`}),l=t(c);return{routeTable:{Type:"AWS::EC2::RouteTable",Properties:{VpcId:N.Ref(i),Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:n},{Key:"Type",Value:s}]}},logicalId:l}}static createRoute(a,n,i){let s=t(`${a}-route-${i.type}`),c={Type:"AWS::EC2::Route",Properties:{RouteTableId:N.Ref(a),DestinationCidrBlock:n}};if(i.type==="igw")c.Properties.GatewayId=N.Ref(i.logicalId);else if(i.type==="nat")c.Properties.NatGatewayId=N.Ref(i.logicalId);else if(i.type==="instance")c.Properties.InstanceId=N.Ref(i.logicalId);return{route:c,logicalId:s}}static associateSubnetWithRouteTable(a,n){let i=t(`${a}-rt-assoc`);return{association:{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:N.Ref(a),RouteTableId:N.Ref(n)}},logicalId:i}}static enableFlowLogs(a){let{slug:n,environment:i,resourceId:s,resourceType:c,trafficType:l="ALL",logGroupName:u}=a,h=r({slug:n,environment:i,resourceType:"flowlog"}),y=t(h);return{flowLog:{Type:"AWS::EC2::FlowLog",Properties:{ResourceType:c,ResourceIds:[s],TrafficType:l,LogDestinationType:"cloud-watch-logs",LogGroupName:u||`/aws/vpc/${n}-${i}`,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}},logicalId:y}}static calculateSubnetCidrs(a,n,i=3){let[s,c]=a.split("/"),l=Number.parseInt(c,10),u=Math.ceil(Math.log2(n*i)),h=l+u;if(h>28)throw Error("VPC CIDR is too small to accommodate requested subnets");let[y,f,S,b]=s.split(".").map(Number),C=(y<<24)+(f<<16)+(S<<8)+b,T=2**(32-h),v=[];for(let w=0;w<n*i;w++){let R=C+w*T,k=[R>>>24&255,R>>>16&255,R>>>8&255,R&255].join(".");v.push(`${k}/${h}`)}return v}static getAvailabilityZones(a,n){return["a","b","c","d","e","f"].slice(0,n).map((i)=>`${a}${i}`)}static createMultiAzNetwork(a){let{slug:n,environment:i,region:s,cidr:c="10.0.0.0/16",zones:l=3,enableNatGateway:u=!1,singleNatGateway:h=!1,enableFlowLogs:y=!1}=a,f={},S=[],b=[],C=[],{vpc:T,logicalId:v}=A.createVpc({slug:n,environment:i,cidr:c});f[v]=T;let{internetGateway:w,logicalId:R}=A.createInternetGateway(n,i);f[R]=w;let{attachment:k,logicalId:W}=A.attachInternetGateway(v,R);f[W]=k;let{routeTable:P,logicalId:V}=A.createRouteTable(n,i,v,"public");f[V]=P;let{route:B,logicalId:j}=A.createRoute(V,"0.0.0.0/0",{type:"igw",logicalId:R});B.DependsOn=W,f[j]=B;let J=A.calculateSubnetCidrs(c,l,2),K=A.getAvailabilityZones(s,l),ee=[];for(let te=0;te<l;te++){let ne=K[te],me=J[te*2],oe=J[te*2+1],{subnet:ue,logicalId:ie}=A.createSubnet({slug:n,environment:i,vpcId:N.Ref(v),type:"public",cidr:me,availabilityZone:ne});f[ie]=ue,S.push(ie);let{association:Ie,logicalId:_e}=A.associateSubnetWithRouteTable(ie,V);f[_e]=Ie;let{subnet:Ct,logicalId:pe}=A.createSubnet({slug:n,environment:i,vpcId:N.Ref(v),type:"private",cidr:oe,availabilityZone:ne});if(f[pe]=Ct,b.push(pe),u&&(!h||te===0)){let{eip:de,logicalId:ge}=A.createEip(`${n}-${ne}`,i);f[ge]=de;let{natGateway:Re,logicalId:he}=A.createNatGateway({slug:`${n}-${ne}`,environment:i,subnetId:N.Ref(ie)},ge);Re.DependsOn=W,f[he]=Re,C.push(he);let{routeTable:Ae,logicalId:$e}=A.createRouteTable(`${n}-${ne}`,i,v,"private");f[$e]=Ae,ee.push($e);let{route:We,logicalId:z}=A.createRoute($e,"0.0.0.0/0",{type:"nat",logicalId:he});f[z]=We;let{association:re,logicalId:ae}=A.associateSubnetWithRouteTable(pe,$e);f[ae]=re}else if(u&&h&&te>0){let{association:de,logicalId:ge}=A.associateSubnetWithRouteTable(pe,ee[0]);f[ge]=de}else{let{routeTable:de,logicalId:ge}=A.createRouteTable(`${n}-${ne}-isolated`,i,v,"private");f[ge]=de;let{association:Re,logicalId:he}=A.associateSubnetWithRouteTable(pe,ge);f[he]=Re}}if(y){let{flowLog:te,logicalId:ne}=A.enableFlowLogs({slug:n,environment:i,resourceId:N.Ref(v),resourceType:"VPC"});f[ne]=te}return{resources:f,outputs:{vpcId:v,publicSubnetIds:S,privateSubnetIds:b,natGatewayIds:C.length>0?C:void 0}}}static NatGatewayCostWarning=`
616
616
  ⚠️ NAT Gateway Cost Warning:
617
617
  - Each NAT Gateway costs approximately $32-45/month (hourly charges)
618
618
  - Data processing charges: $0.045/GB processed
@@ -620,7 +620,7 @@ echo "Redis server setup complete!"
620
620
  - Using a single NAT Gateway (singleNatGateway: true)
621
621
  - Using NAT Instances instead (cheaper but requires management)
622
622
  - Disabling NAT entirely for isolated private subnets
623
- `}class Fe{static createFileSystem(a){let{slug:n,environment:i,encrypted:s=!0,kmsKeyId:c,performanceMode:l="generalPurpose",throughputMode:u="bursting",provisionedThroughput:h,enableBackup:y=!0}=a,f=r({slug:n,environment:i,resourceType:"efs"}),S=t(f),b={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:s,PerformanceMode:l,ThroughputMode:u,FileSystemTags:[{Key:"Name",Value:f},{Key:"Environment",Value:i}]}};if(c)b.Properties.KmsKeyId=c;if(u==="provisioned"&&h)b.Properties.ProvisionedThroughputInMibps=h;if(y)b.Properties.BackupPolicy={Status:"ENABLED"};return{fileSystem:b,logicalId:S}}static createMountTarget(a,n){let{slug:i,environment:s,subnetId:c,securityGroups:l,ipAddress:u}=n,h=r({slug:i,environment:s,resourceType:"efs-mt"}),y=t(`${h}-${c}`),f={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:N.Ref(a),SubnetId:c,SecurityGroups:l}};if(u)f.Properties.IpAddress=u;return{mountTarget:f,logicalId:y}}static createAccessPoint(a,n){let{slug:i,environment:s,path:c="/",uid:l="1000",gid:u="1000",permissions:h="755"}=n,y=r({slug:i,environment:s,resourceType:"efs-ap"}),f=t(`${y}-${c.replace(/\//g,"-")}`);return{accessPoint:{Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:N.Ref(a),PosixUser:{Uid:l,Gid:u},RootDirectory:{Path:c,CreationInfo:{OwnerUid:l,OwnerGid:u,Permissions:h}},AccessPointTags:[{Key:"Name",Value:`${y}-${c}`},{Key:"Environment",Value:s}]}},logicalId:f}}static setLifecyclePolicy(a,n){let{transitionToIA:i,transitionToPrimary:s=!1}=n;if(!a.Properties)a.Properties={};if(a.Properties.LifecyclePolicies=[],i){let c=`AFTER_${i}_DAYS`;a.Properties.LifecyclePolicies.push({TransitionToIA:c})}if(s)a.Properties.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"});return a}static enableBackup(a){if(!a.Properties)a.Properties={};return a.Properties.BackupPolicy={Status:"ENABLED"},a}static disableBackup(a){if(!a.Properties)a.Properties={};return a.Properties.BackupPolicy={Status:"DISABLED"},a}static setProvisionedThroughput(a,n){if(!a.Properties)a.Properties={};return a.Properties.ThroughputMode="provisioned",a.Properties.ProvisionedThroughputInMibps=n,a}static setElasticThroughput(a){if(!a.Properties)a.Properties={};return a.Properties.ThroughputMode="elastic",a}static enableMaxIO(a){if(!a.Properties)a.Properties={};return a.Properties.PerformanceMode="maxIO",a}static createEfsSecurityGroup(a){let{slug:n,environment:i,vpcId:s,sourceSecurityGroupIds:c=[],sourceCidrBlocks:l=[],description:u}=a,h=r({slug:n,environment:i,resourceType:"efs-sg"}),y=t(h),f=[];for(let S of c)f.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:S,Description:"NFS from security group"});for(let S of l)f.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,CidrIp:S,Description:"NFS from CIDR block"});return{securityGroup:{Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:h,GroupDescription:u||`Security group for EFS mount targets - ${n} ${i}`,VpcId:s,SecurityGroupIngress:f,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}},logicalId:y}}static createMultiAzMountTargets(a,n){let{slug:i,environment:s,subnetIds:c,securityGroupId:l}=n,u=[],h=[];for(let y=0;y<c.length;y++){let f=c[y],S=r({slug:i,environment:s,resourceType:"efs-mt"}),b=t(`${S}-az${y+1}`),C={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:N.Ref(a),SubnetId:f,SecurityGroups:[l]}};u.push(C),h.push(b)}return{mountTargets:u,logicalIds:h}}static createCompleteFileSystem(a){let{slug:n,environment:i,vpcId:s,subnetIds:c,sourceSecurityGroupIds:l=[],encrypted:u=!0,performanceMode:h="generalPurpose",throughputMode:y="elastic",enableBackup:f=!0,transitionToIA:S}=a,b={},{fileSystem:C,logicalId:T}=Fe.createFileSystem({slug:n,environment:i,encrypted:u,performanceMode:h,throughputMode:y,enableBackup:f});if(S)Fe.setLifecyclePolicy(C,{transitionToIA:S,transitionToPrimary:!0});b[T]=C;let{securityGroup:v,logicalId:w}=Fe.createEfsSecurityGroup({slug:n,environment:i,vpcId:s,sourceSecurityGroupIds:l});b[w]=v;let{mountTargets:R,logicalIds:k}=Fe.createMultiAzMountTargets(T,{slug:n,environment:i,subnetIds:c,securityGroupId:N.Ref(w)});for(let W=0;W<R.length;W++)b[k[W]]=R[W];return{resources:b,outputs:{fileSystemId:T,securityGroupId:w,mountTargetIds:k}}}}class m{static verifyDomain(a){let{domain:n,slug:i,environment:s,enableDkim:c=!0,dkimKeyLength:l="RSA_2048_BIT"}=a,u=r({slug:i,environment:s,resourceType:"ses-identity"}),h=t(`${u}-${n.replace(/\./g,"")}`),y={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:n,FeedbackAttributes:{EmailForwardingEnabled:!0}}};if(c)y.Properties.DkimSigningAttributes={NextSigningKeyLength:l};return{emailIdentity:y,logicalId:h}}static createDkimRecords(a,n,i){let s=[];for(let c=0;c<n.length;c++){let l=n[c],u=t(`dkim-${a.replace(/\./g,"")}-${c+1}`),h={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:`${l}._domainkey.${a}`,Type:"CNAME",TTL:1800,ResourceRecords:[`${l}.dkim.amazonses.com`]}};s.push({record:h,logicalId:u})}return s}static createConfigurationSet(a){let{slug:n,environment:i,name:s,reputationMetrics:c=!0,sendingEnabled:l=!0,suppressBounces:u=!0,suppressComplaints:h=!0}=a,y=s||r({slug:n,environment:i,resourceType:"ses-config"}),f=t(y),S=[];if(u)S.push("BOUNCE");if(h)S.push("COMPLAINT");return{configurationSet:{Type:"AWS::SES::ConfigurationSet",Properties:{Name:y,ReputationOptions:{ReputationMetricsEnabled:c},SendingOptions:{SendingEnabled:l},SuppressionOptions:{SuppressedReasons:S}}},logicalId:f}}static createReceiptRuleSet(a){let{slug:n,environment:i,name:s}=a,c=s||r({slug:n,environment:i,resourceType:"ses-ruleset"}),l=t(c);return{ruleSet:{Type:"AWS::SES::ReceiptRuleSet",Properties:{RuleSetName:c}},logicalId:l}}static createReceiptRule(a,n){let{slug:i,environment:s,ruleSetName:c,recipients:l,enabled:u=!0,scanEnabled:h=!0,tlsPolicy:y="Require",s3Action:f,lambdaAction:S,snsAction:b}=n,C=r({slug:i,environment:s,resourceType:"ses-rule"}),T=t(C),v=[];if(f)v.push({S3Action:{BucketName:f.bucketName,ObjectKeyPrefix:f.prefix,KmsKeyArn:f.kmsKeyArn}});if(S)v.push({LambdaAction:{FunctionArn:S.functionArn,InvocationType:S.invocationType||"Event"}});if(b)v.push({SNSAction:{TopicArn:b.topicArn,Encoding:b.encoding||"UTF-8"}});return{receiptRule:{Type:"AWS::SES::ReceiptRule",Properties:{RuleSetName:c,Rule:{Name:C,Enabled:u,ScanEnabled:h,TlsPolicy:y,Recipients:l,Actions:v.length>0?v:void 0}}},logicalId:T}}static createMxRecord(a,n,i){let s=t(`mx-${a.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n,Name:a,Type:"MX",TTL:300,ResourceRecords:[`10 inbound-smtp.${i}.amazonaws.com`]}},logicalId:s}}static createVerificationRecord(a,n,i){let s=t(`verification-${a.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:`_amazonses.${a}`,Type:"TXT",TTL:1800,ResourceRecords:[`"${n}"`]}},logicalId:s}}static getSmtpEndpoint(a){return`email-smtp.${a}.amazonaws.com`}static SmtpPorts={TLS:587,SSL:465,Unencrypted:25};static createSpfRecord(a,n,i){let{includeDomains:s=[],softFail:c=!1}=i||{},l=t(`spf-${a.replace(/\./g,"")}`),u="v=spf1 include:amazonses.com";for(let h of s)u+=` include:${h}`;return u+=c?" ~all":" -all",{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n,Name:a,Type:"TXT",TTL:300,ResourceRecords:[`"${u}"`]}},logicalId:l}}static createDmarcRecord(a,n,i){let{policy:s="none",subdomainPolicy:c,percentage:l=100,reportingEmail:u,forensicEmail:h}=i||{},y=t(`dmarc-${a.replace(/\./g,"")}`),f=`v=DMARC1; p=${s}; pct=${l}`;if(c)f+=`; sp=${c}`;if(u)f+=`; rua=mailto:${u}`;if(h)f+=`; ruf=mailto:${h}`;return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n,Name:`_dmarc.${a}`,Type:"TXT",TTL:300,ResourceRecords:[`"${f}"`]}},logicalId:y}}static createInboundEmailSetup(a){let{slug:n,environment:i,domain:s,s3BucketName:c,s3KeyPrefix:l="inbound/",region:u,hostedZoneId:h,lambdaFunctionArn:y,snsTopicArn:f}=a,S={},{ruleSet:b,logicalId:C}=m.createReceiptRuleSet({slug:n,environment:i});S[C]=b;let{receiptRule:T,logicalId:v}=m.createReceiptRule(C,{slug:n,environment:i,ruleSetName:b.Properties.RuleSetName||`${n}-${i}-receipt-rule-set`,recipients:[s],s3Action:{bucketName:c,prefix:l},lambdaAction:y?{functionArn:y,invocationType:"Event"}:void 0,snsAction:f?{topicArn:f}:void 0});S[v]=T;let{record:w,logicalId:R}=m.createMxRecord(s,h,u);return S[R]=w,{resources:S,outputs:{ruleSetLogicalId:C,ruleLogicalId:v,mxRecordLogicalId:R}}}static createCompleteDomainSetup(a){let{slug:n,environment:i,domain:s,hostedZoneId:c,region:l,enableInbound:u=!1,inboundS3Bucket:h,dmarcReportingEmail:y}=a,f={},{emailIdentity:S,logicalId:b}=m.verifyDomain({domain:s,slug:n,environment:i});f[b]=S;let{configurationSet:C,logicalId:T}=m.createConfigurationSet({slug:n,environment:i});f[T]=C;let{record:v,logicalId:w}=m.createSpfRecord(s,c);f[w]=v;let{record:R,logicalId:k}=m.createDmarcRecord(s,c,{policy:"none",reportingEmail:y||`dmarc-reports@${s}`});if(f[k]=R,u&&h){let W=m.createInboundEmailSetup({slug:n,environment:i,domain:s,s3BucketName:h,region:l,hostedZoneId:c});Object.assign(f,W.resources)}return{resources:f,outputs:{identityLogicalId:b,configSetLogicalId:T}}}static InboundSmtpEndpoints={"us-east-1":"inbound-smtp.us-east-1.amazonaws.com","us-west-2":"inbound-smtp.us-west-2.amazonaws.com","eu-west-1":"inbound-smtp.eu-west-1.amazonaws.com"};static supportsInboundEmail(a){return a in m.InboundSmtpEndpoints}static createEmailLambdaRole(a){let{slug:n,environment:i,s3BucketArn:s,sesIdentityArn:c}=a,l=r({slug:n,environment:i,resourceType:"email-lambda-role"}),u=t(l),h=t(`${l}-policy`),y={Type:"AWS::IAM::Role",Properties:{RoleName:l,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:i}]}},f=[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[s,`${s}/*`]}];if(c)f.push({Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:c});let S={Type:"AWS::IAM::Policy",Properties:{PolicyName:`${l}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:f},Roles:[N.Ref(u)]}};return{role:y,policy:S,roleLogicalId:u,policyLogicalId:h}}static createOutboundEmailLambda(a){let{slug:n,environment:i,roleArn:s,domain:c,configurationSetName:l,timeout:u=30,memorySize:h=256}=a,y=r({slug:n,environment:i,resourceType:"outbound-email"}),f=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:s,Timeout:u,MemorySize:h,Environment:{Variables:{DOMAIN:c,CONFIGURATION_SET:l||""}},Code:{ZipFile:m.LambdaCode.outboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},{Key:"Purpose",Value:"OutboundEmail"}]}},logicalId:f}}static createInboundEmailLambda(a){let{slug:n,environment:i,roleArn:s,s3BucketName:c,organizedPrefix:l="organized/",timeout:u=60,memorySize:h=512}=a,y=r({slug:n,environment:i,resourceType:"inbound-email"}),f=t(y),S=t(`${y}-permission`),b={Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:s,Timeout:u,MemorySize:h,Environment:{Variables:{S3_BUCKET:c,ORGANIZED_PREFIX:l}},Code:{ZipFile:m.LambdaCode.inboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},{Key:"Purpose",Value:"InboundEmail"}]}},C={Type:"AWS::Lambda::Permission",Properties:{FunctionName:N.Ref(f),Action:"lambda:InvokeFunction",Principal:"ses.amazonaws.com",SourceAccount:N.Ref("AWS::AccountId")}};return{function:b,permission:C,logicalId:f,permissionLogicalId:S}}static createEmailConversionLambda(a){let{slug:n,environment:i,roleArn:s,s3BucketName:c,convertedPrefix:l="converted/",timeout:u=60,memorySize:h=512}=a,y=r({slug:n,environment:i,resourceType:"email-conversion"}),f=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:s,Timeout:u,MemorySize:h,Environment:{Variables:{S3_BUCKET:c,CONVERTED_PREFIX:l}},Code:{ZipFile:m.LambdaCode.emailConversion},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},{Key:"Purpose",Value:"EmailConversion"}]}},logicalId:f}}static createEmailBucketNotification(a){let{lambdaArn:n,prefix:i="inbound/",suffix:s,events:c}=a,l=c??["s3:ObjectCreated:*"],u={};if(i||s){if(u.S3Key={Rules:[]},i)u.S3Key.Rules.push({Name:"prefix",Value:i});if(s)u.S3Key.Rules.push({Name:"suffix",Value:s})}return{notificationConfiguration:{LambdaConfigurations:[{Event:l[0],Function:n,Filter:Object.keys(u).length>0?u:void 0}]}}}static createS3LambdaPermission(a){let{slug:n,environment:i,lambdaLogicalId:s,s3BucketArn:c}=a,l=r({slug:n,environment:i,resourceType:"s3-lambda-permission"}),u=t(l);return{permission:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:N.Ref(s),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:c}},logicalId:u}}static createEmailProcessingStack(a){let{slug:n,environment:i,domain:s,s3BucketName:c,s3BucketArn:l,configurationSetName:u,enableInbound:h=!0,enableConversion:y=!0}=a,f={},{role:S,policy:b,roleLogicalId:C,policyLogicalId:T}=m.createEmailLambdaRole({slug:n,environment:i,s3BucketArn:l,sesIdentityArn:`arn:aws:ses:*:*:identity/${s}`});f[C]=S,f[T]=b;let{function:v,logicalId:w}=m.createOutboundEmailLambda({slug:n,environment:i,roleArn:N.GetAtt(C,"Arn"),domain:s,configurationSetName:u});f[w]=v;let R={roleLogicalId:C,outboundLambdaLogicalId:w};if(h){let{function:k,permission:W,logicalId:P,permissionLogicalId:V}=m.createInboundEmailLambda({slug:n,environment:i,roleArn:N.GetAtt(C,"Arn"),s3BucketName:c});f[P]=k,f[V]=W;let{permission:B,logicalId:j}=m.createS3LambdaPermission({slug:n,environment:i,lambdaLogicalId:P,s3BucketArn:l});f[j]=B,R.inboundLambdaLogicalId=P}if(y){let{function:k,logicalId:W}=m.createEmailConversionLambda({slug:n,environment:i,roleArn:N.GetAtt(C,"Arn"),s3BucketName:c});f[W]=k,R.conversionLambdaLogicalId=W}return{resources:f,outputs:R}}static LambdaCode={outboundEmail:`
623
+ `}class Ue{static createFileSystem(a){let{slug:n,environment:i,encrypted:s=!0,kmsKeyId:c,performanceMode:l="generalPurpose",throughputMode:u="bursting",provisionedThroughput:h,enableBackup:y=!0}=a,f=r({slug:n,environment:i,resourceType:"efs"}),S=t(f),b={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:s,PerformanceMode:l,ThroughputMode:u,FileSystemTags:[{Key:"Name",Value:f},{Key:"Environment",Value:i}]}};if(c)b.Properties.KmsKeyId=c;if(u==="provisioned"&&h)b.Properties.ProvisionedThroughputInMibps=h;if(y)b.Properties.BackupPolicy={Status:"ENABLED"};return{fileSystem:b,logicalId:S}}static createMountTarget(a,n){let{slug:i,environment:s,subnetId:c,securityGroups:l,ipAddress:u}=n,h=r({slug:i,environment:s,resourceType:"efs-mt"}),y=t(`${h}-${c}`),f={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:N.Ref(a),SubnetId:c,SecurityGroups:l}};if(u)f.Properties.IpAddress=u;return{mountTarget:f,logicalId:y}}static createAccessPoint(a,n){let{slug:i,environment:s,path:c="/",uid:l="1000",gid:u="1000",permissions:h="755"}=n,y=r({slug:i,environment:s,resourceType:"efs-ap"}),f=t(`${y}-${c.replace(/\//g,"-")}`);return{accessPoint:{Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:N.Ref(a),PosixUser:{Uid:l,Gid:u},RootDirectory:{Path:c,CreationInfo:{OwnerUid:l,OwnerGid:u,Permissions:h}},AccessPointTags:[{Key:"Name",Value:`${y}-${c}`},{Key:"Environment",Value:s}]}},logicalId:f}}static setLifecyclePolicy(a,n){let{transitionToIA:i,transitionToPrimary:s=!1}=n;if(!a.Properties)a.Properties={};if(a.Properties.LifecyclePolicies=[],i){let c=`AFTER_${i}_DAYS`;a.Properties.LifecyclePolicies.push({TransitionToIA:c})}if(s)a.Properties.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"});return a}static enableBackup(a){if(!a.Properties)a.Properties={};return a.Properties.BackupPolicy={Status:"ENABLED"},a}static disableBackup(a){if(!a.Properties)a.Properties={};return a.Properties.BackupPolicy={Status:"DISABLED"},a}static setProvisionedThroughput(a,n){if(!a.Properties)a.Properties={};return a.Properties.ThroughputMode="provisioned",a.Properties.ProvisionedThroughputInMibps=n,a}static setElasticThroughput(a){if(!a.Properties)a.Properties={};return a.Properties.ThroughputMode="elastic",a}static enableMaxIO(a){if(!a.Properties)a.Properties={};return a.Properties.PerformanceMode="maxIO",a}static createEfsSecurityGroup(a){let{slug:n,environment:i,vpcId:s,sourceSecurityGroupIds:c=[],sourceCidrBlocks:l=[],description:u}=a,h=r({slug:n,environment:i,resourceType:"efs-sg"}),y=t(h),f=[];for(let S of c)f.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:S,Description:"NFS from security group"});for(let S of l)f.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,CidrIp:S,Description:"NFS from CIDR block"});return{securityGroup:{Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:h,GroupDescription:u||`Security group for EFS mount targets - ${n} ${i}`,VpcId:s,SecurityGroupIngress:f,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}},logicalId:y}}static createMultiAzMountTargets(a,n){let{slug:i,environment:s,subnetIds:c,securityGroupId:l}=n,u=[],h=[];for(let y=0;y<c.length;y++){let f=c[y],S=r({slug:i,environment:s,resourceType:"efs-mt"}),b=t(`${S}-az${y+1}`),C={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:N.Ref(a),SubnetId:f,SecurityGroups:[l]}};u.push(C),h.push(b)}return{mountTargets:u,logicalIds:h}}static createCompleteFileSystem(a){let{slug:n,environment:i,vpcId:s,subnetIds:c,sourceSecurityGroupIds:l=[],encrypted:u=!0,performanceMode:h="generalPurpose",throughputMode:y="elastic",enableBackup:f=!0,transitionToIA:S}=a,b={},{fileSystem:C,logicalId:T}=Ue.createFileSystem({slug:n,environment:i,encrypted:u,performanceMode:h,throughputMode:y,enableBackup:f});if(S)Ue.setLifecyclePolicy(C,{transitionToIA:S,transitionToPrimary:!0});b[T]=C;let{securityGroup:v,logicalId:w}=Ue.createEfsSecurityGroup({slug:n,environment:i,vpcId:s,sourceSecurityGroupIds:l});b[w]=v;let{mountTargets:R,logicalIds:k}=Ue.createMultiAzMountTargets(T,{slug:n,environment:i,subnetIds:c,securityGroupId:N.Ref(w)});for(let W=0;W<R.length;W++)b[k[W]]=R[W];return{resources:b,outputs:{fileSystemId:T,securityGroupId:w,mountTargetIds:k}}}}class m{static verifyDomain(a){let{domain:n,slug:i,environment:s,enableDkim:c=!0,dkimKeyLength:l="RSA_2048_BIT"}=a,u=r({slug:i,environment:s,resourceType:"ses-identity"}),h=t(`${u}-${n.replace(/\./g,"")}`),y={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:n,FeedbackAttributes:{EmailForwardingEnabled:!0}}};if(c)y.Properties.DkimSigningAttributes={NextSigningKeyLength:l};return{emailIdentity:y,logicalId:h}}static createDkimRecords(a,n,i){let s=[];for(let c=0;c<n.length;c++){let l=n[c],u=t(`dkim-${a.replace(/\./g,"")}-${c+1}`),h={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:`${l}._domainkey.${a}`,Type:"CNAME",TTL:1800,ResourceRecords:[`${l}.dkim.amazonses.com`]}};s.push({record:h,logicalId:u})}return s}static createConfigurationSet(a){let{slug:n,environment:i,name:s,reputationMetrics:c=!0,sendingEnabled:l=!0,suppressBounces:u=!0,suppressComplaints:h=!0}=a,y=s||r({slug:n,environment:i,resourceType:"ses-config"}),f=t(y),S=[];if(u)S.push("BOUNCE");if(h)S.push("COMPLAINT");return{configurationSet:{Type:"AWS::SES::ConfigurationSet",Properties:{Name:y,ReputationOptions:{ReputationMetricsEnabled:c},SendingOptions:{SendingEnabled:l},SuppressionOptions:{SuppressedReasons:S}}},logicalId:f}}static createReceiptRuleSet(a){let{slug:n,environment:i,name:s}=a,c=s||r({slug:n,environment:i,resourceType:"ses-ruleset"}),l=t(c);return{ruleSet:{Type:"AWS::SES::ReceiptRuleSet",Properties:{RuleSetName:c}},logicalId:l}}static createReceiptRule(a,n){let{slug:i,environment:s,ruleSetName:c,recipients:l,enabled:u=!0,scanEnabled:h=!0,tlsPolicy:y="Require",s3Action:f,lambdaAction:S,snsAction:b}=n,C=r({slug:i,environment:s,resourceType:"ses-rule"}),T=t(C),v=[];if(f)v.push({S3Action:{BucketName:f.bucketName,ObjectKeyPrefix:f.prefix,KmsKeyArn:f.kmsKeyArn}});if(S)v.push({LambdaAction:{FunctionArn:S.functionArn,InvocationType:S.invocationType||"Event"}});if(b)v.push({SNSAction:{TopicArn:b.topicArn,Encoding:b.encoding||"UTF-8"}});return{receiptRule:{Type:"AWS::SES::ReceiptRule",Properties:{RuleSetName:c,Rule:{Name:C,Enabled:u,ScanEnabled:h,TlsPolicy:y,Recipients:l,Actions:v.length>0?v:void 0}}},logicalId:T}}static createMxRecord(a,n,i){let s=t(`mx-${a.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n,Name:a,Type:"MX",TTL:300,ResourceRecords:[`10 inbound-smtp.${i}.amazonaws.com`]}},logicalId:s}}static createVerificationRecord(a,n,i){let s=t(`verification-${a.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:`_amazonses.${a}`,Type:"TXT",TTL:1800,ResourceRecords:[`"${n}"`]}},logicalId:s}}static getSmtpEndpoint(a){return`email-smtp.${a}.amazonaws.com`}static SmtpPorts={TLS:587,SSL:465,Unencrypted:25};static createSpfRecord(a,n,i){let{includeDomains:s=[],softFail:c=!1}=i||{},l=t(`spf-${a.replace(/\./g,"")}`),u="v=spf1 include:amazonses.com";for(let h of s)u+=` include:${h}`;return u+=c?" ~all":" -all",{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n,Name:a,Type:"TXT",TTL:300,ResourceRecords:[`"${u}"`]}},logicalId:l}}static createDmarcRecord(a,n,i){let{policy:s="none",subdomainPolicy:c,percentage:l=100,reportingEmail:u,forensicEmail:h}=i||{},y=t(`dmarc-${a.replace(/\./g,"")}`),f=`v=DMARC1; p=${s}; pct=${l}`;if(c)f+=`; sp=${c}`;if(u)f+=`; rua=mailto:${u}`;if(h)f+=`; ruf=mailto:${h}`;return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n,Name:`_dmarc.${a}`,Type:"TXT",TTL:300,ResourceRecords:[`"${f}"`]}},logicalId:y}}static createInboundEmailSetup(a){let{slug:n,environment:i,domain:s,s3BucketName:c,s3KeyPrefix:l="inbound/",region:u,hostedZoneId:h,lambdaFunctionArn:y,snsTopicArn:f}=a,S={},{ruleSet:b,logicalId:C}=m.createReceiptRuleSet({slug:n,environment:i});S[C]=b;let{receiptRule:T,logicalId:v}=m.createReceiptRule(C,{slug:n,environment:i,ruleSetName:b.Properties.RuleSetName||`${n}-${i}-receipt-rule-set`,recipients:[s],s3Action:{bucketName:c,prefix:l},lambdaAction:y?{functionArn:y,invocationType:"Event"}:void 0,snsAction:f?{topicArn:f}:void 0});S[v]=T;let{record:w,logicalId:R}=m.createMxRecord(s,h,u);return S[R]=w,{resources:S,outputs:{ruleSetLogicalId:C,ruleLogicalId:v,mxRecordLogicalId:R}}}static createCompleteDomainSetup(a){let{slug:n,environment:i,domain:s,hostedZoneId:c,region:l,enableInbound:u=!1,inboundS3Bucket:h,dmarcReportingEmail:y}=a,f={},{emailIdentity:S,logicalId:b}=m.verifyDomain({domain:s,slug:n,environment:i});f[b]=S;let{configurationSet:C,logicalId:T}=m.createConfigurationSet({slug:n,environment:i});f[T]=C;let{record:v,logicalId:w}=m.createSpfRecord(s,c);f[w]=v;let{record:R,logicalId:k}=m.createDmarcRecord(s,c,{policy:"none",reportingEmail:y||`dmarc-reports@${s}`});if(f[k]=R,u&&h){let W=m.createInboundEmailSetup({slug:n,environment:i,domain:s,s3BucketName:h,region:l,hostedZoneId:c});Object.assign(f,W.resources)}return{resources:f,outputs:{identityLogicalId:b,configSetLogicalId:T}}}static InboundSmtpEndpoints={"us-east-1":"inbound-smtp.us-east-1.amazonaws.com","us-west-2":"inbound-smtp.us-west-2.amazonaws.com","eu-west-1":"inbound-smtp.eu-west-1.amazonaws.com"};static supportsInboundEmail(a){return a in m.InboundSmtpEndpoints}static createEmailLambdaRole(a){let{slug:n,environment:i,s3BucketArn:s,sesIdentityArn:c}=a,l=r({slug:n,environment:i,resourceType:"email-lambda-role"}),u=t(l),h=t(`${l}-policy`),y={Type:"AWS::IAM::Role",Properties:{RoleName:l,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:i}]}},f=[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[s,`${s}/*`]}];if(c)f.push({Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:c});let S={Type:"AWS::IAM::Policy",Properties:{PolicyName:`${l}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:f},Roles:[N.Ref(u)]}};return{role:y,policy:S,roleLogicalId:u,policyLogicalId:h}}static createOutboundEmailLambda(a){let{slug:n,environment:i,roleArn:s,domain:c,configurationSetName:l,timeout:u=30,memorySize:h=256}=a,y=r({slug:n,environment:i,resourceType:"outbound-email"}),f=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:s,Timeout:u,MemorySize:h,Environment:{Variables:{DOMAIN:c,CONFIGURATION_SET:l||""}},Code:{ZipFile:m.LambdaCode.outboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},{Key:"Purpose",Value:"OutboundEmail"}]}},logicalId:f}}static createInboundEmailLambda(a){let{slug:n,environment:i,roleArn:s,s3BucketName:c,organizedPrefix:l="organized/",timeout:u=60,memorySize:h=512}=a,y=r({slug:n,environment:i,resourceType:"inbound-email"}),f=t(y),S=t(`${y}-permission`),b={Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:s,Timeout:u,MemorySize:h,Environment:{Variables:{S3_BUCKET:c,ORGANIZED_PREFIX:l}},Code:{ZipFile:m.LambdaCode.inboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},{Key:"Purpose",Value:"InboundEmail"}]}},C={Type:"AWS::Lambda::Permission",Properties:{FunctionName:N.Ref(f),Action:"lambda:InvokeFunction",Principal:"ses.amazonaws.com",SourceAccount:N.Ref("AWS::AccountId")}};return{function:b,permission:C,logicalId:f,permissionLogicalId:S}}static createEmailConversionLambda(a){let{slug:n,environment:i,roleArn:s,s3BucketName:c,convertedPrefix:l="converted/",timeout:u=60,memorySize:h=512}=a,y=r({slug:n,environment:i,resourceType:"email-conversion"}),f=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:s,Timeout:u,MemorySize:h,Environment:{Variables:{S3_BUCKET:c,CONVERTED_PREFIX:l}},Code:{ZipFile:m.LambdaCode.emailConversion},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},{Key:"Purpose",Value:"EmailConversion"}]}},logicalId:f}}static createEmailBucketNotification(a){let{lambdaArn:n,prefix:i="inbound/",suffix:s,events:c}=a,l=c??["s3:ObjectCreated:*"],u={};if(i||s){if(u.S3Key={Rules:[]},i)u.S3Key.Rules.push({Name:"prefix",Value:i});if(s)u.S3Key.Rules.push({Name:"suffix",Value:s})}return{notificationConfiguration:{LambdaConfigurations:[{Event:l[0],Function:n,Filter:Object.keys(u).length>0?u:void 0}]}}}static createS3LambdaPermission(a){let{slug:n,environment:i,lambdaLogicalId:s,s3BucketArn:c}=a,l=r({slug:n,environment:i,resourceType:"s3-lambda-permission"}),u=t(l);return{permission:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:N.Ref(s),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:c}},logicalId:u}}static createEmailProcessingStack(a){let{slug:n,environment:i,domain:s,s3BucketName:c,s3BucketArn:l,configurationSetName:u,enableInbound:h=!0,enableConversion:y=!0}=a,f={},{role:S,policy:b,roleLogicalId:C,policyLogicalId:T}=m.createEmailLambdaRole({slug:n,environment:i,s3BucketArn:l,sesIdentityArn:`arn:aws:ses:*:*:identity/${s}`});f[C]=S,f[T]=b;let{function:v,logicalId:w}=m.createOutboundEmailLambda({slug:n,environment:i,roleArn:N.GetAtt(C,"Arn"),domain:s,configurationSetName:u});f[w]=v;let R={roleLogicalId:C,outboundLambdaLogicalId:w};if(h){let{function:k,permission:W,logicalId:P,permissionLogicalId:V}=m.createInboundEmailLambda({slug:n,environment:i,roleArn:N.GetAtt(C,"Arn"),s3BucketName:c});f[P]=k,f[V]=W;let{permission:B,logicalId:j}=m.createS3LambdaPermission({slug:n,environment:i,lambdaLogicalId:P,s3BucketArn:l});f[j]=B,R.inboundLambdaLogicalId=P}if(y){let{function:k,logicalId:W}=m.createEmailConversionLambda({slug:n,environment:i,roleArn:N.GetAtt(C,"Arn"),s3BucketName:c});f[W]=k,R.conversionLambdaLogicalId=W}return{resources:f,outputs:R}}static LambdaCode={outboundEmail:`
624
624
  const { SESClient, SendRawEmailCommand } = require('@aws-sdk/client-ses');
625
625
  const ses = new SESClient({});
626
626
 
@@ -1166,7 +1166,7 @@ else if (encoding === 'quoted-printable') {
1166
1166
 
1167
1167
  return content;
1168
1168
  }
1169
- `}}var af={};_e(af,{default:()=>cr,handler:()=>va});var va=`
1169
+ `}}var af={};Be(af,{default:()=>cr,handler:()=>va});var va=`
1170
1170
  const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
1171
1171
  const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');
1172
1172
 
@@ -1658,7 +1658,7 @@ catch (error) {
1658
1658
 
1659
1659
  return { statusCode: 200, body: 'OK' };
1660
1660
  };
1661
- `;class Ue{static LambdaCode={incomingCall:va,voicemail:ur,missedCall:lr};static createConnectInstance(a){let{slug:n,environment:i,instanceAlias:s,inboundCallsEnabled:c=!0,outboundCallsEnabled:l=!0}=a;return{[`${n}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:s,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:c,OutboundCalls:l,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation(a){return{[`${a.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:a.instanceArn,Name:a.name,TimeZone:a.timezone,Config:a.schedule.map((n)=>({Day:n.day,StartTime:{Hours:n.startHour,Minutes:n.startMinute},EndTime:{Hours:n.endHour,Minutes:n.endMinute}}))}}}}static createQueue(a){return{[`${a.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:a.instanceArn,Name:a.name,HoursOfOperationArn:a.hoursOfOperationArn,MaxContacts:a.maxContacts||10}}}}static createContactFlow(a){return{[`${a.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:a.instanceArn,Name:a.name,Type:a.type,Content:a.content}}}}static createBasicIvrFlow(a){let n={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:a.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:a.queueArn},Transitions:{NextAction:a.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...a.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:a.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(n)}static createPhoneLambdaRole(a){return{[`${a.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${a.slug}-phone-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"PhoneLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"}]}}]}}}}static createIncomingCallLambda(a){return{[`${a.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Ue.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",CALL_LOG_TABLE:a.callLogTable||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createVoicemailLambda(a){return{[`${a.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:Ue.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:a.voicemailBucket,NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",CALL_LOG_TABLE:a.callLogTable||"",TRANSCRIPTION_ENABLED:a.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda(a){return{[`${a.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Ue.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",CALL_LOG_TABLE:a.callLogTable||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createCallLogTable(a){return{[`${a.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup(a){let n={},i={};Object.assign(n,Ue.createPhoneLambdaRole({slug:a.slug})),Object.assign(n,Ue.createCallLogTable({slug:a.slug})),n[`${a.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${a.slug}-phone-notifications`}},n[`${a.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${a.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let s={"Fn::GetAtt":[`${a.slug}PhoneLambdaRole`,"Arn"]},c={Ref:`${a.slug}PhoneNotificationTopic`},l={Ref:`${a.slug}CallLogTable`},u={Ref:`${a.slug}VoicemailBucket`};if(Object.assign(n,Ue.createIncomingCallLambda({slug:a.slug,roleArn:s,notificationTopicArn:c,callLogTable:l,webhookUrl:a.webhookUrl})),a.voicemailEnabled!==!1)Object.assign(n,Ue.createVoicemailLambda({slug:a.slug,roleArn:s,voicemailBucket:u,notificationTopicArn:c,callLogTable:l,transcriptionEnabled:a.transcriptionEnabled}));return Object.assign(n,Ue.createMissedCallLambda({slug:a.slug,roleArn:s,notificationTopicArn:c,callLogTable:l,webhookUrl:a.webhookUrl})),i[`${a.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${a.slug}PhoneNotificationTopic`}},i[`${a.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${a.slug}CallLogTable`}},i[`${a.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${a.slug}VoicemailBucket`}},{resources:n,outputs:i}}}class M{static createQueue(a){let{slug:n,environment:i,name:s,delaySeconds:c=0,visibilityTimeout:l=30,messageRetentionPeriod:u=345600,maxMessageSize:h=262144,receiveMessageWaitTime:y=0,fifo:f=!1,contentBasedDeduplication:S=!1,encrypted:b=!0,kmsKeyId:C}=a,T=s||r({slug:n,environment:i,resourceType:"queue"}),v=f?`${T}.fifo`:T,w=t(T),R={Type:"AWS::SQS::Queue",Properties:{QueueName:v,DelaySeconds:c,MaximumMessageSize:h,MessageRetentionPeriod:u,ReceiveMessageWaitTimeSeconds:y,VisibilityTimeout:l,Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:i}]}};if(f)R.Properties.FifoQueue=!0,R.Properties.ContentBasedDeduplication=S;if(b)if(C)R.Properties.KmsMasterKeyId=C;else R.Properties.SqsManagedSseEnabled=!0;return{queue:R,logicalId:w}}static createDeadLetterQueue(a,n){let{slug:i,environment:s,maxReceiveCount:c=3}=n,l=r({slug:i,environment:s,resourceType:"dlq"}),u=t(l),h={Type:"AWS::SQS::Queue",Properties:{QueueName:l,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s},{Key:"Type",Value:"DeadLetterQueue"}]}},y={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:N.GetAtt(u,"Arn"),maxReceiveCount:c}}};return{deadLetterQueue:h,updatedSourceQueue:y,deadLetterLogicalId:u}}static createSchedule(a,n){let{slug:i,environment:s,name:c,description:l,enabled:u=!0}=n,h=c||r({slug:i,environment:s,resourceType:"schedule"}),y=t(h);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:h,Description:l,ScheduleExpression:a,State:u?"ENABLED":"DISABLED",Targets:[]}},logicalId:y}}static scheduleEcsTask(a,n,i){let{slug:s,environment:c,name:l,description:u,enabled:h=!0,taskDefinitionArn:y,clusterArn:f,subnets:S,securityGroups:b=[],assignPublicIp:C=!1,taskCount:T=1,containerOverrides:v}=i,w=l||r({slug:s,environment:c,resourceType:"ecs-schedule"}),R=t(w),k={Id:"1",Arn:f,RoleArn:n,EcsParameters:{TaskDefinitionArn:y,TaskCount:T,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:S,SecurityGroups:b,AssignPublicIp:C?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(v&&v.length>0)k.Input=JSON.stringify({containerOverrides:v});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:w,Description:u||`Scheduled ECS task: ${y}`,ScheduleExpression:a,State:h?"ENABLED":"DISABLED",Targets:[k]}},logicalId:R}}static scheduleLambda(a,n){let{slug:i,environment:s,name:c,description:l,enabled:u=!0,functionArn:h,input:y}=n,f=c||r({slug:i,environment:s,resourceType:"lambda-schedule"}),S=t(f),b={Id:"1",Arn:h};if(y)b.Input=JSON.stringify(y);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:f,Description:l||`Scheduled Lambda: ${h}`,ScheduleExpression:a,State:u?"ENABLED":"DISABLED",Targets:[b]}},logicalId:S}}static scheduleSqsMessage(a,n){let{slug:i,environment:s,name:c,description:l,enabled:u=!0,queueArn:h,messageGroupId:y}=n,f=c||r({slug:i,environment:s,resourceType:"sqs-schedule"}),S=t(f),b={Id:"1",Arn:h};if(y)b.SqsParameters={MessageGroupId:y};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:f,Description:l||`Scheduled SQS message: ${h}`,ScheduleExpression:a,State:u?"ENABLED":"DISABLED",Targets:[b]}},logicalId:S}}static addTarget(a,n){if(!a.Properties.Targets)a.Properties.Targets=[];let i={Id:n.id,Arn:n.arn};if(n.roleArn)i.RoleArn=n.roleArn;if(n.input)i.Input=JSON.stringify(n.input);return a.Properties.Targets.push(i),a}static toCronExpression(a){if(a.startsWith("cron(")||a.startsWith("rate("))return a;return`cron(${a})`}static rateExpression(a,n){return`rate(${a} ${n})`}static CronExpressions={EveryMinute:"cron(* * * * ? *)",Every5Minutes:"cron(*/5 * * * ? *)",Every15Minutes:"cron(*/15 * * * ? *)",Every30Minutes:"cron(*/30 * * * ? *)",Hourly:"cron(0 * * * ? *)",Daily:"cron(0 0 * * ? *)",DailyAt9AM:"cron(0 9 * * ? *)",DailyAtMidnight:"cron(0 0 * * ? *)",Weekly:"cron(0 0 ? * SUN *)",Monthly:"cron(0 0 1 * ? *)"};static RateExpressions={Every1Minute:"rate(1 minute)",Every5Minutes:"rate(5 minutes)",Every10Minutes:"rate(10 minutes)",Every15Minutes:"rate(15 minutes)",Every30Minutes:"rate(30 minutes)",Every1Hour:"rate(1 hour)",Every6Hours:"rate(6 hours)",Every12Hours:"rate(12 hours)",Every1Day:"rate(1 day)"};static rateStringToExpression(a){let n=a.toLowerCase().trim(),i=n.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(i){let f=parseInt(i[1],10),S=i[2].toLowerCase(),b=S.endsWith("s")&&f===1?S.slice(0,-1):S,C=!S.endsWith("s")&&f>1?`${S}s`:S;return`rate(${f} ${f===1?b:C})`}let s=n.match(/^every\s+(minute|hour|day)$/i);if(s)return`rate(1 ${s[1]})`;let c={"every minute":"rate(1 minute)","every hour":"rate(1 hour)","every day":"rate(1 day)",hourly:"cron(0 * * * ? *)",daily:"cron(0 0 * * ? *)","daily at midnight":"cron(0 0 * * ? *)",weekly:"cron(0 0 ? * SUN *)",monthly:"cron(0 0 1 * ? *)",yearly:"cron(0 0 1 1 ? *)"};if(c[n])return c[n];let l=n.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(l){let f=parseInt(l[1],10),S=l[2]?.toLowerCase();if(S==="pm"&&f!==12)f+=12;else if(S==="am"&&f===12)f=0;return`cron(0 ${f} * * ? *)`}let u=n.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(u){let f=parseInt(u[1],10);return`cron(${parseInt(u[2],10)} ${f} * * ? *)`}let h={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},y=n.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(y)return`cron(0 0 ? * ${h[y[1].toLowerCase()]} *)`;return M.toCronExpression(a)}static JobConfig={create:(a)=>{let{name:n,handler:i,retries:s=3,backoff:c="exponential",backoffDelay:l=1000,maxDelay:u=30000,timeout:h=60000,jitter:y=!0}=a;return{name:n,handler:i,retries:s,backoff:c,backoffDelay:l,maxDelay:u,timeout:h,jitter:y}},calculateDelay:(a,n)=>{let{backoff:i,backoffDelay:s,maxDelay:c,jitter:l}=n,u;switch(i){case"linear":u=s*a;break;case"exponential":u=s*2**(a-1);break;case"fixed":default:u=s}if(u=Math.min(u,c||Number.MAX_SAFE_INTEGER),l){let h=u*0.25*Math.random();u+=h}return Math.floor(u)},presets:{fastRetry:{retries:5,backoff:"exponential",backoffDelay:100,maxDelay:5000,jitter:!0},standard:{retries:3,backoff:"exponential",backoffDelay:1000,maxDelay:30000,jitter:!0},longRunning:{retries:2,backoff:"exponential",backoffDelay:5000,maxDelay:60000,timeout:300000,jitter:!0},critical:{retries:10,backoff:"exponential",backoffDelay:500,maxDelay:60000,jitter:!0},noRetry:{retries:0,backoff:"fixed",backoffDelay:0,maxDelay:0,jitter:!1}}};static createJobContainerOverride(a){let{containerName:n,jobClass:i,jobData:s,environment:c={}}=a,l=[{name:"JOB_CLASS",value:i}];if(s)l.push({name:"JOB_DATA",value:JSON.stringify(s)});for(let[u,h]of Object.entries(c))l.push({name:u,value:h});return{name:n,command:["bun","run","app/Jobs/runner.ts"],environment:l}}static createScheduledJob(a){let{slug:n,environment:i,schedule:s,jobClass:c,jobData:l,taskDefinitionArn:u,clusterArn:h,subnets:y,securityGroups:f=[],roleArn:S,containerName:b="app"}=a,C=M.rateStringToExpression(s),T=M.createJobContainerOverride({containerName:b,jobClass:c,jobData:l});return M.scheduleEcsTask(C,S,{slug:n,environment:i,name:`${n}-${c.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${c}`,taskDefinitionArn:u,clusterArn:h,subnets:y,securityGroups:f,containerOverrides:[T]})}static QueuePresets={highThroughput:(a,n)=>M.createQueue({slug:a,environment:n,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:(a,n)=>M.createQueue({slug:a,environment:n,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:(a,n)=>M.createQueue({slug:a,environment:n,fifo:!0,contentBasedDeduplication:!0}),delayed:(a,n,i=60)=>M.createQueue({slug:a,environment:n,delaySeconds:i})}}class at{static async discoverJobs(a){let{projectRoot:n,jobsPath:i="app/Jobs"}=a,s=`${n}/${i}`,c=[];try{let l=await import("node:fs"),u=await import("node:path");if(!l.existsSync(s))return[];let h=l.readdirSync(s).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_")&&y!=="runner.ts");for(let y of h){let f=u.join(s,y),S=y.replace(".ts",""),b=l.readFileSync(f,"utf-8"),C=at.parseJobMetadata(b,S,f);if(C)c.push(C)}}catch{return[]}return c}static parseJobMetadata(a,n,i){let s=a.match(/export\s + const\s + schedule\s*=\s*['"`]([^'"`]+)['"`]/)||a.match(/schedule:\s*['"`]([^'"`]+)['"`]/),c=a.match(/export\s+const\s+enabled\s*=\s*(true|false)/)||a.match(/enabled:\s*(true|false)/),l=a.match(/export\s+const\s+retries\s*=\s*(\d+)/)||a.match(/retries:\s*(\d+)/),u=a.match(/export\s+const\s+timeout\s*=\s*(\d+)/)||a.match(/timeout:\s*(\d+)/),h=a.match(/export\s+const\s+backoff\s*=\s*['"`](linear|exponential|fixed)['"`]/)||a.match(/backoff:\s*['"`](linear|exponential|fixed)['"`]/),y=a.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||a.match(/description:\s*['"`]([^'"`]+)['"`]/);if(!(a.includes("export async function handle")||a.includes("export function handle")||a.includes("export default")))return null;return{name:n,path:i,schedule:s?.[1],handler:`${n}.handle`,enabled:c?.[1]!=="false",retries:l?parseInt(l[1],10):void 0,backoff:h?.[1],timeout:u?parseInt(u[1],10):void 0,description:y?.[1]}}static async discoverActions(a){let{projectRoot:n,actionsPath:i="app/Actions"}=a,s=`${n}/${i}`,c=[];try{let l=await import("node:fs"),u=await import("node:path");if(!l.existsSync(s))return[];let h=l.readdirSync(s).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_"));for(let y of h){let f=u.join(s,y),S=y.replace(".ts",""),b=l.readFileSync(f,"utf-8"),C=at.parseActionMetadata(b,S,f);if(C)c.push(C)}}catch{return[]}return c}static parseActionMetadata(a,n,i){if(!(a.includes("export async function handle")||a.includes("export function handle")||a.includes("export default")))return null;let s=a.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||a.match(/description:\s*['"`]([^'"`]+)['"`]/);return{name:n,path:i,handler:`${n}.handle`,description:s?.[1]}}static generateScheduledJobResources(a){let{slug:n,environment:i,jobs:s,taskDefinitionArn:c,clusterArn:l,subnets:u,securityGroups:h=[],roleArn:y,containerName:f="app"}=a,S={},b=0;for(let C of s){if(!C.schedule||!C.enabled)continue;let{rule:T,logicalId:v}=M.createScheduledJob({slug:n,environment:i,schedule:C.schedule,jobClass:C.name,taskDefinitionArn:c,clusterArn:l,subnets:u,securityGroups:h,roleArn:y,containerName:f});S[v]=T,b++}return{rules:S,count:b}}static generateJobRunnerScript(){return`#!/usr/bin/env bun
1661
+ `;class Qe{static LambdaCode={incomingCall:va,voicemail:ur,missedCall:lr};static createConnectInstance(a){let{slug:n,environment:i,instanceAlias:s,inboundCallsEnabled:c=!0,outboundCallsEnabled:l=!0}=a;return{[`${n}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:s,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:c,OutboundCalls:l,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation(a){return{[`${a.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:a.instanceArn,Name:a.name,TimeZone:a.timezone,Config:a.schedule.map((n)=>({Day:n.day,StartTime:{Hours:n.startHour,Minutes:n.startMinute},EndTime:{Hours:n.endHour,Minutes:n.endMinute}}))}}}}static createQueue(a){return{[`${a.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:a.instanceArn,Name:a.name,HoursOfOperationArn:a.hoursOfOperationArn,MaxContacts:a.maxContacts||10}}}}static createContactFlow(a){return{[`${a.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:a.instanceArn,Name:a.name,Type:a.type,Content:a.content}}}}static createBasicIvrFlow(a){let n={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:a.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:a.queueArn},Transitions:{NextAction:a.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...a.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:a.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(n)}static createPhoneLambdaRole(a){return{[`${a.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${a.slug}-phone-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"PhoneLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"}]}}]}}}}static createIncomingCallLambda(a){return{[`${a.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Qe.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",CALL_LOG_TABLE:a.callLogTable||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createVoicemailLambda(a){return{[`${a.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:Qe.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:a.voicemailBucket,NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",CALL_LOG_TABLE:a.callLogTable||"",TRANSCRIPTION_ENABLED:a.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda(a){return{[`${a.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Qe.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",CALL_LOG_TABLE:a.callLogTable||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createCallLogTable(a){return{[`${a.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup(a){let n={},i={};Object.assign(n,Qe.createPhoneLambdaRole({slug:a.slug})),Object.assign(n,Qe.createCallLogTable({slug:a.slug})),n[`${a.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${a.slug}-phone-notifications`}},n[`${a.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${a.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let s={"Fn::GetAtt":[`${a.slug}PhoneLambdaRole`,"Arn"]},c={Ref:`${a.slug}PhoneNotificationTopic`},l={Ref:`${a.slug}CallLogTable`},u={Ref:`${a.slug}VoicemailBucket`};if(Object.assign(n,Qe.createIncomingCallLambda({slug:a.slug,roleArn:s,notificationTopicArn:c,callLogTable:l,webhookUrl:a.webhookUrl})),a.voicemailEnabled!==!1)Object.assign(n,Qe.createVoicemailLambda({slug:a.slug,roleArn:s,voicemailBucket:u,notificationTopicArn:c,callLogTable:l,transcriptionEnabled:a.transcriptionEnabled}));return Object.assign(n,Qe.createMissedCallLambda({slug:a.slug,roleArn:s,notificationTopicArn:c,callLogTable:l,webhookUrl:a.webhookUrl})),i[`${a.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${a.slug}PhoneNotificationTopic`}},i[`${a.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${a.slug}CallLogTable`}},i[`${a.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${a.slug}VoicemailBucket`}},{resources:n,outputs:i}}}class M{static createQueue(a){let{slug:n,environment:i,name:s,delaySeconds:c=0,visibilityTimeout:l=30,messageRetentionPeriod:u=345600,maxMessageSize:h=262144,receiveMessageWaitTime:y=0,fifo:f=!1,contentBasedDeduplication:S=!1,encrypted:b=!0,kmsKeyId:C}=a,T=s||r({slug:n,environment:i,resourceType:"queue"}),v=f?`${T}.fifo`:T,w=t(T),R={Type:"AWS::SQS::Queue",Properties:{QueueName:v,DelaySeconds:c,MaximumMessageSize:h,MessageRetentionPeriod:u,ReceiveMessageWaitTimeSeconds:y,VisibilityTimeout:l,Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:i}]}};if(f)R.Properties.FifoQueue=!0,R.Properties.ContentBasedDeduplication=S;if(b)if(C)R.Properties.KmsMasterKeyId=C;else R.Properties.SqsManagedSseEnabled=!0;return{queue:R,logicalId:w}}static createDeadLetterQueue(a,n){let{slug:i,environment:s,maxReceiveCount:c=3}=n,l=r({slug:i,environment:s,resourceType:"dlq"}),u=t(l),h={Type:"AWS::SQS::Queue",Properties:{QueueName:l,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s},{Key:"Type",Value:"DeadLetterQueue"}]}},y={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:N.GetAtt(u,"Arn"),maxReceiveCount:c}}};return{deadLetterQueue:h,updatedSourceQueue:y,deadLetterLogicalId:u}}static createSchedule(a,n){let{slug:i,environment:s,name:c,description:l,enabled:u=!0}=n,h=c||r({slug:i,environment:s,resourceType:"schedule"}),y=t(h);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:h,Description:l,ScheduleExpression:a,State:u?"ENABLED":"DISABLED",Targets:[]}},logicalId:y}}static scheduleEcsTask(a,n,i){let{slug:s,environment:c,name:l,description:u,enabled:h=!0,taskDefinitionArn:y,clusterArn:f,subnets:S,securityGroups:b=[],assignPublicIp:C=!1,taskCount:T=1,containerOverrides:v}=i,w=l||r({slug:s,environment:c,resourceType:"ecs-schedule"}),R=t(w),k={Id:"1",Arn:f,RoleArn:n,EcsParameters:{TaskDefinitionArn:y,TaskCount:T,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:S,SecurityGroups:b,AssignPublicIp:C?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(v&&v.length>0)k.Input=JSON.stringify({containerOverrides:v});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:w,Description:u||`Scheduled ECS task: ${y}`,ScheduleExpression:a,State:h?"ENABLED":"DISABLED",Targets:[k]}},logicalId:R}}static scheduleLambda(a,n){let{slug:i,environment:s,name:c,description:l,enabled:u=!0,functionArn:h,input:y}=n,f=c||r({slug:i,environment:s,resourceType:"lambda-schedule"}),S=t(f),b={Id:"1",Arn:h};if(y)b.Input=JSON.stringify(y);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:f,Description:l||`Scheduled Lambda: ${h}`,ScheduleExpression:a,State:u?"ENABLED":"DISABLED",Targets:[b]}},logicalId:S}}static scheduleSqsMessage(a,n){let{slug:i,environment:s,name:c,description:l,enabled:u=!0,queueArn:h,messageGroupId:y}=n,f=c||r({slug:i,environment:s,resourceType:"sqs-schedule"}),S=t(f),b={Id:"1",Arn:h};if(y)b.SqsParameters={MessageGroupId:y};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:f,Description:l||`Scheduled SQS message: ${h}`,ScheduleExpression:a,State:u?"ENABLED":"DISABLED",Targets:[b]}},logicalId:S}}static addTarget(a,n){if(!a.Properties.Targets)a.Properties.Targets=[];let i={Id:n.id,Arn:n.arn};if(n.roleArn)i.RoleArn=n.roleArn;if(n.input)i.Input=JSON.stringify(n.input);return a.Properties.Targets.push(i),a}static toCronExpression(a){if(a.startsWith("cron(")||a.startsWith("rate("))return a;return`cron(${a})`}static rateExpression(a,n){return`rate(${a} ${n})`}static CronExpressions={EveryMinute:"cron(* * * * ? *)",Every5Minutes:"cron(*/5 * * * ? *)",Every15Minutes:"cron(*/15 * * * ? *)",Every30Minutes:"cron(*/30 * * * ? *)",Hourly:"cron(0 * * * ? *)",Daily:"cron(0 0 * * ? *)",DailyAt9AM:"cron(0 9 * * ? *)",DailyAtMidnight:"cron(0 0 * * ? *)",Weekly:"cron(0 0 ? * SUN *)",Monthly:"cron(0 0 1 * ? *)"};static RateExpressions={Every1Minute:"rate(1 minute)",Every5Minutes:"rate(5 minutes)",Every10Minutes:"rate(10 minutes)",Every15Minutes:"rate(15 minutes)",Every30Minutes:"rate(30 minutes)",Every1Hour:"rate(1 hour)",Every6Hours:"rate(6 hours)",Every12Hours:"rate(12 hours)",Every1Day:"rate(1 day)"};static rateStringToExpression(a){let n=a.toLowerCase().trim(),i=n.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(i){let f=parseInt(i[1],10),S=i[2].toLowerCase(),b=S.endsWith("s")&&f===1?S.slice(0,-1):S,C=!S.endsWith("s")&&f>1?`${S}s`:S;return`rate(${f} ${f===1?b:C})`}let s=n.match(/^every\s+(minute|hour|day)$/i);if(s)return`rate(1 ${s[1]})`;let c={"every minute":"rate(1 minute)","every hour":"rate(1 hour)","every day":"rate(1 day)",hourly:"cron(0 * * * ? *)",daily:"cron(0 0 * * ? *)","daily at midnight":"cron(0 0 * * ? *)",weekly:"cron(0 0 ? * SUN *)",monthly:"cron(0 0 1 * ? *)",yearly:"cron(0 0 1 1 ? *)"};if(c[n])return c[n];let l=n.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(l){let f=parseInt(l[1],10),S=l[2]?.toLowerCase();if(S==="pm"&&f!==12)f+=12;else if(S==="am"&&f===12)f=0;return`cron(0 ${f} * * ? *)`}let u=n.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(u){let f=parseInt(u[1],10);return`cron(${parseInt(u[2],10)} ${f} * * ? *)`}let h={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},y=n.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(y)return`cron(0 0 ? * ${h[y[1].toLowerCase()]} *)`;return M.toCronExpression(a)}static JobConfig={create:(a)=>{let{name:n,handler:i,retries:s=3,backoff:c="exponential",backoffDelay:l=1000,maxDelay:u=30000,timeout:h=60000,jitter:y=!0}=a;return{name:n,handler:i,retries:s,backoff:c,backoffDelay:l,maxDelay:u,timeout:h,jitter:y}},calculateDelay:(a,n)=>{let{backoff:i,backoffDelay:s,maxDelay:c,jitter:l}=n,u;switch(i){case"linear":u=s*a;break;case"exponential":u=s*2**(a-1);break;case"fixed":default:u=s}if(u=Math.min(u,c||Number.MAX_SAFE_INTEGER),l){let h=u*0.25*Math.random();u+=h}return Math.floor(u)},presets:{fastRetry:{retries:5,backoff:"exponential",backoffDelay:100,maxDelay:5000,jitter:!0},standard:{retries:3,backoff:"exponential",backoffDelay:1000,maxDelay:30000,jitter:!0},longRunning:{retries:2,backoff:"exponential",backoffDelay:5000,maxDelay:60000,timeout:300000,jitter:!0},critical:{retries:10,backoff:"exponential",backoffDelay:500,maxDelay:60000,jitter:!0},noRetry:{retries:0,backoff:"fixed",backoffDelay:0,maxDelay:0,jitter:!1}}};static createJobContainerOverride(a){let{containerName:n,jobClass:i,jobData:s,environment:c={}}=a,l=[{name:"JOB_CLASS",value:i}];if(s)l.push({name:"JOB_DATA",value:JSON.stringify(s)});for(let[u,h]of Object.entries(c))l.push({name:u,value:h});return{name:n,command:["bun","run","app/Jobs/runner.ts"],environment:l}}static createScheduledJob(a){let{slug:n,environment:i,schedule:s,jobClass:c,jobData:l,taskDefinitionArn:u,clusterArn:h,subnets:y,securityGroups:f=[],roleArn:S,containerName:b="app"}=a,C=M.rateStringToExpression(s),T=M.createJobContainerOverride({containerName:b,jobClass:c,jobData:l});return M.scheduleEcsTask(C,S,{slug:n,environment:i,name:`${n}-${c.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${c}`,taskDefinitionArn:u,clusterArn:h,subnets:y,securityGroups:f,containerOverrides:[T]})}static QueuePresets={highThroughput:(a,n)=>M.createQueue({slug:a,environment:n,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:(a,n)=>M.createQueue({slug:a,environment:n,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:(a,n)=>M.createQueue({slug:a,environment:n,fifo:!0,contentBasedDeduplication:!0}),delayed:(a,n,i=60)=>M.createQueue({slug:a,environment:n,delaySeconds:i})}}class ct{static async discoverJobs(a){let{projectRoot:n,jobsPath:i="app/Jobs"}=a,s=`${n}/${i}`,c=[];try{let l=await import("node:fs"),u=await import("node:path");if(!l.existsSync(s))return[];let h=l.readdirSync(s).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_")&&y!=="runner.ts");for(let y of h){let f=u.join(s,y),S=y.replace(".ts",""),b=l.readFileSync(f,"utf-8"),C=ct.parseJobMetadata(b,S,f);if(C)c.push(C)}}catch{return[]}return c}static parseJobMetadata(a,n,i){let s=a.match(/export\s + const\s + schedule\s*=\s*['"`]([^'"`]+)['"`]/)||a.match(/schedule:\s*['"`]([^'"`]+)['"`]/),c=a.match(/export\s+const\s+enabled\s*=\s*(true|false)/)||a.match(/enabled:\s*(true|false)/),l=a.match(/export\s+const\s+retries\s*=\s*(\d+)/)||a.match(/retries:\s*(\d+)/),u=a.match(/export\s+const\s+timeout\s*=\s*(\d+)/)||a.match(/timeout:\s*(\d+)/),h=a.match(/export\s+const\s+backoff\s*=\s*['"`](linear|exponential|fixed)['"`]/)||a.match(/backoff:\s*['"`](linear|exponential|fixed)['"`]/),y=a.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||a.match(/description:\s*['"`]([^'"`]+)['"`]/);if(!(a.includes("export async function handle")||a.includes("export function handle")||a.includes("export default")))return null;return{name:n,path:i,schedule:s?.[1],handler:`${n}.handle`,enabled:c?.[1]!=="false",retries:l?parseInt(l[1],10):void 0,backoff:h?.[1],timeout:u?parseInt(u[1],10):void 0,description:y?.[1]}}static async discoverActions(a){let{projectRoot:n,actionsPath:i="app/Actions"}=a,s=`${n}/${i}`,c=[];try{let l=await import("node:fs"),u=await import("node:path");if(!l.existsSync(s))return[];let h=l.readdirSync(s).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_"));for(let y of h){let f=u.join(s,y),S=y.replace(".ts",""),b=l.readFileSync(f,"utf-8"),C=ct.parseActionMetadata(b,S,f);if(C)c.push(C)}}catch{return[]}return c}static parseActionMetadata(a,n,i){if(!(a.includes("export async function handle")||a.includes("export function handle")||a.includes("export default")))return null;let s=a.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||a.match(/description:\s*['"`]([^'"`]+)['"`]/);return{name:n,path:i,handler:`${n}.handle`,description:s?.[1]}}static generateScheduledJobResources(a){let{slug:n,environment:i,jobs:s,taskDefinitionArn:c,clusterArn:l,subnets:u,securityGroups:h=[],roleArn:y,containerName:f="app"}=a,S={},b=0;for(let C of s){if(!C.schedule||!C.enabled)continue;let{rule:T,logicalId:v}=M.createScheduledJob({slug:n,environment:i,schedule:C.schedule,jobClass:C.name,taskDefinitionArn:c,clusterArn:l,subnets:u,securityGroups:h,roleArn:y,containerName:f});S[v]=T,b++}return{rules:S,count:b}}static generateJobRunnerScript(){return`#!/usr/bin/env bun
1662
1662
  /**
1663
1663
  * Job Runner Script
1664
1664
  * This script is invoked by ECS scheduled tasks to run jobs
@@ -1703,7 +1703,7 @@ catch (error) {
1703
1703
  }
1704
1704
 
1705
1705
  run()
1706
- `}static async generateJobManifest(a){let n=await at.discoverJobs(a),i=n.filter((s)=>s.schedule&&s.enabled);return{jobs:n,scheduledCount:i.length,totalCount:n.length}}}var By={loadJobs:at.discoverJobs,loadActions:at.discoverActions,generateScheduledJobs:at.generateScheduledJobResources,generateRunner:at.generateJobRunnerScript,paths:{jobs:"app/Jobs",actions:"app/Actions",runner:"app/Jobs/runner.ts"}},dr=`
1706
+ `}static async generateJobManifest(a){let n=await ct.discoverJobs(a),i=n.filter((s)=>s.schedule&&s.enabled);return{jobs:n,scheduledCount:i.length,totalCount:n.length}}}var By={loadJobs:ct.discoverJobs,loadActions:ct.discoverActions,generateScheduledJobs:ct.generateScheduledJobResources,generateRunner:ct.generateJobRunnerScript,paths:{jobs:"app/Jobs",actions:"app/Actions",runner:"app/Jobs/runner.ts"}},dr=`
1707
1707
  const { DynamoDBClient, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
1708
1708
  const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
1709
1709
 
@@ -1978,7 +1978,7 @@ catch (error) {
1978
1978
 
1979
1979
  return { statusCode: 200, body: 'OK' };
1980
1980
  };
1981
- `,cf={};_e(cf,{default:()=>pr,handler:()=>wa});var wa=`
1981
+ `,cf={};Be(cf,{default:()=>pr,handler:()=>wa});var wa=`
1982
1982
  const { PinpointClient, SendMessagesCommand } = require('@aws-sdk/client-pinpoint');
1983
1983
  const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
1984
1984
  const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');
@@ -2306,14 +2306,14 @@ function resolveTemplate(template, data) {
2306
2306
  }
2307
2307
  return result;
2308
2308
  }
2309
- `;class F{static LambdaCode={send:wa,receive:mr,deliveryStatus:dr};static createPinpointApp(a){return{[`${a.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:a.name||`${a.slug}-sms`}}}}static createSmsChannel(a){let n={ApplicationId:a.applicationId,Enabled:a.enabled!==!1};if(a.senderId)n.SenderId=a.senderId;if(a.shortCode)n.ShortCode=a.shortCode;return{[`${a.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:n}}}static createSmsLambdaRole(a){return{[`${a.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${a.slug}-sms-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda(a){return{[`${a.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:F.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:a.pinpointAppId,MESSAGE_LOG_TABLE:a.messageLogTable||"",SMS_SENDER_ID:a.senderId||"",SMS_ORIGINATION_NUMBER:a.originationNumber||""}}}}}}static createReceiveLambda(a){return{[`${a.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:F.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:a.optOutTable||"",MESSAGE_LOG_TABLE:a.messageLogTable||"",NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createDeliveryStatusLambda(a){return{[`${a.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:F.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:a.messageLogTable||"",NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createMessageLogTable(a){return{[`${a.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable(a){return{[`${a.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic(a){return{[`${a.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${a.slug}-sms-notifications`}}}}static createCompleteSetup(a){let n={},i={};Object.assign(n,F.createPinpointApp({slug:a.slug})),Object.assign(n,F.createSmsChannel({slug:a.slug,applicationId:{Ref:`${a.slug}PinpointApp`},senderId:a.senderId})),Object.assign(n,F.createSmsLambdaRole({slug:a.slug})),Object.assign(n,F.createMessageLogTable({slug:a.slug})),Object.assign(n,F.createOptOutTable({slug:a.slug})),Object.assign(n,F.createNotificationTopic({slug:a.slug}));let s={"Fn::GetAtt":[`${a.slug}SmsLambdaRole`,"Arn"]},c={Ref:`${a.slug}PinpointApp`},l={Ref:`${a.slug}SmsMessageLogTable`},u={Ref:`${a.slug}SmsOptOutTable`},h={Ref:`${a.slug}SmsNotificationTopic`};if(Object.assign(n,F.createSendLambda({slug:a.slug,roleArn:s,pinpointAppId:c,messageLogTable:l,senderId:a.senderId,originationNumber:a.originationNumber})),a.twoWayEnabled)Object.assign(n,F.createReceiveLambda({slug:a.slug,roleArn:s,optOutTable:u,messageLogTable:l,notificationTopicArn:h,webhookUrl:a.webhookUrl}));return Object.assign(n,F.createDeliveryStatusLambda({slug:a.slug,roleArn:s,messageLogTable:l,notificationTopicArn:h,webhookUrl:a.webhookUrl})),i[`${a.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${a.slug}PinpointApp`}},i[`${a.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${a.slug}SmsSendLambda`,"Arn"]}},i[`${a.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${a.slug}SmsNotificationTopic`}},i[`${a.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${a.slug}SmsMessageLogTable`}},{resources:n,outputs:i}}}function wt(a){return a.replace(/[^a-zA-Z0-9]/g," ").trim().split(/\s+/).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")||"User"}function gr(a,n){let i=(a||n).replace(/^\/+|\/+$/g,"");if(!i||i.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${n}`);return i}function hr(a){let n=a.storage;if(n?.type==="efs"){let s="fileSystemId"in n?n.fileSystemId:void 0;if(!s||typeof s==="string"&&!s.trim())throw Error("sftp: EFS storage requires fileSystemId, or a fileSystem name defined in infrastructure.fileSystem");return{type:"efs",fileSystemId:s,posixProfile:n.posixProfile}}let i=(n?.type==="s3"?n.bucket??a.bucket:a.bucket)?.trim();if(!i)throw Error("sftp: S3 storage requires bucket, or a storageBucket name defined in infrastructure.storage");return{type:"s3",bucket:i}}function yr(a,n,i){let s=n.posixProfile??i;if(!s)throw Error(`sftp: user ${a} requires a posixProfile (uid/gid) on an EFS-backed server`);for(let c of[s.uid,s.gid,...s.secondaryGids??[]])if(!Number.isInteger(c)||c<0||c>4294967295)throw Error(`sftp: user ${a} has an invalid posixProfile id ${c}`);return{Uid:s.uid,Gid:s.gid,...s.secondaryGids?.length?{SecondaryGids:s.secondaryGids}:{}}}function fr(a,n){return typeof a==="string"?`/${a}/${n}`:{"Fn::Sub":[`/\${FileSystemId}/${n}`,{FileSystemId:a}]}}function Sr(a){return typeof a==="string"?{"Fn::Sub":"arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}".replace("${FileSystemId}",a)}:{"Fn::Sub":["arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}",{FileSystemId:a}]}}class nd{static create(a){let n=hr(a),i=n.type==="efs"?"EFS":"S3",s=a.endpointType??"PUBLIC";if(s==="VPC"&&(!a.endpointDetails?.vpcId||!a.endpointDetails.subnetIds.length))throw Error("sftp: VPC endpoints require endpointDetails.vpcId and at least one subnet");let c=`${wt(a.slug)}${wt(a.environment)}Sftp`,l=`${c}Server`,u={},h;if(a.logging!==!1){let y=`${c}LoggingRole`;u[y]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TransferLogging",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:DescribeLogStreams","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:log-group:/aws/transfer/*"}]}}]}},h={"Fn::GetAtt":[y,"Arn"]}}u[l]={Type:"AWS::Transfer::Server",Properties:{Domain:i,EndpointType:s,IdentityProviderType:"SERVICE_MANAGED",Protocols:["SFTP"],...s==="VPC"?{EndpointDetails:{VpcId:a.endpointDetails.vpcId,SubnetIds:a.endpointDetails.subnetIds,...a.endpointDetails.securityGroupIds?.length?{SecurityGroupIds:a.endpointDetails.securityGroupIds}:{},...a.endpointDetails.addressAllocationIds?.length?{AddressAllocationIds:a.endpointDetails.addressAllocationIds}:{}}}:{},...a.securityPolicyName?{SecurityPolicyName:a.securityPolicyName}:{},...h?{LoggingRole:h}:{},Tags:[{Key:"Project",Value:a.slug},{Key:"Environment",Value:a.environment},{Key:"ManagedBy",Value:"ts-cloud"}]}};for(let[y,f]of Object.entries(a.users)){if(!/^[a-zA-Z0-9_.@-]{3,100}$/.test(y))throw Error(`sftp: invalid username ${y}`);if(!f.sshPublicKeys.length)throw Error(`sftp: user ${y} requires at least one SSH public key`);let S=wt(y),b=gr(f.homeDirectory,y),C=`${c}${S}User`,T=f.roleArn;if(!T){let v=`${c}${S}Role`,w;if(n.type==="efs")w=[{Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:DescribeMountTargets"],Resource:Sr(n.fileSystemId)}];else{let R=`arn:aws:s3:::${n.bucket}`;w=[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:R,Condition:{StringLike:{"s3:prefix":[b,`${b}/*`]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:GetObjectVersion"],Resource:`${R}/${b}/*`}]}u[v]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"SftpHomeDirectory",PolicyDocument:{Version:"2012-10-17",Statement:w}}]}},T={"Fn::GetAtt":[v,"Arn"]}}u[C]={Type:"AWS::Transfer::User",DependsOn:[l],Properties:{ServerId:{Ref:l},UserName:y,Role:T,HomeDirectoryType:"PATH",HomeDirectory:n.type==="efs"?fr(n.fileSystemId,b):`/${n.bucket}/${b}`,...n.type==="efs"?{PosixProfile:yr(y,f,n.posixProfile)}:{},SshPublicKeys:f.sshPublicKeys}}}return{resources:u,serverLogicalId:l,domain:i}}}class be{static createBedrockRole(a,n){let{slug:i,environment:s,name:c,models:l=["*"],allowStreaming:u=!0}=n,h=c||r({slug:i,environment:s,resourceType:"bedrock-role"}),y=t(h),f=["bedrock:InvokeModel"];if(u)f.push("bedrock:InvokeModelWithResponseStream");let S=l.map((b)=>b==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${b}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:h,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:a},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${h}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:f,Resource:S}]}}],Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:s}]}},logicalId:y}}static createBedrockPolicy(a){let{slug:n,environment:i,name:s,models:c=["*"],allowInvoke:l=!0,allowStreaming:u=!0,allowAsync:h=!1}=a,y=s||r({slug:n,environment:i,resourceType:"bedrock-policy"}),f=t(y),S=[];if(l)S.push("bedrock:InvokeModel");if(u)S.push("bedrock:InvokeModelWithResponseStream");if(h)S.push("bedrock:InvokeModelAsync");let b=c.map((C)=>C==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${C}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:y,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:S,Resource:b}]}}},logicalId:f}}static enableBedrockForLambda(a){return be.createBedrockRole("lambda.amazonaws.com",a)}static enableBedrockForEcs(a){return be.createBedrockRole("ecs-tasks.amazonaws.com",a)}static enableBedrockForEc2(a){return be.createBedrockRole("ec2.amazonaws.com",a)}static addBedrockPermissions(a,n=["*"],i=!0){let s=["bedrock:InvokeModel"];if(i)s.push("bedrock:InvokeModelWithResponseStream");let c=n.map((l)=>l==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${l}`);if(!a.Properties.Policies)a.Properties.Policies=[];return a.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:s,Resource:c}]}}),a}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}}class Ft{static createPostgres(a){return Ft.createRDSInstance("postgres","16.2",a)}static createMysql(a){return Ft.createRDSInstance("mysql","8.0.35",a)}static createRDSInstance(a,n,i){let{slug:s,environment:c,instanceClass:l="db.t3.micro",allocatedStorage:u=20,storageType:h="gp3",masterUsername:y="admin",masterPassword:f,databaseName:S,subnetIds:b,securityGroupIds:C,encrypted:T=!0,kmsKeyId:v,multiAz:w=!1,backupRetentionDays:R=7,publiclyAccessible:k=!1,enableCloudwatchLogs:W=!0,deletionProtection:P=!0}=i,V=r({slug:s,environment:c,resourceType:`${a}-db`}),B=t(V),j,Z;if(b&&b.length>0){let ee=r({slug:s,environment:c,resourceType:"db-subnet-group"});Z=t(ee),j={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:ee,DBSubnetGroupDescription:`Subnet group for ${V}`,SubnetIds:b,Tags:[{Key:"Name",Value:ee},{Key:"Environment",Value:c}]}}}let K={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:V,DBInstanceClass:l,Engine:a,EngineVersion:n,MasterUsername:y,MasterUserPassword:f,AllocatedStorage:u,StorageType:h,StorageEncrypted:T,MultiAZ:w,BackupRetentionPeriod:R,PubliclyAccessible:k,DeletionProtection:P,Tags:[{Key:"Name",Value:V},{Key:"Environment",Value:c}]}};if(S)K.Properties.DBName=S;if(v)K.Properties.KmsKeyId=v;if(Z)K.Properties.DBSubnetGroupName=N.Ref(Z);if(C&&C.length>0)K.Properties.VPCSecurityGroups=C;if(W)K.Properties.EnableCloudwatchLogsExports=a==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:K,subnetGroup:j,logicalId:B,subnetGroupId:Z}}static createReadReplica(a,n){let{slug:i,environment:s,instanceClass:c="db.t3.micro",securityGroupIds:l,publiclyAccessible:u=!1}=n,h=r({slug:i,environment:s,resourceType:"db-replica"}),y=t(h),f={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:h,DBInstanceClass:c,SourceDBInstanceIdentifier:N.Ref(a),PubliclyAccessible:u,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:s},{Key:"Type",Value:"ReadReplica"}]}};if(l&&l.length>0)f.Properties.VPCSecurityGroups=l;return{replica:f,logicalId:y}}static createParameterGroup(a,n,i){let{slug:s,environment:c,parameters:l={}}=i,u=r({slug:s,environment:c,resourceType:"db-params"}),h=t(u),y=a==="postgres"?`postgres${n.split(".")[0]}`:`mysql${n.split(".")[0]}.${n.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:u,Description:`Parameter group for ${u}`,Family:y,Parameters:l,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:c}]}},logicalId:h}}static enableBackup(a,n=7){return a.Properties.BackupRetentionPeriod=n,a}static createTable(a){let{slug:n,environment:i,tableName:s,partitionKey:c,sortKey:l,billingMode:u="PAY_PER_REQUEST",readCapacity:h=5,writeCapacity:y=5,streamEnabled:f=!1,streamViewType:S="NEW_AND_OLD_IMAGES",encrypted:b=!0,kmsKeyId:C,pointInTimeRecovery:T=!0,ttlAttribute:v}=a,w=s||r({slug:n,environment:i,resourceType:"table"}),R=t(w),k=[{AttributeName:c.name,AttributeType:c.type}];if(l)k.push({AttributeName:l.name,AttributeType:l.type});let W=[{AttributeName:c.name,KeyType:"HASH"}];if(l)W.push({AttributeName:l.name,KeyType:"RANGE"});let P={Type:"AWS::DynamoDB::Table",Properties:{TableName:w,BillingMode:u,AttributeDefinitions:k,KeySchema:W,Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:i}]}};if(u==="PROVISIONED")P.Properties.ProvisionedThroughput={ReadCapacityUnits:h,WriteCapacityUnits:y};if(f)P.Properties.StreamSpecification={StreamViewType:S};if(b)P.Properties.SSESpecification={SSEEnabled:!0,SSEType:C?"KMS":"AES256",KMSMasterKeyId:C};if(T)P.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(v)P.Properties.TimeToLiveSpecification={AttributeName:v,Enabled:!0};return{table:P,logicalId:R}}static addGlobalSecondaryIndex(a,n){let{indexName:i,partitionKey:s,sortKey:c,projectionType:l="ALL",nonKeyAttributes:u,readCapacity:h=5,writeCapacity:y=5}=n;if(!a.Properties.AttributeDefinitions.some((b)=>b.AttributeName===s.name))a.Properties.AttributeDefinitions.push({AttributeName:s.name,AttributeType:s.type});if(c&&!a.Properties.AttributeDefinitions.some((b)=>b.AttributeName===c.name))a.Properties.AttributeDefinitions.push({AttributeName:c.name,AttributeType:c.type});let f=[{AttributeName:s.name,KeyType:"HASH"}];if(c)f.push({AttributeName:c.name,KeyType:"RANGE"});let S={IndexName:i,KeySchema:f,Projection:{ProjectionType:l,NonKeyAttributes:l==="INCLUDE"?u:void 0},ProvisionedThroughput:void 0};if(a.Properties.BillingMode==="PROVISIONED")S.ProvisionedThroughput={ReadCapacityUnits:h,WriteCapacityUnits:y};if(!a.Properties.GlobalSecondaryIndexes)a.Properties.GlobalSecondaryIndexes=[];return a.Properties.GlobalSecondaryIndexes.push(S),a}static enableStreams(a,n="NEW_AND_OLD_IMAGES"){return a.Properties.StreamSpecification={StreamViewType:n},a}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}}class Gs{static createRedis(a){let{slug:n,environment:i,nodeType:s="cache.t3.micro",engineVersion:c="7.1",port:l=6379,subnetIds:u,securityGroupIds:h,numCacheClusters:y=2,automaticFailover:f=!0,multiAz:S=!0,clusterMode:b=!1,numNodeGroups:C=1,replicasPerNodeGroup:T=1,atRestEncryption:v=!0,transitEncryption:w=!0,authToken:R,kmsKeyId:k,snapshotRetentionDays:W=7,snapshotWindow:P,maintenanceWindow:V}=a,B=r({slug:n,environment:i,resourceType:"redis"}),j=t(B),Z,K;if(u&&u.length>0){let te=r({slug:n,environment:i,resourceType:"cache-subnet-group"});K=t(te),Z={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:te,Description:`Subnet group for ${B}`,SubnetIds:u,Tags:[{Key:"Name",Value:te},{Key:"Environment",Value:i}]}}}let ee={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:B,ReplicationGroupDescription:`Redis cluster for ${n} ${i}`,Engine:"redis",EngineVersion:c,CacheNodeType:s,Port:l,AutomaticFailoverEnabled:f,MultiAZEnabled:S,AtRestEncryptionEnabled:v,TransitEncryptionEnabled:w,SnapshotRetentionLimit:W,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:B},{Key:"Environment",Value:i}]}};if(b)ee.Properties.NumNodeGroups=C,ee.Properties.ReplicasPerNodeGroup=T;else ee.Properties.NumCacheClusters=y;if(R)ee.Properties.AuthToken=R;if(k)ee.Properties.KmsKeyId=k;if(K)ee.Properties.CacheSubnetGroupName=N.Ref(K);if(h&&h.length>0)ee.Properties.SecurityGroupIds=h;if(P)ee.Properties.SnapshotWindow=P;if(V)ee.Properties.PreferredMaintenanceWindow=V;return{replicationGroup:ee,subnetGroup:Z,logicalId:j,subnetGroupId:K}}static createMemcached(a){let{slug:n,environment:i,nodeType:s="cache.t3.micro",engineVersion:c="1.6.22",port:l=11211,numCacheNodes:u=2,subnetIds:h,securityGroupIds:y,azMode:f="cross-az",preferredAzs:S,maintenanceWindow:b}=a,C=r({slug:n,environment:i,resourceType:"memcached"}),T=t(C),v,w;if(h&&h.length>0){let k=r({slug:n,environment:i,resourceType:"cache-subnet-group"});w=t(k),v={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:k,Description:`Subnet group for ${C}`,SubnetIds:h,Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:i}]}}}let R={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:C,CacheNodeType:s,Engine:"memcached",EngineVersion:c,NumCacheNodes:u,Port:l,AZMode:f,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:i}]}};if(w)R.Properties.CacheSubnetGroupName=N.Ref(w);if(y&&y.length>0)R.Properties.VpcSecurityGroupIds=y;if(S&&S.length>0)R.Properties.PreferredAvailabilityZones=S;if(b)R.Properties.PreferredMaintenanceWindow=b;return{cluster:R,subnetGroup:v,logicalId:T,subnetGroupId:w}}static enableClusterMode(a,n=3,i=2){return delete a.Properties.NumCacheClusters,a.Properties.NumNodeGroups=n,a.Properties.ReplicasPerNodeGroup=i,a}static createRedisParameterGroup(a,n){let{slug:i,environment:s,parameters:c={}}=n,l=r({slug:i,environment:s,resourceType:"redis-params"}),u=t(l);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${a.split(".")[0]}.x`,Description:`Parameter group for ${l}`,Properties:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s}]}},logicalId:u}}static createMemcachedParameterGroup(a,n){let{slug:i,environment:s,parameters:c={}}=n,l=r({slug:i,environment:s,resourceType:"memcached-params"}),u=t(l);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${a.split(".")[0]}.${a.split(".")[1]}`,Description:`Parameter group for ${l}`,Properties:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s}]}},logicalId:u}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}}class J{static createUser(a){let{slug:n,environment:i,userName:s,groups:c,managedPolicyArns:l}=a,u=s||r({slug:n,environment:i,resourceType:"user"}),h=t(u),y={Type:"AWS::IAM::User",Properties:{UserName:u,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i}]}};if(c&&c.length>0)y.Properties.Groups=c;if(l&&l.length>0)y.Properties.ManagedPolicyArns=l;return{user:y,logicalId:h}}static createRole(a){let{slug:n,environment:i,roleName:s,servicePrincipal:c,awsPrincipal:l,managedPolicyArns:u}=a,h=s||r({slug:n,environment:i,resourceType:"role"}),y=t(h),f={};if(c)f.Service=c;if(l)f.AWS=l;let S={Type:"AWS::IAM::Role",Properties:{RoleName:h,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:f,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(u&&u.length>0)S.Properties.ManagedPolicyArns=u;return{role:S,logicalId:y}}static createGroup(a){let{slug:n,environment:i,groupName:s,managedPolicyArns:c}=a,l=s||r({slug:n,environment:i,resourceType:"group"}),u=t(l),h={Type:"AWS::IAM::Group",Properties:{GroupName:l}};if(c&&c.length>0)h.Properties.ManagedPolicyArns=c;return{group:h,logicalId:u}}static createPolicy(a){let{slug:n,environment:i,policyName:s,description:c,statements:l}=a,u=s||r({slug:n,environment:i,resourceType:"policy"}),h=t(u),y=l.map((f)=>({Sid:f.sid,Effect:f.effect||"Allow",Action:f.actions,Resource:f.resources,Condition:f.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:u,Description:c||`Managed policy for ${u}`,PolicyDocument:{Version:"2012-10-17",Statement:y}}},logicalId:h}}static attachPolicyToRole(a,n){if(!a.Properties.ManagedPolicyArns)a.Properties.ManagedPolicyArns=[];if(!a.Properties.ManagedPolicyArns.includes(n))a.Properties.ManagedPolicyArns.push(n);return a}static attachPolicyToUser(a,n){if(!a.Properties.ManagedPolicyArns)a.Properties.ManagedPolicyArns=[];if(!a.Properties.ManagedPolicyArns.includes(n))a.Properties.ManagedPolicyArns.push(n);return a}static attachPolicyToGroup(a,n){if(!a.Properties.ManagedPolicyArns)a.Properties.ManagedPolicyArns=[];if(!a.Properties.ManagedPolicyArns.includes(n))a.Properties.ManagedPolicyArns.push(n);return a}static addInlinePolicyToRole(a,n,i){if(!a.Properties.Policies)a.Properties.Policies=[];let s=i.map((c)=>({Effect:c.effect||"Allow",Action:c.actions,Resource:c.resources}));return a.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:s}}),a}static addInlinePolicyToUser(a,n,i){if(!a.Properties.Policies)a.Properties.Policies=[];let s=i.map((c)=>({Effect:c.effect||"Allow",Action:c.actions,Resource:c.resources}));return a.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:s}}),a}static createAccessKey(a,n){let{slug:i,environment:s,status:c="Active"}=n,l=r({slug:i,environment:s,resourceType:"access-key"}),u=t(l);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:N.Ref(a),Status:c}},logicalId:u}}static createInstanceProfile(a,n){let{slug:i,environment:s,profileName:c}=n,l=c||r({slug:i,environment:s,resourceType:"instance-profile"}),u=t(l);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:l,Roles:[N.Ref(a)]}},logicalId:u}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser(a){let{slug:n,environment:i,permissions:s,createAccessKey:c=!0}=a,l={},u=[];if(s.s3Buckets&&s.s3Buckets.length>0)u.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...s.s3Buckets,...s.s3Buckets.map((T)=>`${T}/*`)]});if(s.cloudFrontDistributions&&s.cloudFrontDistributions.length>0)u.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:s.cloudFrontDistributions});if(s.ecrRepositories&&s.ecrRepositories.length>0)u.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:s.ecrRepositories}),u.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(s.ecsServices&&s.ecsServices.length>0)u.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:s.ecsServices}),u.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),u.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(s.cloudFormationStacks&&s.cloudFormationStacks.length>0)u.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:s.cloudFormationStacks});if(s.lambdaFunctions&&s.lambdaFunctions.length>0)u.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:s.lambdaFunctions});if(s.secretsManagerSecrets&&s.secretsManagerSecrets.length>0)u.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:s.secretsManagerSecrets});let{policy:h,logicalId:y}=J.createPolicy({slug:n,environment:i,policyName:r({slug:n,environment:i,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${n} (${i})`,statements:u});l[y]=h;let{user:f,logicalId:S}=J.createUser({slug:n,environment:i,userName:r({slug:n,environment:i,resourceType:"cicd-user"}),managedPolicyArns:[N.Ref(y)]});l[S]=f;let b,C;if(c){let T=J.createAccessKey(S,{slug:n,environment:i});b=T.accessKey,C=T.logicalId,l[C]=b}return{user:f,accessKey:b,policy:h,userLogicalId:S,accessKeyLogicalId:C,policyLogicalId:y,resources:l}}static createCrossAccountRole(a){let{slug:n,environment:i,trustedAccountIds:s,externalId:c,permissions:l,maxSessionDuration:u=3600}=a,h={},{policy:y,logicalId:f}=J.createPolicy({slug:n,environment:i,policyName:r({slug:n,environment:i,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${n} (${i})`,statements:l});h[f]=y;let S=r({slug:n,environment:i,resourceType:"cross-account-role"}),b=t(S),C={};if(c)C.StringEquals={"sts:ExternalId":c};let T={Type:"AWS::IAM::Role",Properties:{RoleName:S,MaxSessionDuration:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:s.map((v)=>`arn:aws:iam::${v}:root`)},Action:"sts:AssumeRole",...Object.keys(C).length>0?{Condition:C}:{}}]},ManagedPolicyArns:[N.Ref(f)],Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:i},{Key:"Purpose",Value:"Cross-Account Access"}]}};return h[b]=T,{role:T,policy:y,roleLogicalId:b,policyLogicalId:f,resources:h}}static createCliUser(a){let{slug:n,environment:i,permissions:s="readonly"}=a,c={},l=[],u=[];switch(s){case"readonly":u=[J.ManagedPolicies.ReadOnlyAccess];break;case"deploy":l=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":u=[J.ManagedPolicies.AdministratorAccess];break}let h,y;if(l.length>0){let T=J.createPolicy({slug:n,environment:i,policyName:r({slug:n,environment:i,resourceType:"cli-policy"}),description:`CLI access policy for ${n} (${i})`,statements:l});h=T.policy,y=T.logicalId,c[y]=h,u=[N.Ref(y)]}let{user:f,logicalId:S}=J.createUser({slug:n,environment:i,userName:r({slug:n,environment:i,resourceType:"cli-user"}),managedPolicyArns:u});c[S]=f;let{accessKey:b,logicalId:C}=J.createAccessKey(S,{slug:n,environment:i});return c[C]=b,{user:f,accessKey:b,policy:h,userLogicalId:S,accessKeyLogicalId:C,policyLogicalId:y,resources:c}}static CiCdPolicies={s3Deployment:(a)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:a},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:a.map((n)=>`${n}/*`)}],cloudFrontInvalidation:(a)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:a}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:(a)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:a}],lambdaDeployment:(a)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:a}],cloudFormationDeployment:(a)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:a}]}}class id{static createRestApi(a){let{slug:n,environment:i,name:s,description:c,endpointType:l="REGIONAL",binaryMediaTypes:u,compressionSize:h}=a,y=s||r({slug:n,environment:i,resourceType:"rest-api"}),f=t(y),S={Type:"AWS::ApiGateway::RestApi",Properties:{Name:y,Description:c||`REST API for ${n} ${i}`,EndpointConfiguration:{Types:[l]},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i}]}};if(u&&u.length>0)S.Properties.BinaryMediaTypes=u;if(h!==void 0)S.Properties.MinimumCompressionSize=h;return{restApi:S,logicalId:f}}static createHttpApi(a){let{slug:n,environment:i,name:s,description:c,corsEnabled:l=!0,corsOrigins:u=["*"],corsMethods:h=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:y=["*"],corsMaxAge:f=86400,corsAllowCredentials:S=!1}=a,b=s||r({slug:n,environment:i,resourceType:"http-api"}),C=t(b),T={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:b,Description:c||`HTTP API for ${n} ${i}`,ProtocolType:"HTTP",Tags:{Name:b,Environment:i}}};if(l)T.Properties.CorsConfiguration={AllowOrigins:u,AllowMethods:h,AllowHeaders:y,MaxAge:f,AllowCredentials:S};return{httpApi:T,logicalId:C}}static createWebSocketApi(a){let{slug:n,environment:i,name:s,description:c}=a,l=s||r({slug:n,environment:i,resourceType:"ws-api"}),u=t(l);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:l,Description:c||`WebSocket API for ${n} ${i}`,ProtocolType:"WEBSOCKET",Tags:{Name:l,Environment:i}}},logicalId:u}}static createDeployment(a,n){let{slug:i,environment:s,description:c}=n,l=r({slug:i,environment:s,resourceType:"api-deployment"}),u=t(l);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:N.Ref(a),Description:c||`Deployment for ${l}`}},logicalId:u}}static createStage(a,n,i){let{slug:s,environment:c,stageName:l,description:u,cacheEnabled:h=!1,cacheSize:y="0.5",variables:f,throttling:S}=i,b=r({slug:s,environment:c,resourceType:"api-stage"}),C=t(b),T={Type:"AWS::ApiGateway::Stage",Properties:{StageName:l||c,RestApiId:N.Ref(a),DeploymentId:N.Ref(n),Description:u,CacheClusterEnabled:h,Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:c}]}};if(h)T.Properties.CacheClusterSize=y;if(f)T.Properties.Variables=f;if(S)T.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:S.burstLimit,ThrottlingRateLimit:S.rateLimit}];return{stage:T,logicalId:C}}static createAuthorizer(a,n){let{slug:i,environment:s,name:c,type:l,functionArn:u,identitySource:h,userPoolArns:y,ttl:f=300}=n,S=c||r({slug:i,environment:s,resourceType:"api-authorizer"}),b=t(S),C={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:S,Type:l,RestApiId:N.Ref(a),AuthorizerResultTtlInSeconds:f}};if(l==="TOKEN"||l==="REQUEST"){if(!u)throw Error("Lambda authorizer requires functionArn");C.Properties.AuthorizerUri=u,C.Properties.IdentitySource=h||"method.request.header.Authorization"}if(l==="COGNITO_USER_POOLS"){if(!y||y.length===0)throw Error("Cognito authorizer requires userPoolArns");C.Properties.ProviderARNs=y,C.Properties.IdentitySource=h||"method.request.header.Authorization"}return{authorizer:C,logicalId:b}}static setCors(a,n={}){let{origins:i=["*"],methods:s=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:c=["*"],maxAge:l=86400,allowCredentials:u=!1}=n;return a.Properties.CorsConfiguration={AllowOrigins:i,AllowMethods:s,AllowHeaders:c,MaxAge:l,AllowCredentials:u},a}static addThrottling(a,n=5000,i=1e4){if(!a.Properties.MethodSettings)a.Properties.MethodSettings=[];return a.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:n,ThrottlingRateLimit:i}),a}static enableCaching(a,n="0.5",i=300){if(a.Properties.CacheClusterEnabled=!0,a.Properties.CacheClusterSize=n,!a.Properties.MethodSettings)a.Properties.MethodSettings=[];return a.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:i}),a}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}}class X{static createTopic(a){let{slug:n,environment:i,topicName:s,displayName:c,encrypted:l=!1,kmsKeyId:u}=a,h=s||r({slug:n,environment:i,resourceType:"topic"}),y=t(h),f={Type:"AWS::SNS::Topic",Properties:{TopicName:h,DisplayName:c||h,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(l&&u)f.Properties.KmsMasterKeyId=u;return{topic:f,logicalId:y}}static subscribe(a,n){let{slug:i,environment:s,protocol:c,endpoint:l,filterPolicy:u,rawMessageDelivery:h=!1}=n,y=r({slug:i,environment:s,resourceType:"subscription"}),f=l.replace(/[^a-zA-Z0-9]/g,""),S=f.length>12?f.slice(-12):f,b=t(`${y}-${c}-${S}`),C={Type:"AWS::SNS::Subscription",Properties:{TopicArn:N.Ref(a),Protocol:c,Endpoint:l,RawMessageDelivery:h}};if(u)C.Properties.FilterPolicy=u;return{subscription:C,logicalId:b}}static subscribeEmail(a,n,i){return X.subscribe(a,{...i,protocol:"email",endpoint:n})}static subscribeLambda(a,n,i){return X.subscribe(a,{...i,protocol:"lambda",endpoint:n,rawMessageDelivery:!0})}static subscribeSqs(a,n,i){return X.subscribe(a,{...i,protocol:"sqs",endpoint:n})}static subscribeHttp(a,n,i){let s=n.startsWith("https://")?"https":"http";return X.subscribe(a,{...i,protocol:s,endpoint:n})}static subscribeSms(a,n,i){return X.subscribe(a,{...i,protocol:"sms",endpoint:n})}static setTopicPolicy(a,n){let{slug:i,environment:s,allowedPrincipals:c,allowedServices:l,actions:u="SNS:Publish"}=n,h=r({slug:i,environment:s,resourceType:"topic-policy"}),y=t(h),f={};if(c)f.AWS=c;if(l)f.Service=l;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[N.Ref(a)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:f,Action:u,Resource:N.Ref(a)}]}}},logicalId:y}}static allowCloudWatchAlarms(a,n){return X.setTopicPolicy(a,{...n,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge(a,n){return X.setTopicPolicy(a,{...n,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3(a,n){return X.setTopicPolicy(a,{...n,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption(a,n){if(!a.Properties)a.Properties={};return a.Properties.KmsMasterKeyId=n,a}static addInlineSubscription(a,n,i){if(!a.Properties)a.Properties={};if(!a.Properties.Subscription)a.Properties.Subscription=[];return a.Properties.Subscription.push({Protocol:n,Endpoint:i}),a}static FilterPolicies={eventType:(a)=>({eventType:a}),status:(a)=>({status:a}),numericRange:(a,n,i)=>({[a]:[{numeric:[">=",n,"<=",i]}]}),prefix:(a,n)=>({[a]:[{prefix:n}]}),and:(...a)=>Object.assign({},...a),exists:(a,n)=>({[a]:[{exists:n}]})};static UseCases={createAlertTopic:(a)=>X.createTopic({...a,topicName:a.topicName||`${a.slug}-${a.environment}-alerts`,displayName:a.displayName||"Alert Notifications"}),createEventFanout:(a)=>X.createTopic({...a,topicName:a.topicName||`${a.slug}-${a.environment}-events`,displayName:a.displayName||"Event Fanout"}),createNotificationTopic:(a)=>X.createTopic({...a,topicName:a.topicName||`${a.slug}-${a.environment}-notifications`,displayName:a.displayName||"User Notifications"})}}class df{static createStateMachine(a){let{slug:n,environment:i,stateMachineName:s,type:c="STANDARD",definition:l,roleArn:u,loggingConfiguration:h,tracingConfiguration:y}=a,f=s||r({slug:n,environment:i,resourceType:"state-machine"}),S=t(f),b,C,T;if(u)T=u;else{let w=r({slug:n,environment:i,resourceType:"state-machine-role"});C=t(w),b={Type:"AWS::IAM::Role",Properties:{RoleName:w,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:i}]}},T=N.GetAtt(C,"Arn")}let v={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:f,StateMachineType:c,DefinitionString:JSON.stringify(l),RoleArn:T,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:i}]}};if(h)v.Properties.LoggingConfiguration={Level:h.level,IncludeExecutionData:h.includeExecutionData,Destinations:h.destinations?.map((w)=>({CloudWatchLogsLogGroup:{LogGroupArn:w}}))};if(y)v.Properties.TracingConfiguration={Enabled:y.enabled};return{stateMachine:v,logicalId:S,role:b,roleLogicalId:C}}static createLambdaTask(a,n){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:a,Payload:n?.parameters||{"Input.$":"$"}},ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createDynamoDBTask(a,n,i,s){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[a],Parameters:{TableName:n,...i},ResultPath:s?.resultPath,Retry:s?.retry,Catch:s?.catch,Next:s?.next,End:s?.end}}static createSNSPublishTask(a,n,i){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:a,Message:n},ResultPath:i?.resultPath,Retry:i?.retry,Catch:i?.catch,Next:i?.next,End:i?.end}}static createSQSSendMessageTask(a,n,i){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:a,MessageBody:n},ResultPath:i?.resultPath,Retry:i?.retry,Catch:i?.catch,Next:i?.next,End:i?.end}}static createPassState(a){return{Type:"Pass",Result:a?.result,ResultPath:a?.resultPath,Parameters:a?.parameters,Next:a?.next,End:a?.end}}static createWaitState(a){return{Type:"Wait",Seconds:a.seconds,Timestamp:a.timestamp,SecondsPath:a.secondsPath,TimestampPath:a.timestampPath,Next:a.next,End:a.end}}static createChoiceState(a,n){return{Type:"Choice",Choices:a,Default:n}}static createParallelState(a,n){return{Type:"Parallel",Branches:a,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createMapState(a,n){return{Type:"Map",ItemsPath:n?.itemsPath||"$.items",Iterator:a,MaxConcurrency:n?.maxConcurrency,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState(a,n){return{Type:"Fail",Error:a,Cause:n}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:(a,n,i,s)=>({ErrorEquals:a,IntervalSeconds:n,MaxAttempts:i,BackoffRate:s})};static CatchPolicies={all:(a,n)=>({ErrorEquals:["States.ALL"],Next:a,ResultPath:n||"$.error"}),specific:(a,n,i)=>({ErrorEquals:a,Next:n,ResultPath:i||"$.error"})};static Patterns={sequential:(a,n,i)=>{let s={};return i.forEach((c,l)=>{let u=l===i.length-1;s[c.name]={...c.state,Next:u?void 0:i[l+1].name,End:u}}),{Comment:"Sequential workflow",StartAt:i[0].name,States:s}},fanout:(a,n,i)=>({Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:i.map((s)=>s.definition),End:!0}}}),map:(a,n,i,s)=>({Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:i,MaxConcurrency:s,End:!0}}}),withErrorHandling:(a,n,i,s)=>({Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...i,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:s,Success:{Type:"Succeed"}}})}}class qs{static createAlarm(a){let{slug:n,environment:i,alarmName:s,metricName:c,namespace:l,statistic:u="Average",period:h=300,evaluationPeriods:y=1,threshold:f,comparisonOperator:S,treatMissingData:b="notBreaching",actionsEnabled:C=!0,alarmActions:T,okActions:v,insufficientDataActions:w,dimensions:R,unit:k,datapointsToAlarm:W}=a,P=s||r({slug:n,environment:i,resourceType:"alarm"}),V=t(P),B={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:P,MetricName:c,Namespace:l,Statistic:u,Period:h,EvaluationPeriods:y,Threshold:f,ComparisonOperator:S,TreatMissingData:b,ActionsEnabled:C}};if(T&&T.length>0)B.Properties.AlarmActions=T;if(v&&v.length>0)B.Properties.OKActions=v;if(w&&w.length>0)B.Properties.InsufficientDataActions=w;if(R)B.Properties.Dimensions=Object.entries(R).map(([j,Z])=>({Name:j,Value:Z}));if(k)B.Properties.Unit=k;if(W!==void 0)B.Properties.DatapointsToAlarm=W;return{alarm:B,logicalId:V}}static createCompositeAlarm(a){let{slug:n,environment:i,alarmName:s,alarmRule:c,actionsEnabled:l=!0,alarmActions:u,okActions:h,insufficientDataActions:y}=a,f=s||r({slug:n,environment:i,resourceType:"composite-alarm"}),S=t(f),b={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:f,AlarmRule:c,ActionsEnabled:l}};if(u&&u.length>0)b.Properties.AlarmActions=u;if(h&&h.length>0)b.Properties.OKActions=h;if(y&&y.length>0)b.Properties.InsufficientDataActions=y;return{alarm:b,logicalId:S}}static createDashboard(a){let{slug:n,environment:i,dashboardName:s,widgets:c}=a,l=s||r({slug:n,environment:i,resourceType:"dashboard"}),u=t(l),h={widgets:c.map((y)=>({type:y.type,x:y.x,y:y.y,width:y.width,height:y.height,properties:y.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:l,DashboardBody:JSON.stringify(h)}},logicalId:u}}static createLogGroup(a){let{slug:n,environment:i,logGroupName:s,retentionInDays:c,kmsKeyId:l}=a,u=s||r({slug:n,environment:i,resourceType:"log-group"}),h=t(u),y={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:u}};if(c!==void 0)y.Properties.RetentionInDays=c;if(l)y.Properties.KmsKeyId=l;return{logGroup:y,logicalId:h}}static createLogStream(a,n){let{slug:i,environment:s,logStreamName:c}=n,l=c||r({slug:i,environment:s,resourceType:"log-stream"}),u=t(l);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:N.Ref(a),LogStreamName:l}},logicalId:u}}static createMetricFilter(a,n){let{slug:i,environment:s,filterName:c,filterPattern:l,metricTransformations:u}=n,h=c||r({slug:i,environment:s,resourceType:"metric-filter"}),y=t(h);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:N.Ref(a),FilterPattern:l,MetricTransformations:u.map((f)=>({MetricName:f.metricName,MetricNamespace:f.metricNamespace,MetricValue:f.metricValue,DefaultValue:f.defaultValue,Unit:f.unit}))}},logicalId:y}}static AlarmTypes={highCpu:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i},alarmActions:c?[c]:void 0}),highMemory:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i},alarmActions:c?[c]:void 0}),highDisk:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:c?[c]:void 0}),lambdaErrors:(a,n,i,s=5,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:i},alarmActions:c?[c]:void 0}),lambdaThrottles:(a,n,i,s=10,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:i},alarmActions:c?[c]:void 0}),apiGateway5xxErrors:(a,n,i,s=10,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:i},alarmActions:c?[c]:void 0}),apiGateway4xxErrors:(a,n,i,s=50,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:i},alarmActions:c?[c]:void 0}),dynamoDBThrottles:(a,n,i,s=5,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:i},alarmActions:c?[c]:void 0}),rdsCpu:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:i},alarmActions:c?[c]:void 0}),rdsFreeStorage:(a,n,i,s=5368709120,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:i},alarmActions:c?[c]:void 0,unit:"Bytes"}),sqsQueueDepth:(a,n,i,s=100,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:i},alarmActions:c?[c]:void 0}),albUnhealthyTargets:(a,n,i,s,c=1,l)=>({slug:a,environment:n,alarmName:`${a}-${n}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:c,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:i,TargetGroup:s},alarmActions:l?[l]:void 0}),sesBounceRate:(a,n,i=5,s)=>({slug:a,environment:n,alarmName:`${a}-${n}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:i/100,comparisonOperator:"GreaterThanThreshold",alarmActions:s?[s]:void 0}),sesComplaintRate:(a,n,i=0.1,s)=>({slug:a,environment:n,alarmName:`${a}-${n}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:i/100,comparisonOperator:"GreaterThanThreshold",alarmActions:s?[s]:void 0}),smsDeliveryFailure:(a,n,i,s=10,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:i},alarmActions:c?[c]:void 0}),smsSpendLimit:(a,n,i=100,s)=>({slug:a,environment:n,alarmName:`${a}-${n}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",alarmActions:s?[s]:void 0}),connectMissedCalls:(a,n,i,s=5,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i},alarmActions:c?[c]:void 0})};static DashboardWidgets={metric:(a,n,i,s,c,l)=>({type:"metric",x:a,y:n,width:i,height:s,properties:{metrics:c,title:l||"Metrics",region:"us-east-1",period:300}}),text:(a,n,i,s,c)=>({type:"text",x:a,y:n,width:i,height:s,properties:{markdown:c}}),log:(a,n,i,s,c,l)=>({type:"log",x:a,y:n,width:i,height:s,properties:{query:`SOURCE '${c.join("' | SOURCE '")}'
2309
+ `;class F{static LambdaCode={send:wa,receive:mr,deliveryStatus:dr};static createPinpointApp(a){return{[`${a.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:a.name||`${a.slug}-sms`}}}}static createSmsChannel(a){let n={ApplicationId:a.applicationId,Enabled:a.enabled!==!1};if(a.senderId)n.SenderId=a.senderId;if(a.shortCode)n.ShortCode=a.shortCode;return{[`${a.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:n}}}static createSmsLambdaRole(a){return{[`${a.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${a.slug}-sms-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda(a){return{[`${a.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:F.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:a.pinpointAppId,MESSAGE_LOG_TABLE:a.messageLogTable||"",SMS_SENDER_ID:a.senderId||"",SMS_ORIGINATION_NUMBER:a.originationNumber||""}}}}}}static createReceiveLambda(a){return{[`${a.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:F.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:a.optOutTable||"",MESSAGE_LOG_TABLE:a.messageLogTable||"",NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createDeliveryStatusLambda(a){return{[`${a.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:F.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:a.messageLogTable||"",NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||"",WEBHOOK_URL:a.webhookUrl||""}}}}}}static createMessageLogTable(a){return{[`${a.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable(a){return{[`${a.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic(a){return{[`${a.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${a.slug}-sms-notifications`}}}}static createCompleteSetup(a){let n={},i={};Object.assign(n,F.createPinpointApp({slug:a.slug})),Object.assign(n,F.createSmsChannel({slug:a.slug,applicationId:{Ref:`${a.slug}PinpointApp`},senderId:a.senderId})),Object.assign(n,F.createSmsLambdaRole({slug:a.slug})),Object.assign(n,F.createMessageLogTable({slug:a.slug})),Object.assign(n,F.createOptOutTable({slug:a.slug})),Object.assign(n,F.createNotificationTopic({slug:a.slug}));let s={"Fn::GetAtt":[`${a.slug}SmsLambdaRole`,"Arn"]},c={Ref:`${a.slug}PinpointApp`},l={Ref:`${a.slug}SmsMessageLogTable`},u={Ref:`${a.slug}SmsOptOutTable`},h={Ref:`${a.slug}SmsNotificationTopic`};if(Object.assign(n,F.createSendLambda({slug:a.slug,roleArn:s,pinpointAppId:c,messageLogTable:l,senderId:a.senderId,originationNumber:a.originationNumber})),a.twoWayEnabled)Object.assign(n,F.createReceiveLambda({slug:a.slug,roleArn:s,optOutTable:u,messageLogTable:l,notificationTopicArn:h,webhookUrl:a.webhookUrl}));return Object.assign(n,F.createDeliveryStatusLambda({slug:a.slug,roleArn:s,messageLogTable:l,notificationTopicArn:h,webhookUrl:a.webhookUrl})),i[`${a.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${a.slug}PinpointApp`}},i[`${a.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${a.slug}SmsSendLambda`,"Arn"]}},i[`${a.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${a.slug}SmsNotificationTopic`}},i[`${a.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${a.slug}SmsMessageLogTable`}},{resources:n,outputs:i}}}function wt(a){return a.replace(/[^a-zA-Z0-9]/g," ").trim().split(/\s+/).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")||"User"}function gr(a,n){let i=(a||n).replace(/^\/+|\/+$/g,"");if(!i||i.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${n}`);return i}function hr(a){let n=a.storage;if(n?.type==="efs"){let s="fileSystemId"in n?n.fileSystemId:void 0;if(!s||typeof s==="string"&&!s.trim())throw Error("sftp: EFS storage requires fileSystemId, or a fileSystem name defined in infrastructure.fileSystem");return{type:"efs",fileSystemId:s,posixProfile:n.posixProfile}}let i=(n?.type==="s3"?n.bucket??a.bucket:a.bucket)?.trim();if(!i)throw Error("sftp: S3 storage requires bucket, or a storageBucket name defined in infrastructure.storage");return{type:"s3",bucket:i}}function yr(a,n,i){let s=n.posixProfile??i;if(!s)throw Error(`sftp: user ${a} requires a posixProfile (uid/gid) on an EFS-backed server`);for(let c of[s.uid,s.gid,...s.secondaryGids??[]])if(!Number.isInteger(c)||c<0||c>4294967295)throw Error(`sftp: user ${a} has an invalid posixProfile id ${c}`);return{Uid:s.uid,Gid:s.gid,...s.secondaryGids?.length?{SecondaryGids:s.secondaryGids}:{}}}function fr(a,n){return typeof a==="string"?`/${a}/${n}`:{"Fn::Sub":[`/\${FileSystemId}/${n}`,{FileSystemId:a}]}}function Sr(a){return typeof a==="string"?{"Fn::Sub":"arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}".replace("${FileSystemId}",a)}:{"Fn::Sub":["arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}",{FileSystemId:a}]}}class nd{static create(a){let n=hr(a),i=n.type==="efs"?"EFS":"S3",s=a.endpointType??"PUBLIC";if(s==="VPC"&&(!a.endpointDetails?.vpcId||!a.endpointDetails.subnetIds.length))throw Error("sftp: VPC endpoints require endpointDetails.vpcId and at least one subnet");let c=`${wt(a.slug)}${wt(a.environment)}Sftp`,l=`${c}Server`,u={},h;if(a.logging!==!1){let y=`${c}LoggingRole`;u[y]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TransferLogging",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:DescribeLogStreams","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:log-group:/aws/transfer/*"}]}}]}},h={"Fn::GetAtt":[y,"Arn"]}}u[l]={Type:"AWS::Transfer::Server",Properties:{Domain:i,EndpointType:s,IdentityProviderType:"SERVICE_MANAGED",Protocols:["SFTP"],...s==="VPC"?{EndpointDetails:{VpcId:a.endpointDetails.vpcId,SubnetIds:a.endpointDetails.subnetIds,...a.endpointDetails.securityGroupIds?.length?{SecurityGroupIds:a.endpointDetails.securityGroupIds}:{},...a.endpointDetails.addressAllocationIds?.length?{AddressAllocationIds:a.endpointDetails.addressAllocationIds}:{}}}:{},...a.securityPolicyName?{SecurityPolicyName:a.securityPolicyName}:{},...h?{LoggingRole:h}:{},Tags:[{Key:"Project",Value:a.slug},{Key:"Environment",Value:a.environment},{Key:"ManagedBy",Value:"ts-cloud"}]}};for(let[y,f]of Object.entries(a.users)){if(!/^[a-zA-Z0-9_.@-]{3,100}$/.test(y))throw Error(`sftp: invalid username ${y}`);if(!f.sshPublicKeys.length)throw Error(`sftp: user ${y} requires at least one SSH public key`);let S=wt(y),b=gr(f.homeDirectory,y),C=`${c}${S}User`,T=f.roleArn;if(!T){let v=`${c}${S}Role`,w;if(n.type==="efs")w=[{Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:DescribeMountTargets"],Resource:Sr(n.fileSystemId)}];else{let R=`arn:aws:s3:::${n.bucket}`;w=[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:R,Condition:{StringLike:{"s3:prefix":[b,`${b}/*`]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:GetObjectVersion"],Resource:`${R}/${b}/*`}]}u[v]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"SftpHomeDirectory",PolicyDocument:{Version:"2012-10-17",Statement:w}}]}},T={"Fn::GetAtt":[v,"Arn"]}}u[C]={Type:"AWS::Transfer::User",DependsOn:[l],Properties:{ServerId:{Ref:l},UserName:y,Role:T,HomeDirectoryType:"PATH",HomeDirectory:n.type==="efs"?fr(n.fileSystemId,b):`/${n.bucket}/${b}`,...n.type==="efs"?{PosixProfile:yr(y,f,n.posixProfile)}:{},SshPublicKeys:f.sshPublicKeys}}}return{resources:u,serverLogicalId:l,domain:i}}}class be{static createBedrockRole(a,n){let{slug:i,environment:s,name:c,models:l=["*"],allowStreaming:u=!0}=n,h=c||r({slug:i,environment:s,resourceType:"bedrock-role"}),y=t(h),f=["bedrock:InvokeModel"];if(u)f.push("bedrock:InvokeModelWithResponseStream");let S=l.map((b)=>b==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${b}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:h,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:a},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${h}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:f,Resource:S}]}}],Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:s}]}},logicalId:y}}static createBedrockPolicy(a){let{slug:n,environment:i,name:s,models:c=["*"],allowInvoke:l=!0,allowStreaming:u=!0,allowAsync:h=!1}=a,y=s||r({slug:n,environment:i,resourceType:"bedrock-policy"}),f=t(y),S=[];if(l)S.push("bedrock:InvokeModel");if(u)S.push("bedrock:InvokeModelWithResponseStream");if(h)S.push("bedrock:InvokeModelAsync");let b=c.map((C)=>C==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${C}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:y,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:S,Resource:b}]}}},logicalId:f}}static enableBedrockForLambda(a){return be.createBedrockRole("lambda.amazonaws.com",a)}static enableBedrockForEcs(a){return be.createBedrockRole("ecs-tasks.amazonaws.com",a)}static enableBedrockForEc2(a){return be.createBedrockRole("ec2.amazonaws.com",a)}static addBedrockPermissions(a,n=["*"],i=!0){let s=["bedrock:InvokeModel"];if(i)s.push("bedrock:InvokeModelWithResponseStream");let c=n.map((l)=>l==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${l}`);if(!a.Properties.Policies)a.Properties.Policies=[];return a.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:s,Resource:c}]}}),a}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}}class Ft{static createPostgres(a){return Ft.createRDSInstance("postgres","16.2",a)}static createMysql(a){return Ft.createRDSInstance("mysql","8.0.35",a)}static createRDSInstance(a,n,i){let{slug:s,environment:c,instanceClass:l="db.t3.micro",allocatedStorage:u=20,storageType:h="gp3",masterUsername:y="admin",masterPassword:f,databaseName:S,subnetIds:b,securityGroupIds:C,encrypted:T=!0,kmsKeyId:v,multiAz:w=!1,backupRetentionDays:R=7,publiclyAccessible:k=!1,enableCloudwatchLogs:W=!0,deletionProtection:P=!0}=i,V=r({slug:s,environment:c,resourceType:`${a}-db`}),B=t(V),j,J;if(b&&b.length>0){let ee=r({slug:s,environment:c,resourceType:"db-subnet-group"});J=t(ee),j={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:ee,DBSubnetGroupDescription:`Subnet group for ${V}`,SubnetIds:b,Tags:[{Key:"Name",Value:ee},{Key:"Environment",Value:c}]}}}let K={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:V,DBInstanceClass:l,Engine:a,EngineVersion:n,MasterUsername:y,MasterUserPassword:f,AllocatedStorage:u,StorageType:h,StorageEncrypted:T,MultiAZ:w,BackupRetentionPeriod:R,PubliclyAccessible:k,DeletionProtection:P,Tags:[{Key:"Name",Value:V},{Key:"Environment",Value:c}]}};if(S)K.Properties.DBName=S;if(v)K.Properties.KmsKeyId=v;if(J)K.Properties.DBSubnetGroupName=N.Ref(J);if(C&&C.length>0)K.Properties.VPCSecurityGroups=C;if(W)K.Properties.EnableCloudwatchLogsExports=a==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:K,subnetGroup:j,logicalId:B,subnetGroupId:J}}static createReadReplica(a,n){let{slug:i,environment:s,instanceClass:c="db.t3.micro",securityGroupIds:l,publiclyAccessible:u=!1}=n,h=r({slug:i,environment:s,resourceType:"db-replica"}),y=t(h),f={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:h,DBInstanceClass:c,SourceDBInstanceIdentifier:N.Ref(a),PubliclyAccessible:u,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:s},{Key:"Type",Value:"ReadReplica"}]}};if(l&&l.length>0)f.Properties.VPCSecurityGroups=l;return{replica:f,logicalId:y}}static createParameterGroup(a,n,i){let{slug:s,environment:c,parameters:l={}}=i,u=r({slug:s,environment:c,resourceType:"db-params"}),h=t(u),y=a==="postgres"?`postgres${n.split(".")[0]}`:`mysql${n.split(".")[0]}.${n.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:u,Description:`Parameter group for ${u}`,Family:y,Parameters:l,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:c}]}},logicalId:h}}static enableBackup(a,n=7){return a.Properties.BackupRetentionPeriod=n,a}static createTable(a){let{slug:n,environment:i,tableName:s,partitionKey:c,sortKey:l,billingMode:u="PAY_PER_REQUEST",readCapacity:h=5,writeCapacity:y=5,streamEnabled:f=!1,streamViewType:S="NEW_AND_OLD_IMAGES",encrypted:b=!0,kmsKeyId:C,pointInTimeRecovery:T=!0,ttlAttribute:v}=a,w=s||r({slug:n,environment:i,resourceType:"table"}),R=t(w),k=[{AttributeName:c.name,AttributeType:c.type}];if(l)k.push({AttributeName:l.name,AttributeType:l.type});let W=[{AttributeName:c.name,KeyType:"HASH"}];if(l)W.push({AttributeName:l.name,KeyType:"RANGE"});let P={Type:"AWS::DynamoDB::Table",Properties:{TableName:w,BillingMode:u,AttributeDefinitions:k,KeySchema:W,Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:i}]}};if(u==="PROVISIONED")P.Properties.ProvisionedThroughput={ReadCapacityUnits:h,WriteCapacityUnits:y};if(f)P.Properties.StreamSpecification={StreamViewType:S};if(b)P.Properties.SSESpecification={SSEEnabled:!0,SSEType:C?"KMS":"AES256",KMSMasterKeyId:C};if(T)P.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(v)P.Properties.TimeToLiveSpecification={AttributeName:v,Enabled:!0};return{table:P,logicalId:R}}static addGlobalSecondaryIndex(a,n){let{indexName:i,partitionKey:s,sortKey:c,projectionType:l="ALL",nonKeyAttributes:u,readCapacity:h=5,writeCapacity:y=5}=n;if(!a.Properties.AttributeDefinitions.some((b)=>b.AttributeName===s.name))a.Properties.AttributeDefinitions.push({AttributeName:s.name,AttributeType:s.type});if(c&&!a.Properties.AttributeDefinitions.some((b)=>b.AttributeName===c.name))a.Properties.AttributeDefinitions.push({AttributeName:c.name,AttributeType:c.type});let f=[{AttributeName:s.name,KeyType:"HASH"}];if(c)f.push({AttributeName:c.name,KeyType:"RANGE"});let S={IndexName:i,KeySchema:f,Projection:{ProjectionType:l,NonKeyAttributes:l==="INCLUDE"?u:void 0},ProvisionedThroughput:void 0};if(a.Properties.BillingMode==="PROVISIONED")S.ProvisionedThroughput={ReadCapacityUnits:h,WriteCapacityUnits:y};if(!a.Properties.GlobalSecondaryIndexes)a.Properties.GlobalSecondaryIndexes=[];return a.Properties.GlobalSecondaryIndexes.push(S),a}static enableStreams(a,n="NEW_AND_OLD_IMAGES"){return a.Properties.StreamSpecification={StreamViewType:n},a}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}}class Gs{static createRedis(a){let{slug:n,environment:i,nodeType:s="cache.t3.micro",engineVersion:c="7.1",port:l=6379,subnetIds:u,securityGroupIds:h,numCacheClusters:y=2,automaticFailover:f=!0,multiAz:S=!0,clusterMode:b=!1,numNodeGroups:C=1,replicasPerNodeGroup:T=1,atRestEncryption:v=!0,transitEncryption:w=!0,authToken:R,kmsKeyId:k,snapshotRetentionDays:W=7,snapshotWindow:P,maintenanceWindow:V}=a,B=r({slug:n,environment:i,resourceType:"redis"}),j=t(B),J,K;if(u&&u.length>0){let te=r({slug:n,environment:i,resourceType:"cache-subnet-group"});K=t(te),J={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:te,Description:`Subnet group for ${B}`,SubnetIds:u,Tags:[{Key:"Name",Value:te},{Key:"Environment",Value:i}]}}}let ee={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:B,ReplicationGroupDescription:`Redis cluster for ${n} ${i}`,Engine:"redis",EngineVersion:c,CacheNodeType:s,Port:l,AutomaticFailoverEnabled:f,MultiAZEnabled:S,AtRestEncryptionEnabled:v,TransitEncryptionEnabled:w,SnapshotRetentionLimit:W,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:B},{Key:"Environment",Value:i}]}};if(b)ee.Properties.NumNodeGroups=C,ee.Properties.ReplicasPerNodeGroup=T;else ee.Properties.NumCacheClusters=y;if(R)ee.Properties.AuthToken=R;if(k)ee.Properties.KmsKeyId=k;if(K)ee.Properties.CacheSubnetGroupName=N.Ref(K);if(h&&h.length>0)ee.Properties.SecurityGroupIds=h;if(P)ee.Properties.SnapshotWindow=P;if(V)ee.Properties.PreferredMaintenanceWindow=V;return{replicationGroup:ee,subnetGroup:J,logicalId:j,subnetGroupId:K}}static createMemcached(a){let{slug:n,environment:i,nodeType:s="cache.t3.micro",engineVersion:c="1.6.22",port:l=11211,numCacheNodes:u=2,subnetIds:h,securityGroupIds:y,azMode:f="cross-az",preferredAzs:S,maintenanceWindow:b}=a,C=r({slug:n,environment:i,resourceType:"memcached"}),T=t(C),v,w;if(h&&h.length>0){let k=r({slug:n,environment:i,resourceType:"cache-subnet-group"});w=t(k),v={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:k,Description:`Subnet group for ${C}`,SubnetIds:h,Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:i}]}}}let R={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:C,CacheNodeType:s,Engine:"memcached",EngineVersion:c,NumCacheNodes:u,Port:l,AZMode:f,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:i}]}};if(w)R.Properties.CacheSubnetGroupName=N.Ref(w);if(y&&y.length>0)R.Properties.VpcSecurityGroupIds=y;if(S&&S.length>0)R.Properties.PreferredAvailabilityZones=S;if(b)R.Properties.PreferredMaintenanceWindow=b;return{cluster:R,subnetGroup:v,logicalId:T,subnetGroupId:w}}static enableClusterMode(a,n=3,i=2){return delete a.Properties.NumCacheClusters,a.Properties.NumNodeGroups=n,a.Properties.ReplicasPerNodeGroup=i,a}static createRedisParameterGroup(a,n){let{slug:i,environment:s,parameters:c={}}=n,l=r({slug:i,environment:s,resourceType:"redis-params"}),u=t(l);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${a.split(".")[0]}.x`,Description:`Parameter group for ${l}`,Properties:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s}]}},logicalId:u}}static createMemcachedParameterGroup(a,n){let{slug:i,environment:s,parameters:c={}}=n,l=r({slug:i,environment:s,resourceType:"memcached-params"}),u=t(l);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${a.split(".")[0]}.${a.split(".")[1]}`,Description:`Parameter group for ${l}`,Properties:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:s}]}},logicalId:u}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}}class X{static createUser(a){let{slug:n,environment:i,userName:s,groups:c,managedPolicyArns:l}=a,u=s||r({slug:n,environment:i,resourceType:"user"}),h=t(u),y={Type:"AWS::IAM::User",Properties:{UserName:u,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i}]}};if(c&&c.length>0)y.Properties.Groups=c;if(l&&l.length>0)y.Properties.ManagedPolicyArns=l;return{user:y,logicalId:h}}static createRole(a){let{slug:n,environment:i,roleName:s,servicePrincipal:c,awsPrincipal:l,managedPolicyArns:u}=a,h=s||r({slug:n,environment:i,resourceType:"role"}),y=t(h),f={};if(c)f.Service=c;if(l)f.AWS=l;let S={Type:"AWS::IAM::Role",Properties:{RoleName:h,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:f,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(u&&u.length>0)S.Properties.ManagedPolicyArns=u;return{role:S,logicalId:y}}static createGroup(a){let{slug:n,environment:i,groupName:s,managedPolicyArns:c}=a,l=s||r({slug:n,environment:i,resourceType:"group"}),u=t(l),h={Type:"AWS::IAM::Group",Properties:{GroupName:l}};if(c&&c.length>0)h.Properties.ManagedPolicyArns=c;return{group:h,logicalId:u}}static createPolicy(a){let{slug:n,environment:i,policyName:s,description:c,statements:l}=a,u=s||r({slug:n,environment:i,resourceType:"policy"}),h=t(u),y=l.map((f)=>({Sid:f.sid,Effect:f.effect||"Allow",Action:f.actions,Resource:f.resources,Condition:f.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:u,Description:c||`Managed policy for ${u}`,PolicyDocument:{Version:"2012-10-17",Statement:y}}},logicalId:h}}static attachPolicyToRole(a,n){if(!a.Properties.ManagedPolicyArns)a.Properties.ManagedPolicyArns=[];if(!a.Properties.ManagedPolicyArns.includes(n))a.Properties.ManagedPolicyArns.push(n);return a}static attachPolicyToUser(a,n){if(!a.Properties.ManagedPolicyArns)a.Properties.ManagedPolicyArns=[];if(!a.Properties.ManagedPolicyArns.includes(n))a.Properties.ManagedPolicyArns.push(n);return a}static attachPolicyToGroup(a,n){if(!a.Properties.ManagedPolicyArns)a.Properties.ManagedPolicyArns=[];if(!a.Properties.ManagedPolicyArns.includes(n))a.Properties.ManagedPolicyArns.push(n);return a}static addInlinePolicyToRole(a,n,i){if(!a.Properties.Policies)a.Properties.Policies=[];let s=i.map((c)=>({Effect:c.effect||"Allow",Action:c.actions,Resource:c.resources}));return a.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:s}}),a}static addInlinePolicyToUser(a,n,i){if(!a.Properties.Policies)a.Properties.Policies=[];let s=i.map((c)=>({Effect:c.effect||"Allow",Action:c.actions,Resource:c.resources}));return a.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:s}}),a}static createAccessKey(a,n){let{slug:i,environment:s,status:c="Active"}=n,l=r({slug:i,environment:s,resourceType:"access-key"}),u=t(l);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:N.Ref(a),Status:c}},logicalId:u}}static createInstanceProfile(a,n){let{slug:i,environment:s,profileName:c}=n,l=c||r({slug:i,environment:s,resourceType:"instance-profile"}),u=t(l);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:l,Roles:[N.Ref(a)]}},logicalId:u}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser(a){let{slug:n,environment:i,permissions:s,createAccessKey:c=!0}=a,l={},u=[];if(s.s3Buckets&&s.s3Buckets.length>0)u.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...s.s3Buckets,...s.s3Buckets.map((T)=>`${T}/*`)]});if(s.cloudFrontDistributions&&s.cloudFrontDistributions.length>0)u.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:s.cloudFrontDistributions});if(s.ecrRepositories&&s.ecrRepositories.length>0)u.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:s.ecrRepositories}),u.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(s.ecsServices&&s.ecsServices.length>0)u.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:s.ecsServices}),u.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),u.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(s.cloudFormationStacks&&s.cloudFormationStacks.length>0)u.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:s.cloudFormationStacks});if(s.lambdaFunctions&&s.lambdaFunctions.length>0)u.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:s.lambdaFunctions});if(s.secretsManagerSecrets&&s.secretsManagerSecrets.length>0)u.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:s.secretsManagerSecrets});let{policy:h,logicalId:y}=X.createPolicy({slug:n,environment:i,policyName:r({slug:n,environment:i,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${n} (${i})`,statements:u});l[y]=h;let{user:f,logicalId:S}=X.createUser({slug:n,environment:i,userName:r({slug:n,environment:i,resourceType:"cicd-user"}),managedPolicyArns:[N.Ref(y)]});l[S]=f;let b,C;if(c){let T=X.createAccessKey(S,{slug:n,environment:i});b=T.accessKey,C=T.logicalId,l[C]=b}return{user:f,accessKey:b,policy:h,userLogicalId:S,accessKeyLogicalId:C,policyLogicalId:y,resources:l}}static createCrossAccountRole(a){let{slug:n,environment:i,trustedAccountIds:s,externalId:c,permissions:l,maxSessionDuration:u=3600}=a,h={},{policy:y,logicalId:f}=X.createPolicy({slug:n,environment:i,policyName:r({slug:n,environment:i,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${n} (${i})`,statements:l});h[f]=y;let S=r({slug:n,environment:i,resourceType:"cross-account-role"}),b=t(S),C={};if(c)C.StringEquals={"sts:ExternalId":c};let T={Type:"AWS::IAM::Role",Properties:{RoleName:S,MaxSessionDuration:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:s.map((v)=>`arn:aws:iam::${v}:root`)},Action:"sts:AssumeRole",...Object.keys(C).length>0?{Condition:C}:{}}]},ManagedPolicyArns:[N.Ref(f)],Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:i},{Key:"Purpose",Value:"Cross-Account Access"}]}};return h[b]=T,{role:T,policy:y,roleLogicalId:b,policyLogicalId:f,resources:h}}static createCliUser(a){let{slug:n,environment:i,permissions:s="readonly"}=a,c={},l=[],u=[];switch(s){case"readonly":u=[X.ManagedPolicies.ReadOnlyAccess];break;case"deploy":l=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":u=[X.ManagedPolicies.AdministratorAccess];break}let h,y;if(l.length>0){let T=X.createPolicy({slug:n,environment:i,policyName:r({slug:n,environment:i,resourceType:"cli-policy"}),description:`CLI access policy for ${n} (${i})`,statements:l});h=T.policy,y=T.logicalId,c[y]=h,u=[N.Ref(y)]}let{user:f,logicalId:S}=X.createUser({slug:n,environment:i,userName:r({slug:n,environment:i,resourceType:"cli-user"}),managedPolicyArns:u});c[S]=f;let{accessKey:b,logicalId:C}=X.createAccessKey(S,{slug:n,environment:i});return c[C]=b,{user:f,accessKey:b,policy:h,userLogicalId:S,accessKeyLogicalId:C,policyLogicalId:y,resources:c}}static CiCdPolicies={s3Deployment:(a)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:a},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:a.map((n)=>`${n}/*`)}],cloudFrontInvalidation:(a)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:a}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:(a)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:a}],lambdaDeployment:(a)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:a}],cloudFormationDeployment:(a)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:a}]}}class id{static createRestApi(a){let{slug:n,environment:i,name:s,description:c,endpointType:l="REGIONAL",binaryMediaTypes:u,compressionSize:h}=a,y=s||r({slug:n,environment:i,resourceType:"rest-api"}),f=t(y),S={Type:"AWS::ApiGateway::RestApi",Properties:{Name:y,Description:c||`REST API for ${n} ${i}`,EndpointConfiguration:{Types:[l]},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i}]}};if(u&&u.length>0)S.Properties.BinaryMediaTypes=u;if(h!==void 0)S.Properties.MinimumCompressionSize=h;return{restApi:S,logicalId:f}}static createHttpApi(a){let{slug:n,environment:i,name:s,description:c,corsEnabled:l=!0,corsOrigins:u=["*"],corsMethods:h=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:y=["*"],corsMaxAge:f=86400,corsAllowCredentials:S=!1}=a,b=s||r({slug:n,environment:i,resourceType:"http-api"}),C=t(b),T={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:b,Description:c||`HTTP API for ${n} ${i}`,ProtocolType:"HTTP",Tags:{Name:b,Environment:i}}};if(l)T.Properties.CorsConfiguration={AllowOrigins:u,AllowMethods:h,AllowHeaders:y,MaxAge:f,AllowCredentials:S};return{httpApi:T,logicalId:C}}static createWebSocketApi(a){let{slug:n,environment:i,name:s,description:c}=a,l=s||r({slug:n,environment:i,resourceType:"ws-api"}),u=t(l);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:l,Description:c||`WebSocket API for ${n} ${i}`,ProtocolType:"WEBSOCKET",Tags:{Name:l,Environment:i}}},logicalId:u}}static createDeployment(a,n){let{slug:i,environment:s,description:c}=n,l=r({slug:i,environment:s,resourceType:"api-deployment"}),u=t(l);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:N.Ref(a),Description:c||`Deployment for ${l}`}},logicalId:u}}static createStage(a,n,i){let{slug:s,environment:c,stageName:l,description:u,cacheEnabled:h=!1,cacheSize:y="0.5",variables:f,throttling:S}=i,b=r({slug:s,environment:c,resourceType:"api-stage"}),C=t(b),T={Type:"AWS::ApiGateway::Stage",Properties:{StageName:l||c,RestApiId:N.Ref(a),DeploymentId:N.Ref(n),Description:u,CacheClusterEnabled:h,Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:c}]}};if(h)T.Properties.CacheClusterSize=y;if(f)T.Properties.Variables=f;if(S)T.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:S.burstLimit,ThrottlingRateLimit:S.rateLimit}];return{stage:T,logicalId:C}}static createAuthorizer(a,n){let{slug:i,environment:s,name:c,type:l,functionArn:u,identitySource:h,userPoolArns:y,ttl:f=300}=n,S=c||r({slug:i,environment:s,resourceType:"api-authorizer"}),b=t(S),C={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:S,Type:l,RestApiId:N.Ref(a),AuthorizerResultTtlInSeconds:f}};if(l==="TOKEN"||l==="REQUEST"){if(!u)throw Error("Lambda authorizer requires functionArn");C.Properties.AuthorizerUri=u,C.Properties.IdentitySource=h||"method.request.header.Authorization"}if(l==="COGNITO_USER_POOLS"){if(!y||y.length===0)throw Error("Cognito authorizer requires userPoolArns");C.Properties.ProviderARNs=y,C.Properties.IdentitySource=h||"method.request.header.Authorization"}return{authorizer:C,logicalId:b}}static setCors(a,n={}){let{origins:i=["*"],methods:s=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:c=["*"],maxAge:l=86400,allowCredentials:u=!1}=n;return a.Properties.CorsConfiguration={AllowOrigins:i,AllowMethods:s,AllowHeaders:c,MaxAge:l,AllowCredentials:u},a}static addThrottling(a,n=5000,i=1e4){if(!a.Properties.MethodSettings)a.Properties.MethodSettings=[];return a.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:n,ThrottlingRateLimit:i}),a}static enableCaching(a,n="0.5",i=300){if(a.Properties.CacheClusterEnabled=!0,a.Properties.CacheClusterSize=n,!a.Properties.MethodSettings)a.Properties.MethodSettings=[];return a.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:i}),a}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}}class Y{static createTopic(a){let{slug:n,environment:i,topicName:s,displayName:c,encrypted:l=!1,kmsKeyId:u}=a,h=s||r({slug:n,environment:i,resourceType:"topic"}),y=t(h),f={Type:"AWS::SNS::Topic",Properties:{TopicName:h,DisplayName:c||h,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:i}]}};if(l&&u)f.Properties.KmsMasterKeyId=u;return{topic:f,logicalId:y}}static subscribe(a,n){let{slug:i,environment:s,protocol:c,endpoint:l,filterPolicy:u,rawMessageDelivery:h=!1}=n,y=r({slug:i,environment:s,resourceType:"subscription"}),f=l.replace(/[^a-zA-Z0-9]/g,""),S=f.length>12?f.slice(-12):f,b=t(`${y}-${c}-${S}`),C={Type:"AWS::SNS::Subscription",Properties:{TopicArn:N.Ref(a),Protocol:c,Endpoint:l,RawMessageDelivery:h}};if(u)C.Properties.FilterPolicy=u;return{subscription:C,logicalId:b}}static subscribeEmail(a,n,i){return Y.subscribe(a,{...i,protocol:"email",endpoint:n})}static subscribeLambda(a,n,i){return Y.subscribe(a,{...i,protocol:"lambda",endpoint:n,rawMessageDelivery:!0})}static subscribeSqs(a,n,i){return Y.subscribe(a,{...i,protocol:"sqs",endpoint:n})}static subscribeHttp(a,n,i){let s=n.startsWith("https://")?"https":"http";return Y.subscribe(a,{...i,protocol:s,endpoint:n})}static subscribeSms(a,n,i){return Y.subscribe(a,{...i,protocol:"sms",endpoint:n})}static setTopicPolicy(a,n){let{slug:i,environment:s,allowedPrincipals:c,allowedServices:l,actions:u="SNS:Publish"}=n,h=r({slug:i,environment:s,resourceType:"topic-policy"}),y=t(h),f={};if(c)f.AWS=c;if(l)f.Service=l;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[N.Ref(a)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:f,Action:u,Resource:N.Ref(a)}]}}},logicalId:y}}static allowCloudWatchAlarms(a,n){return Y.setTopicPolicy(a,{...n,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge(a,n){return Y.setTopicPolicy(a,{...n,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3(a,n){return Y.setTopicPolicy(a,{...n,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption(a,n){if(!a.Properties)a.Properties={};return a.Properties.KmsMasterKeyId=n,a}static addInlineSubscription(a,n,i){if(!a.Properties)a.Properties={};if(!a.Properties.Subscription)a.Properties.Subscription=[];return a.Properties.Subscription.push({Protocol:n,Endpoint:i}),a}static FilterPolicies={eventType:(a)=>({eventType:a}),status:(a)=>({status:a}),numericRange:(a,n,i)=>({[a]:[{numeric:[">=",n,"<=",i]}]}),prefix:(a,n)=>({[a]:[{prefix:n}]}),and:(...a)=>Object.assign({},...a),exists:(a,n)=>({[a]:[{exists:n}]})};static UseCases={createAlertTopic:(a)=>Y.createTopic({...a,topicName:a.topicName||`${a.slug}-${a.environment}-alerts`,displayName:a.displayName||"Alert Notifications"}),createEventFanout:(a)=>Y.createTopic({...a,topicName:a.topicName||`${a.slug}-${a.environment}-events`,displayName:a.displayName||"Event Fanout"}),createNotificationTopic:(a)=>Y.createTopic({...a,topicName:a.topicName||`${a.slug}-${a.environment}-notifications`,displayName:a.displayName||"User Notifications"})}}class df{static createStateMachine(a){let{slug:n,environment:i,stateMachineName:s,type:c="STANDARD",definition:l,roleArn:u,loggingConfiguration:h,tracingConfiguration:y}=a,f=s||r({slug:n,environment:i,resourceType:"state-machine"}),S=t(f),b,C,T;if(u)T=u;else{let w=r({slug:n,environment:i,resourceType:"state-machine-role"});C=t(w),b={Type:"AWS::IAM::Role",Properties:{RoleName:w,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:i}]}},T=N.GetAtt(C,"Arn")}let v={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:f,StateMachineType:c,DefinitionString:JSON.stringify(l),RoleArn:T,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:i}]}};if(h)v.Properties.LoggingConfiguration={Level:h.level,IncludeExecutionData:h.includeExecutionData,Destinations:h.destinations?.map((w)=>({CloudWatchLogsLogGroup:{LogGroupArn:w}}))};if(y)v.Properties.TracingConfiguration={Enabled:y.enabled};return{stateMachine:v,logicalId:S,role:b,roleLogicalId:C}}static createLambdaTask(a,n){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:a,Payload:n?.parameters||{"Input.$":"$"}},ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createDynamoDBTask(a,n,i,s){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[a],Parameters:{TableName:n,...i},ResultPath:s?.resultPath,Retry:s?.retry,Catch:s?.catch,Next:s?.next,End:s?.end}}static createSNSPublishTask(a,n,i){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:a,Message:n},ResultPath:i?.resultPath,Retry:i?.retry,Catch:i?.catch,Next:i?.next,End:i?.end}}static createSQSSendMessageTask(a,n,i){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:a,MessageBody:n},ResultPath:i?.resultPath,Retry:i?.retry,Catch:i?.catch,Next:i?.next,End:i?.end}}static createPassState(a){return{Type:"Pass",Result:a?.result,ResultPath:a?.resultPath,Parameters:a?.parameters,Next:a?.next,End:a?.end}}static createWaitState(a){return{Type:"Wait",Seconds:a.seconds,Timestamp:a.timestamp,SecondsPath:a.secondsPath,TimestampPath:a.timestampPath,Next:a.next,End:a.end}}static createChoiceState(a,n){return{Type:"Choice",Choices:a,Default:n}}static createParallelState(a,n){return{Type:"Parallel",Branches:a,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createMapState(a,n){return{Type:"Map",ItemsPath:n?.itemsPath||"$.items",Iterator:a,MaxConcurrency:n?.maxConcurrency,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState(a,n){return{Type:"Fail",Error:a,Cause:n}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:(a,n,i,s)=>({ErrorEquals:a,IntervalSeconds:n,MaxAttempts:i,BackoffRate:s})};static CatchPolicies={all:(a,n)=>({ErrorEquals:["States.ALL"],Next:a,ResultPath:n||"$.error"}),specific:(a,n,i)=>({ErrorEquals:a,Next:n,ResultPath:i||"$.error"})};static Patterns={sequential:(a,n,i)=>{let s={};return i.forEach((c,l)=>{let u=l===i.length-1;s[c.name]={...c.state,Next:u?void 0:i[l+1].name,End:u}}),{Comment:"Sequential workflow",StartAt:i[0].name,States:s}},fanout:(a,n,i)=>({Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:i.map((s)=>s.definition),End:!0}}}),map:(a,n,i,s)=>({Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:i,MaxConcurrency:s,End:!0}}}),withErrorHandling:(a,n,i,s)=>({Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...i,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:s,Success:{Type:"Succeed"}}})}}class qs{static createAlarm(a){let{slug:n,environment:i,alarmName:s,metricName:c,namespace:l,statistic:u="Average",period:h=300,evaluationPeriods:y=1,threshold:f,comparisonOperator:S,treatMissingData:b="notBreaching",actionsEnabled:C=!0,alarmActions:T,okActions:v,insufficientDataActions:w,dimensions:R,unit:k,datapointsToAlarm:W}=a,P=s||r({slug:n,environment:i,resourceType:"alarm"}),V=t(P),B={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:P,MetricName:c,Namespace:l,Statistic:u,Period:h,EvaluationPeriods:y,Threshold:f,ComparisonOperator:S,TreatMissingData:b,ActionsEnabled:C}};if(T&&T.length>0)B.Properties.AlarmActions=T;if(v&&v.length>0)B.Properties.OKActions=v;if(w&&w.length>0)B.Properties.InsufficientDataActions=w;if(R)B.Properties.Dimensions=Object.entries(R).map(([j,J])=>({Name:j,Value:J}));if(k)B.Properties.Unit=k;if(W!==void 0)B.Properties.DatapointsToAlarm=W;return{alarm:B,logicalId:V}}static createCompositeAlarm(a){let{slug:n,environment:i,alarmName:s,alarmRule:c,actionsEnabled:l=!0,alarmActions:u,okActions:h,insufficientDataActions:y}=a,f=s||r({slug:n,environment:i,resourceType:"composite-alarm"}),S=t(f),b={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:f,AlarmRule:c,ActionsEnabled:l}};if(u&&u.length>0)b.Properties.AlarmActions=u;if(h&&h.length>0)b.Properties.OKActions=h;if(y&&y.length>0)b.Properties.InsufficientDataActions=y;return{alarm:b,logicalId:S}}static createDashboard(a){let{slug:n,environment:i,dashboardName:s,widgets:c}=a,l=s||r({slug:n,environment:i,resourceType:"dashboard"}),u=t(l),h={widgets:c.map((y)=>({type:y.type,x:y.x,y:y.y,width:y.width,height:y.height,properties:y.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:l,DashboardBody:JSON.stringify(h)}},logicalId:u}}static createLogGroup(a){let{slug:n,environment:i,logGroupName:s,retentionInDays:c,kmsKeyId:l}=a,u=s||r({slug:n,environment:i,resourceType:"log-group"}),h=t(u),y={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:u}};if(c!==void 0)y.Properties.RetentionInDays=c;if(l)y.Properties.KmsKeyId=l;return{logGroup:y,logicalId:h}}static createLogStream(a,n){let{slug:i,environment:s,logStreamName:c}=n,l=c||r({slug:i,environment:s,resourceType:"log-stream"}),u=t(l);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:N.Ref(a),LogStreamName:l}},logicalId:u}}static createMetricFilter(a,n){let{slug:i,environment:s,filterName:c,filterPattern:l,metricTransformations:u}=n,h=c||r({slug:i,environment:s,resourceType:"metric-filter"}),y=t(h);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:N.Ref(a),FilterPattern:l,MetricTransformations:u.map((f)=>({MetricName:f.metricName,MetricNamespace:f.metricNamespace,MetricValue:f.metricValue,DefaultValue:f.defaultValue,Unit:f.unit}))}},logicalId:y}}static AlarmTypes={highCpu:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i},alarmActions:c?[c]:void 0}),highMemory:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i},alarmActions:c?[c]:void 0}),highDisk:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:c?[c]:void 0}),lambdaErrors:(a,n,i,s=5,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:i},alarmActions:c?[c]:void 0}),lambdaThrottles:(a,n,i,s=10,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:i},alarmActions:c?[c]:void 0}),apiGateway5xxErrors:(a,n,i,s=10,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:i},alarmActions:c?[c]:void 0}),apiGateway4xxErrors:(a,n,i,s=50,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:i},alarmActions:c?[c]:void 0}),dynamoDBThrottles:(a,n,i,s=5,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:i},alarmActions:c?[c]:void 0}),rdsCpu:(a,n,i,s=80,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:i},alarmActions:c?[c]:void 0}),rdsFreeStorage:(a,n,i,s=5368709120,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:i},alarmActions:c?[c]:void 0,unit:"Bytes"}),sqsQueueDepth:(a,n,i,s=100,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:i},alarmActions:c?[c]:void 0}),albUnhealthyTargets:(a,n,i,s,c=1,l)=>({slug:a,environment:n,alarmName:`${a}-${n}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:c,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:i,TargetGroup:s},alarmActions:l?[l]:void 0}),sesBounceRate:(a,n,i=5,s)=>({slug:a,environment:n,alarmName:`${a}-${n}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:i/100,comparisonOperator:"GreaterThanThreshold",alarmActions:s?[s]:void 0}),sesComplaintRate:(a,n,i=0.1,s)=>({slug:a,environment:n,alarmName:`${a}-${n}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:i/100,comparisonOperator:"GreaterThanThreshold",alarmActions:s?[s]:void 0}),smsDeliveryFailure:(a,n,i,s=10,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:i},alarmActions:c?[c]:void 0}),smsSpendLimit:(a,n,i=100,s)=>({slug:a,environment:n,alarmName:`${a}-${n}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",alarmActions:s?[s]:void 0}),connectMissedCalls:(a,n,i,s=5,c)=>({slug:a,environment:n,alarmName:`${a}-${n}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:i},alarmActions:c?[c]:void 0})};static DashboardWidgets={metric:(a,n,i,s,c,l)=>({type:"metric",x:a,y:n,width:i,height:s,properties:{metrics:c,title:l||"Metrics",region:"us-east-1",period:300}}),text:(a,n,i,s,c)=>({type:"text",x:a,y:n,width:i,height:s,properties:{markdown:c}}),log:(a,n,i,s,c,l)=>({type:"log",x:a,y:n,width:i,height:s,properties:{query:`SOURCE '${c.join("' | SOURCE '")}'
2310
2310
  | fields @timestamp, @message
2311
2311
  | sort @timestamp desc
2312
2312
  | limit 20`,region:"us-east-1",title:l||"Logs"}})};static RetentionPeriods={ONE_DAY:1,THREE_DAYS:3,FIVE_DAYS:5,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,TWO_MONTHS:60,THREE_MONTHS:90,FOUR_MONTHS:120,FIVE_MONTHS:150,SIX_MONTHS:180,ONE_YEAR:365,THIRTEEN_MONTHS:400,EIGHTEEN_MONTHS:545,TWO_YEARS:731,FIVE_YEARS:1827,TEN_YEARS:3653,NEVER_EXPIRE:void 0};static FilterPatterns={errors:"[time, request_id, event_type = ERROR*, ...]",all:"",jsonField:(a,n)=>`{ $.${a} = "${n}" }`,httpStatus:(a)=>`[..., status_code = ${a}, ...]`,http4xx:"[..., status_code = 4*, ...]",http5xx:"[..., status_code = 5*, ...]"};static createApplicationDashboard(a){let{slug:n,environment:i,region:s="us-east-1",components:c={}}=a,l=[],u=0;if(l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:`# ${n.toUpperCase()} Dashboard (${i})`}}),u+=1,c.ec2InstanceIds&&c.ec2InstanceIds.length>0)l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:"## EC2 Instances"}}),u+=1,l.push({type:"metric",x:0,y:u,width:8,height:6,properties:{title:"CPU Utilization",region:s,metrics:c.ec2InstanceIds.map((h)=>["AWS/EC2","CPUUtilization","InstanceId",h]),period:300,stat:"Average"}}),l.push({type:"metric",x:8,y:u,width:8,height:6,properties:{title:"Network Traffic",region:s,metrics:[...c.ec2InstanceIds.flatMap((h)=>[["AWS/EC2","NetworkIn","InstanceId",h,{label:`${h} In`}],["AWS/EC2","NetworkOut","InstanceId",h,{label:`${h} Out`}]])],period:300,stat:"Sum"}}),l.push({type:"metric",x:16,y:u,width:8,height:6,properties:{title:"Status Checks",region:s,metrics:c.ec2InstanceIds.map((h)=>["AWS/EC2","StatusCheckFailed","InstanceId",h]),period:60,stat:"Maximum"}}),u+=6;if(c.lambdaFunctionNames&&c.lambdaFunctionNames.length>0)l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:"## Lambda Functions"}}),u+=1,l.push({type:"metric",x:0,y:u,width:8,height:6,properties:{title:"Invocations",region:s,metrics:c.lambdaFunctionNames.map((h)=>["AWS/Lambda","Invocations","FunctionName",h]),period:300,stat:"Sum"}}),l.push({type:"metric",x:8,y:u,width:8,height:6,properties:{title:"Duration",region:s,metrics:c.lambdaFunctionNames.map((h)=>["AWS/Lambda","Duration","FunctionName",h]),period:300,stat:"Average"}}),l.push({type:"metric",x:16,y:u,width:8,height:6,properties:{title:"Errors",region:s,metrics:c.lambdaFunctionNames.map((h)=>["AWS/Lambda","Errors","FunctionName",h]),period:300,stat:"Sum"}}),u+=6;if(c.ecsClusterName&&c.ecsServiceName)l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:"## ECS Service"}}),u+=1,l.push({type:"metric",x:0,y:u,width:8,height:6,properties:{title:"CPU Utilization",region:s,metrics:[["AWS/ECS","CPUUtilization","ClusterName",c.ecsClusterName,"ServiceName",c.ecsServiceName]],period:300,stat:"Average"}}),l.push({type:"metric",x:8,y:u,width:8,height:6,properties:{title:"Memory Utilization",region:s,metrics:[["AWS/ECS","MemoryUtilization","ClusterName",c.ecsClusterName,"ServiceName",c.ecsServiceName]],period:300,stat:"Average"}}),l.push({type:"metric",x:16,y:u,width:8,height:6,properties:{title:"Running Tasks",region:s,metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",c.ecsClusterName,"ServiceName",c.ecsServiceName]],period:60,stat:"Average"}}),u+=6;if(c.albName)l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:"## Application Load Balancer"}}),u+=1,l.push({type:"metric",x:0,y:u,width:8,height:6,properties:{title:"Request Count",region:s,metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",c.albName]],period:60,stat:"Sum"}}),l.push({type:"metric",x:8,y:u,width:8,height:6,properties:{title:"Response Time",region:s,metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",c.albName]],period:60,stat:"Average"}}),l.push({type:"metric",x:16,y:u,width:8,height:6,properties:{title:"HTTP Errors",region:s,metrics:[["AWS/ApplicationELB","HTTPCode_Target_4XX_Count","LoadBalancer",c.albName,{label:"4XX"}],["AWS/ApplicationELB","HTTPCode_Target_5XX_Count","LoadBalancer",c.albName,{label:"5XX"}]],period:60,stat:"Sum"}}),u+=6;if(c.rdsInstanceId)l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:"## RDS Database"}}),u+=1,l.push({type:"metric",x:0,y:u,width:8,height:6,properties:{title:"CPU Utilization",region:s,metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",c.rdsInstanceId]],period:300,stat:"Average"}}),l.push({type:"metric",x:8,y:u,width:8,height:6,properties:{title:"Database Connections",region:s,metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",c.rdsInstanceId]],period:60,stat:"Sum"}}),l.push({type:"metric",x:16,y:u,width:8,height:6,properties:{title:"Free Storage Space",region:s,metrics:[["AWS/RDS","FreeStorageSpace","DBInstanceIdentifier",c.rdsInstanceId]],period:300,stat:"Average"}}),u+=6;if(c.sqsQueueNames&&c.sqsQueueNames.length>0)l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:"## SQS Queues"}}),u+=1,l.push({type:"metric",x:0,y:u,width:12,height:6,properties:{title:"Messages Visible",region:s,metrics:c.sqsQueueNames.map((h)=>["AWS/SQS","ApproximateNumberOfMessagesVisible","QueueName",h]),period:60,stat:"Sum"}}),l.push({type:"metric",x:12,y:u,width:12,height:6,properties:{title:"Message Age",region:s,metrics:c.sqsQueueNames.map((h)=>["AWS/SQS","ApproximateAgeOfOldestMessage","QueueName",h]),period:60,stat:"Maximum"}}),u+=6;if(c.logGroupNames&&c.logGroupNames.length>0)l.push({type:"text",x:0,y:u,width:24,height:1,properties:{markdown:"## Application Logs"}}),u+=1,l.push({type:"log",x:0,y:u,width:24,height:6,properties:{query:`SOURCE '${c.logGroupNames.join("' | SOURCE '")}'
2313
2313
  | fields @timestamp, @message
2314
2314
  | filter @message like /ERROR|WARN|Exception/
2315
2315
  | sort @timestamp desc
2316
- | limit 50`,region:s,title:"Recent Errors and Warnings"}}),u+=6;return qs.createDashboard({slug:n,environment:i,widgets:l})}static DashboardTemplates={staticWebsite:(a)=>({slug:a.slug,environment:a.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${a.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",a.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",a.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",a.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",a.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:a.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",a.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:a.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",a.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(a)=>({slug:a.slug,environment:a.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${a.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:a.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",a.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:a.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",a.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:a.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",a.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",a.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...a.lambdaFunctionNames.map((n,i)=>({type:"metric",x:i%3*8,y:7+Math.floor(i/3)*6,width:8,height:6,properties:{title:`${n} Metrics`,region:a.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",n],["AWS/Lambda","Duration","FunctionName",n],["AWS/Lambda","Errors","FunctionName",n]],period:300,stat:"Sum"}}))]}),containerService:(a)=>({slug:a.slug,environment:a.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${a.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:a.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",a.ecsClusterName,"ServiceName",a.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:a.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",a.ecsClusterName,"ServiceName",a.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:a.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",a.ecsClusterName,"ServiceName",a.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:a.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",a.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:a.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",a.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:a.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",a.albName]],period:60,stat:"Average"}},...a.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:a.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",a.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:a.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",a.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(a)=>{let{metricName:n,namespace:i,threshold:s,comparisonOperator:c="GreaterThanThreshold",evaluationPeriods:l=1,period:u=300,statistic:h="Average",treatMissingData:y="missing"}=a;return{MetricName:n,Namespace:i,Threshold:s,ComparisonOperator:c,EvaluationPeriods:l,Period:u,Statistic:h,TreatMissingData:y}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(a=80)=>({metricName:"CPUUtilization",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(a=80)=>({metricName:"MemoryUtilization",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(a=10)=>({metricName:"Errors",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(a=5000)=>({metricName:"Duration",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(a=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:a,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(a=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(a=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:a,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class U{static createUserPool(a){let{slug:n,environment:i,userPoolName:s,aliasAttributes:c,autoVerifiedAttributes:l,passwordPolicy:u,mfaConfiguration:h,emailConfiguration:y,smsConfiguration:f,lambdaTriggers:S,userPoolAddOns:b,accountRecoverySetting:C}=a,T=s||r({slug:n,environment:i,resourceType:"user-pool"}),v=t(T),w={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:T,Policies:u?{PasswordPolicy:{MinimumLength:u.minimumLength,RequireLowercase:u.requireLowercase,RequireUppercase:u.requireUppercase,RequireNumbers:u.requireNumbers,RequireSymbols:u.requireSymbols,TemporaryPasswordValidityDays:u.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:h,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(c&&c.length>0)w.Properties.UsernameAttributes=c;if(l&&l.length>0)w.Properties.AutoVerifiedAttributes=l;if(y)w.Properties.EmailConfiguration={EmailSendingAccount:y.emailSendingAccount,From:y.from,ReplyToEmailAddress:y.replyToEmailAddress,SourceArn:y.sourceArn,ConfigurationSet:y.configurationSet};if(f)w.Properties.SmsConfiguration={ExternalId:f.externalId,SnsCallerArn:f.snsCallerArn};if(S)w.Properties.LambdaConfig={PreSignUp:S.preSignUp,PostConfirmation:S.postConfirmation,PreAuthentication:S.preAuthentication,PostAuthentication:S.postAuthentication,CustomMessage:S.customMessage,DefineAuthChallenge:S.defineAuthChallenge,CreateAuthChallenge:S.createAuthChallenge,VerifyAuthChallengeResponse:S.verifyAuthChallengeResponse,PreTokenGeneration:S.preTokenGeneration,UserMigration:S.userMigration};if(b)w.Properties.UserPoolAddOns={AdvancedSecurityMode:b.advancedSecurityMode};if(C)w.Properties.AccountRecoverySetting={RecoveryMechanisms:C.recoveryMechanisms};return{userPool:w,logicalId:v}}static createUserPoolClient(a,n){let{slug:i,environment:s,clientName:c,generateSecret:l=!1,refreshTokenValidity:u,accessTokenValidity:h,idTokenValidity:y,tokenValidityUnits:f,readAttributes:S,writeAttributes:b,explicitAuthFlows:C,preventUserExistenceErrors:T,enableTokenRevocation:v,callbackURLs:w,logoutURLs:R,allowedOAuthFlows:k,allowedOAuthScopes:W,allowedOAuthFlowsUserPoolClient:P,supportedIdentityProviders:V}=n,B=c||r({slug:i,environment:s,resourceType:"user-pool-client"}),j=t(B);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:B,UserPoolId:N.Ref(a),GenerateSecret:l,RefreshTokenValidity:u,AccessTokenValidity:h,IdTokenValidity:y,TokenValidityUnits:f,ReadAttributes:S,WriteAttributes:b,ExplicitAuthFlows:C,PreventUserExistenceErrors:T,EnableTokenRevocation:v,CallbackURLs:w,LogoutURLs:R,AllowedOAuthFlows:k,AllowedOAuthScopes:W,AllowedOAuthFlowsUserPoolClient:P,SupportedIdentityProviders:V}},logicalId:j}}static createUserPoolDomain(a,n){let{slug:i,environment:s,domain:c,customDomainConfig:l}=n,u=r({slug:i,environment:s,resourceType:"user-pool-domain"}),h=t(u);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:c,UserPoolId:N.Ref(a),CustomDomainConfig:l}},logicalId:h}}static createIdentityPool(a){let{slug:n,environment:i,identityPoolName:s,allowUnauthenticatedIdentities:c=!1,cognitoIdentityProviders:l,supportedLoginProviders:u,samlProviderARNs:h,openIdConnectProviderARNs:y}=a,f=s||r({slug:n,environment:i,resourceType:"identity-pool"}),S=t(f);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:f,AllowUnauthenticatedIdentities:c,CognitoIdentityProviders:l,SupportedLoginProviders:u,SamlProviderARNs:h,OpenIdConnectProviderARNs:y}},logicalId:S}}static createIdentityPoolRoleAttachment(a,n){let{slug:i,environment:s,authenticatedRole:c,unauthenticatedRole:l,roleMappings:u}=n,h=r({slug:i,environment:s,resourceType:"identity-pool-role-attachment"}),y=t(h),f={authenticated:c};if(l)f.unauthenticated=l;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:N.Ref(a),Roles:f,RoleMappings:u}},logicalId:y}}static createAuthenticatedRole(a){let{slug:n,environment:i,identityPoolLogicalId:s}=a,c=r({slug:n,environment:i,resourceType:"cognito-authenticated-role"}),l=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":N.Ref(s)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i}]}},logicalId:l}}static createUnauthenticatedRole(a){let{slug:n,environment:i,identityPoolLogicalId:s}=a,c=r({slug:n,environment:i,resourceType:"cognito-unauthenticated-role"}),l=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":N.Ref(s)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i}]}},logicalId:l}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(a,n,i)=>{let{userPool:s,logicalId:c}=U.createUserPool({slug:a,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:U.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:l,logicalId:u}=U.createUserPoolClient(c,{slug:a,environment:n,explicitAuthFlows:[...U.AuthFlows.standard],callbackURLs:[i],allowedOAuthFlows:["code"],allowedOAuthScopes:[...U.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:s,poolId:c,client:l,clientId:u}},mobileApp:(a,n)=>{let{userPool:i,logicalId:s}=U.createUserPool({slug:a,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:U.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:c,logicalId:l}=U.createUserPoolClient(s,{slug:a,environment:n,explicitAuthFlows:[...U.AuthFlows.standard]}),{identityPool:u,logicalId:h}=U.createIdentityPool({slug:a,environment:n,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:N.Ref(l),ProviderName:N.GetAtt(s,"ProviderName")}]}),{role:y,logicalId:f}=U.createAuthenticatedRole({slug:a,environment:n,identityPoolLogicalId:h}),{attachment:S,logicalId:b}=U.createIdentityPoolRoleAttachment(h,{slug:a,environment:n,authenticatedRole:N.GetAtt(f,"Arn")});return{userPool:i,poolId:s,client:c,clientId:l,identityPool:u,identityPoolId:h,authRole:y,authRoleId:f,attachment:S,attachmentId:b}}}}class Q{static createApplication(a){let{slug:n,environment:i,applicationName:s,computePlatform:c}=a,l=s||r({slug:n,environment:i,resourceType:"deploy-app"}),u=t(l);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:l,ComputePlatform:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:i}]}},logicalId:u}}static createDeploymentGroup(a,n){let{slug:i,environment:s,deploymentGroupName:c,serviceRoleArn:l,autoScalingGroups:u,ec2TagFilters:h,deploymentConfigName:y,autoRollbackConfiguration:f,alarmConfiguration:S,loadBalancerInfo:b,blueGreenDeploymentConfiguration:C}=n,T=c||r({slug:i,environment:s,resourceType:"deploy-group"}),v=t(T);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:N.Ref(a),DeploymentGroupName:T,ServiceRoleArn:l,AutoScalingGroups:u,Ec2TagFilters:h?.map((w)=>({Key:w.key,Value:w.value,Type:w.type})),DeploymentConfigName:y,AutoRollbackConfiguration:f?{Enabled:f.enabled,Events:f.events}:void 0,AlarmConfiguration:S?{Enabled:S.enabled,Alarms:S.alarms?.map((w)=>({Name:w.name})),IgnorePollAlarmFailure:S.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:b?{TargetGroupInfoList:b.targetGroupInfoList?.map((w)=>({Name:w.name})),ElbInfoList:b.elbInfoList?.map((w)=>({Name:w.name}))}:void 0,BlueGreenDeploymentConfiguration:C?{TerminateBlueInstancesOnDeploymentSuccess:C.terminateBlueInstancesOnDeploymentSuccess?{Action:C.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:C.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:C.deploymentReadyOption?{ActionOnTimeout:C.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:C.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:C.greenFleetProvisioningOption?{Action:C.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:T},{Key:"Environment",Value:s}]}},logicalId:v}}static createDeploymentConfig(a){let{slug:n,environment:i,deploymentConfigName:s,minimumHealthyHosts:c,trafficRoutingConfig:l}=a,u=s||r({slug:n,environment:i,resourceType:"deploy-config"}),h=t(u);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:u,MinimumHealthyHosts:c?{Type:c.type,Value:c.value}:void 0,TrafficRoutingConfig:l?{Type:l.type,TimeBasedCanary:l.timeBasedCanary?{CanaryPercentage:l.timeBasedCanary.canaryPercentage,CanaryInterval:l.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:l.timeBasedLinear?{LinearPercentage:l.timeBasedLinear.linearPercentage,LinearInterval:l.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:h}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(a,n)=>({type:a,value:n})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(a,n)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:a,canaryInterval:n}}),linear:(a,n)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:a,linearInterval:n}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(a)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:a},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(a)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:a},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(a,n,i,s)=>{let{application:c,logicalId:l}=Q.createApplication({slug:a,environment:n,computePlatform:"Server"}),{deploymentGroup:u,logicalId:h}=Q.createDeploymentGroup(l,{slug:a,environment:n,serviceRoleArn:i,autoScalingGroups:s,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Q.RollbackConfigs.onFailure()});return{application:c,appId:l,deploymentGroup:u,groupId:h}},lambdaCanaryDeployment:(a,n,i,s=10,c=5)=>{let{application:l,logicalId:u}=Q.createApplication({slug:a,environment:n,computePlatform:"Lambda"}),{deploymentConfig:h,logicalId:y}=Q.createDeploymentConfig({slug:a,environment:n,trafficRoutingConfig:Q.TrafficRouting.canary(s,c)}),{deploymentGroup:f,logicalId:S}=Q.createDeploymentGroup(u,{slug:a,environment:n,serviceRoleArn:i,deploymentConfigName:N.Ref(y),autoRollbackConfiguration:Q.RollbackConfigs.onAlarmOrFailure()});return{application:l,appId:u,deploymentConfig:h,configId:y,deploymentGroup:f,groupId:S}},ecsBlueGreenDeployment:(a,n,i,s)=>{let{application:c,logicalId:l}=Q.createApplication({slug:a,environment:n,computePlatform:"ECS"}),{deploymentGroup:u,logicalId:h}=Q.createDeploymentGroup(l,{slug:a,environment:n,serviceRoleArn:i,loadBalancerInfo:{targetGroupInfoList:[{name:s}]},blueGreenDeploymentConfiguration:Q.BlueGreenConfigs.standard(),autoRollbackConfiguration:Q.RollbackConfigs.onFailure()});return{application:c,appId:l,deploymentGroup:u,groupId:h}}};static Strategies={rolling:(a=25)=>({type:"rolling",batchPercentage:a}),blueGreen:()=>({type:"blue-green"}),canary:(a=10,n=5)=>({type:"canary",canaryPercentage:a,canaryInterval:n}),allAtOnce:()=>({type:"all-at-once"})}}class D{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(a,n="md5"){let i=nt(a);return br(n).update(i).digest("hex")}static computeShortHash(a){return D.computeFileHash(a).slice(0,8)}static getContentType(a){let n=sa(a).toLowerCase();return D.ContentTypes[n]||"application/octet-stream"}static shouldHashFile(a,n){return![...D.NoHashPatterns,...n||[]].some((i)=>i.test(a))}static generateHashedFilename(a,n){let i=sa(a),s=vr(a,i),c=ia(a);if(c===".")return`${s}.${n}${i}`;return He(c,`${s}.${n}${i}`)}static collectFiles(a,n){let i=[],s=n||a;if(!Et(a))return i;let c=Cr(a,{withFileTypes:!0});for(let l of c){let u=He(a,l.name);if(l.isDirectory())i.push(...D.collectFiles(u,s));else if(l.isFile())i.push(u)}return i}static hashDirectory(a){let{sourceDir:n,outputDir:i,excludePatterns:s=[],hashAlgorithm:c="md5",copyUnhashed:l=!0}=a,u=D.collectFiles(n),h=[],y={};for(let S of u){let b=S.replace(n,"").replace(/^[/\\]/,""),C=D.shouldHashFile(b,s),T=Tr(S),v=C?D.computeFileHash(S,c).slice(0,8):"",w=C?D.generateHashedFilename(b,v):b,R={originalPath:b,hashedPath:w,hash:v,size:T.size,contentType:D.getContentType(S)};if(h.push(R),y[b]=w,i){let k=He(i,w),W=ia(k);if(!Et(W)){let{mkdirSync:P}=Za("node:fs");P(W,{recursive:!0})}if(C||l)Ar(S,k)}}let f={version:"1.0",timestamp:new Date().toISOString(),assets:h,hashMap:y};if(i){let S=He(i,"asset-manifest.json");it(S,JSON.stringify(f,null,2))}return f}static getInvalidationPaths(a,n){let i=[];if(!a)return["/*"];let s=a.hashMap,c=n.hashMap;for(let[l,u]of Object.entries(c)){let h=s[l];if(!h||h!==u){if(i.push(`/${l}`),h&&h!==u)i.push(`/${h}`)}}for(let[l,u]of Object.entries(s))if(!c[l])i.push(`/${l}`),i.push(`/${u}`);if(i.length>100)return["/*"];return[...new Set(i)]}static updateHtmlReferences(a){let{htmlDir:n,manifest:i,basePath:s=""}=a,c=D.collectFiles(n).filter((l)=>l.endsWith(".html")||l.endsWith(".htm"));for(let l of c){let u=nt(l,"utf-8");for(let[h,y]of Object.entries(i.hashMap)){if(h===y)continue;let f=[new RegExp(`(src|href)=["']${s}/?${D.escapeRegExp(h)}["']`,"g"),new RegExp(`url\\(["']?${s}/?${D.escapeRegExp(h)}["']?\\)`,"g")];for(let S of f)u=u.replace(S,(b)=>b.replace(h,y))}it(l,u)}}static updateCssReferences(a){let{cssDir:n,manifest:i,basePath:s=""}=a,c=D.collectFiles(n).filter((l)=>l.endsWith(".css"));for(let l of c){let u=nt(l,"utf-8");for(let[h,y]of Object.entries(i.hashMap)){if(h===y)continue;let f=new RegExp(`url\\(["']?${s}/?${D.escapeRegExp(h)}["']?\\)`,"g");u=u.replace(f,`url(${s}/${y})`)}it(l,u)}}static escapeRegExp(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(a){let{sourceDir:n,keyPrefix:i="",excludePatterns:s=[],cacheControl:c={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=a;return D.hashDirectory({sourceDir:n,excludePatterns:s}).assets.map((l)=>{let u=l.hash!=="",h=l.contentType==="text/html",y=c.unhashed||"public, max-age=3600";if(h)y=c.html||"public, max-age=0, must-revalidate";else if(u)y=c.hashed||"public, max-age=31536000, immutable";return{localPath:He(n,l.originalPath),s3Key:i?`${i}/${l.hashedPath}`:l.hashedPath,contentType:l.contentType,cacheControl:y,hash:l.hash}})}static compareManifests(a,n){let i={added:[],removed:[],changed:[],unchanged:[]},s=new Set(Object.keys(a.hashMap)),c=new Set(Object.keys(n.hashMap));for(let l of c)if(!s.has(l))i.added.push(l);for(let l of s)if(!c.has(l))i.removed.push(l);for(let l of c)if(s.has(l))if(a.hashMap[l]!==n.hashMap[l])i.changed.push(l);else i.unchanged.push(l);return i}static loadManifest(a){if(!Et(a))return null;try{let n=nt(a,"utf-8");return JSON.parse(n)}catch{return null}}static saveManifest(a,n){it(n,JSON.stringify(a,null,2))}}class pi{static createSecret(a){let{slug:n,environment:i,secretName:s,description:c,secretString:l,kmsKeyId:u,tags:h}=a,y=s||r({slug:n,environment:i,resourceType:"secret"}),f=t(y),S={Type:"AWS::SecretsManager::Secret",Properties:{Name:y,Description:c,SecretString:l,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},...h?Object.entries(h).map(([b,C])=>({Key:b,Value:C})):[]]}};if(u)S.Properties.KmsKeyId=u;return{secret:S,logicalId:f}}static createGeneratedSecret(a){let{slug:n,environment:i,secretName:s,description:c,excludeCharacters:l,excludeLowercase:u,excludeNumbers:h,excludePunctuation:y,excludeUppercase:f,passwordLength:S,requireEachIncludedType:b,kmsKeyId:C,tags:T}=a,v=s||r({slug:n,environment:i,resourceType:"secret"}),w=t(v),R={Type:"AWS::SecretsManager::Secret",Properties:{Name:v,Description:c,GenerateSecretString:{ExcludeCharacters:l,ExcludeLowercase:u,ExcludeNumbers:h,ExcludePunctuation:y,ExcludeUppercase:f,PasswordLength:S||32,RequireEachIncludedType:b!==!1},Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:i},...T?Object.entries(T).map(([k,W])=>({Key:k,Value:W})):[]]}};if(C)R.Properties.KmsKeyId=C;return{secret:R,logicalId:w}}static createDatabaseSecret(a){let{slug:n,environment:i,secretName:s,username:c,dbname:l,engine:u,host:h,port:y,kmsKeyId:f}=a,S=s||r({slug:n,environment:i,resourceType:"db-secret"}),b=t(S),C={username:c};if(l)C.dbname=l;if(u)C.engine=u;if(h)C.host=h;if(y)C.port=y;let T={Type:"AWS::SecretsManager::Secret",Properties:{Name:S,Description:`Database credentials for ${c}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(C),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:i},{Key:"Type",Value:"database"}]}};if(f)T.Properties.KmsKeyId=f;return{secret:T,logicalId:b}}static attachToDatabase(a){let{slug:n,environment:i,secretId:s,targetId:c,targetType:l}=a,u=r({slug:n,environment:i,resourceType:"secret-attachment"}),h=t(u);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:s,TargetId:c,TargetType:l}},logicalId:h}}static enableRotation(a){let{slug:n,environment:i,secretId:s,rotationLambdaArn:c,automaticallyAfterDays:l,rotationType:u,kmsKeyArn:h,vpcSecurityGroupIds:y,vpcSubnetIds:f}=a,S=r({slug:n,environment:i,resourceType:"secret-rotation"}),b=t(S),C={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:s,RotationRules:{AutomaticallyAfterDays:l||30}}};if(c)C.Properties.RotationLambdaARN=c;else if(u)C.Properties.HostedRotationLambda={RotationType:u,KmsKeyArn:h,VpcSecurityGroupIds:y,VpcSubnetIds:f};return{rotation:C,logicalId:b}}static SecretTypes={apiKey:(a,n,i)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-${i}-api-key`,description:`API key for ${i}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(a,n,i)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-${i}-oauth-secret`,description:`OAuth client secret for ${i}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(a,n)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(a,n)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class E{static createParameter(a){let{slug:n,environment:i,parameterName:s,value:c,type:l="String",description:u,tier:h="Standard",tags:y}=a,f=s||r({slug:n,environment:i,resourceType:"parameter"}),S=t(f);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${n}/${i}/${f}`,Type:l,Value:c,Description:u,Tier:h,Tags:{Name:f,Environment:i,...y}}},logicalId:S}}static createString(a,n,i,s,c){return E.createParameter({slug:a,environment:n,parameterName:i,value:s,type:"String",description:c})}static createSecureString(a,n,i,s,c){return E.createParameter({slug:a,environment:n,parameterName:i,value:s,type:"SecureString",description:c})}static createStringList(a,n,i,s,c){return E.createParameter({slug:a,environment:n,parameterName:i,value:s.join(","),type:"StringList",description:c})}static Parameters={databaseUrl:(a,n,i)=>E.createSecureString(a,n,"database-url",i,"Database connection URL"),apiEndpoint:(a,n,i)=>E.createString(a,n,"api-endpoint",i,"API endpoint URL"),appVersion:(a,n,i)=>E.createString(a,n,"app-version",i,"Application version"),featureFlags:(a,n,i)=>E.createStringList(a,n,"feature-flags",i,"Enabled feature flags"),apiKey:(a,n,i,s)=>E.createSecureString(a,n,`${i}-api-key`,s,`API key for ${i}`),oauthCredentials:(a,n,i,s)=>{let c=E.createString(a,n,"oauth-client-id",i,"OAuth client ID"),l=E.createSecureString(a,n,"oauth-client-secret",s,"OAuth client secret");return{clientId:c,clientSecret:l}},smtpCredentials:(a,n,i,s,c,l)=>{let u=E.createString(a,n,"smtp-username",i,"SMTP username"),h=E.createSecureString(a,n,"smtp-password",s,"SMTP password"),y=E.createString(a,n,"smtp-host",c,"SMTP host"),f=E.createString(a,n,"smtp-port",l.toString(),"SMTP port");return{username:u,password:h,host:y,port:f}},redisUrl:(a,n,i)=>E.createSecureString(a,n,"redis-url",i,"Redis connection URL"),s3Bucket:(a,n,i)=>E.createString(a,n,"s3-bucket",i,"S3 bucket name"),cloudFrontDistribution:(a,n,i)=>E.createString(a,n,"cloudfront-distribution-id",i,"CloudFront distribution ID")}}class Ut{static createDomain(a){let{slug:n,environment:i,domainName:s,engineVersion:c="OpenSearch_2.11",instanceType:l="t3.small.search",instanceCount:u=1,volumeSize:h=10,volumeType:y="gp3",dedicatedMaster:f=!1,dedicatedMasterType:S,dedicatedMasterCount:b=3,multiAz:C=!1,availabilityZoneCount:T=2,vpc:v,encryption:w,enforceHttps:R=!0,tlsSecurityPolicy:k="Policy-Min-TLS-1-2-2019-07",advancedSecurity:W,autoSnapshotHour:P=0,autoTune:V=!0,tags:B={}}=a,j=s||r({slug:n,environment:i,resourceType:"search"}),Z=t(j);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:j,EngineVersion:c,ClusterConfig:{InstanceType:l,InstanceCount:u,DedicatedMasterEnabled:f,...f&&{DedicatedMasterType:S||l,DedicatedMasterCount:b},ZoneAwarenessEnabled:C,...C&&{ZoneAwarenessConfig:{AvailabilityZoneCount:T}}},EBSOptions:{EBSEnabled:!0,VolumeType:y,VolumeSize:h},DomainEndpointOptions:{EnforceHTTPS:R,TLSSecurityPolicy:k},SnapshotOptions:{AutomatedSnapshotStartHour:P},...v&&{VPCOptions:{SubnetIds:v.subnetIds,SecurityGroupIds:v.securityGroupIds}},...w&&{EncryptionAtRestOptions:{Enabled:w.atRest??!0,...w.kmsKeyId&&{KmsKeyId:w.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:w.nodeToNode??!0}},...W&&{AdvancedSecurityOptions:{Enabled:W.enabled,InternalUserDatabaseEnabled:W.internalUserDatabase??!0,...W.masterUserName&&W.masterUserPassword&&{MasterUserOptions:{MasterUserName:W.masterUserName,MasterUserPassword:W.masterUserPassword}},...W.masterUserArn&&{MasterUserOptions:{MasterUserARN:W.masterUserArn}}}},...V&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:j},{Key:"Environment",Value:i},...Object.entries(B).map(([K,ee])=>({Key:K,Value:ee}))]}},logicalId:Z}}static createAccessPolicy(a,n){let{ipAddresses:i,iamPrincipalArns:s,allowAll:c,vpcEndpoint:l}=n;if(c)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:a}]};let u=[];if(s&&s.length>0)u.push({Effect:"Allow",Principal:{AWS:s},Action:"es:*",Resource:a});if(i&&i.length>0)u.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:a,Condition:{IpAddress:{"aws:SourceIp":i}}});if(l)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:a}]};return{Version:"2012-10-17",Statement:u}}static DomainPresets={development:(a,n)=>Ut.createDomain({slug:a,environment:n,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(a,n,i)=>Ut.createDomain({slug:a,environment:n,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:i,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(a,n)=>Ut.createDomain({slug:a,environment:n,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(a,n,i)=>Ut.createDomain({slug:a,environment:n,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:i,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class ct{static createDomainRedirectBucket(a){let{slug:n,environment:i,sourceDomain:s,targetDomain:c,protocol:l="https"}=a,u=r({slug:n,environment:i,resourceType:"s3",suffix:"redirect"}),h=t(u),y=t(`${u}-policy`),f={Type:"AWS::S3::Bucket",Properties:{BucketName:s,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:l}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i},{Key:"Purpose",Value:"Domain Redirect"}]}},S={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(h),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[N.Join("",[N.GetAtt(h,"Arn"),"/*"])]}]}}};return{bucket:f,bucketPolicy:S,logicalId:h,policyLogicalId:y}}static createPathRedirectFunction(a){let{slug:n,environment:i,rules:s}=a,c=r({slug:n,environment:i,resourceType:"cf-redirect"}),l=t(c),u=ct.generateRedirectFunctionCode(s);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:c,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${n} (${i})`,Runtime:"cloudfront-js-2.0"},FunctionCode:u}},logicalId:l,functionCode:u}}static generateRedirectFunctionCode(a){return`function handler(event) {
2316
+ | limit 50`,region:s,title:"Recent Errors and Warnings"}}),u+=6;return qs.createDashboard({slug:n,environment:i,widgets:l})}static DashboardTemplates={staticWebsite:(a)=>({slug:a.slug,environment:a.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${a.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",a.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",a.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",a.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",a.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:a.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",a.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:a.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",a.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(a)=>({slug:a.slug,environment:a.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${a.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:a.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",a.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:a.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",a.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:a.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",a.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",a.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...a.lambdaFunctionNames.map((n,i)=>({type:"metric",x:i%3*8,y:7+Math.floor(i/3)*6,width:8,height:6,properties:{title:`${n} Metrics`,region:a.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",n],["AWS/Lambda","Duration","FunctionName",n],["AWS/Lambda","Errors","FunctionName",n]],period:300,stat:"Sum"}}))]}),containerService:(a)=>({slug:a.slug,environment:a.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${a.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:a.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",a.ecsClusterName,"ServiceName",a.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:a.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",a.ecsClusterName,"ServiceName",a.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:a.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",a.ecsClusterName,"ServiceName",a.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:a.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",a.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:a.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",a.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:a.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",a.albName]],period:60,stat:"Average"}},...a.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:a.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",a.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:a.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",a.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(a)=>{let{metricName:n,namespace:i,threshold:s,comparisonOperator:c="GreaterThanThreshold",evaluationPeriods:l=1,period:u=300,statistic:h="Average",treatMissingData:y="missing"}=a;return{MetricName:n,Namespace:i,Threshold:s,ComparisonOperator:c,EvaluationPeriods:l,Period:u,Statistic:h,TreatMissingData:y}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(a=80)=>({metricName:"CPUUtilization",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(a=80)=>({metricName:"MemoryUtilization",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(a=10)=>({metricName:"Errors",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(a=5000)=>({metricName:"Duration",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(a=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:a,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(a=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:a,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(a=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:a,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class U{static createUserPool(a){let{slug:n,environment:i,userPoolName:s,aliasAttributes:c,autoVerifiedAttributes:l,passwordPolicy:u,mfaConfiguration:h,emailConfiguration:y,smsConfiguration:f,lambdaTriggers:S,userPoolAddOns:b,accountRecoverySetting:C}=a,T=s||r({slug:n,environment:i,resourceType:"user-pool"}),v=t(T),w={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:T,Policies:u?{PasswordPolicy:{MinimumLength:u.minimumLength,RequireLowercase:u.requireLowercase,RequireUppercase:u.requireUppercase,RequireNumbers:u.requireNumbers,RequireSymbols:u.requireSymbols,TemporaryPasswordValidityDays:u.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:h,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(c&&c.length>0)w.Properties.UsernameAttributes=c;if(l&&l.length>0)w.Properties.AutoVerifiedAttributes=l;if(y)w.Properties.EmailConfiguration={EmailSendingAccount:y.emailSendingAccount,From:y.from,ReplyToEmailAddress:y.replyToEmailAddress,SourceArn:y.sourceArn,ConfigurationSet:y.configurationSet};if(f)w.Properties.SmsConfiguration={ExternalId:f.externalId,SnsCallerArn:f.snsCallerArn};if(S)w.Properties.LambdaConfig={PreSignUp:S.preSignUp,PostConfirmation:S.postConfirmation,PreAuthentication:S.preAuthentication,PostAuthentication:S.postAuthentication,CustomMessage:S.customMessage,DefineAuthChallenge:S.defineAuthChallenge,CreateAuthChallenge:S.createAuthChallenge,VerifyAuthChallengeResponse:S.verifyAuthChallengeResponse,PreTokenGeneration:S.preTokenGeneration,UserMigration:S.userMigration};if(b)w.Properties.UserPoolAddOns={AdvancedSecurityMode:b.advancedSecurityMode};if(C)w.Properties.AccountRecoverySetting={RecoveryMechanisms:C.recoveryMechanisms};return{userPool:w,logicalId:v}}static createUserPoolClient(a,n){let{slug:i,environment:s,clientName:c,generateSecret:l=!1,refreshTokenValidity:u,accessTokenValidity:h,idTokenValidity:y,tokenValidityUnits:f,readAttributes:S,writeAttributes:b,explicitAuthFlows:C,preventUserExistenceErrors:T,enableTokenRevocation:v,callbackURLs:w,logoutURLs:R,allowedOAuthFlows:k,allowedOAuthScopes:W,allowedOAuthFlowsUserPoolClient:P,supportedIdentityProviders:V}=n,B=c||r({slug:i,environment:s,resourceType:"user-pool-client"}),j=t(B);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:B,UserPoolId:N.Ref(a),GenerateSecret:l,RefreshTokenValidity:u,AccessTokenValidity:h,IdTokenValidity:y,TokenValidityUnits:f,ReadAttributes:S,WriteAttributes:b,ExplicitAuthFlows:C,PreventUserExistenceErrors:T,EnableTokenRevocation:v,CallbackURLs:w,LogoutURLs:R,AllowedOAuthFlows:k,AllowedOAuthScopes:W,AllowedOAuthFlowsUserPoolClient:P,SupportedIdentityProviders:V}},logicalId:j}}static createUserPoolDomain(a,n){let{slug:i,environment:s,domain:c,customDomainConfig:l}=n,u=r({slug:i,environment:s,resourceType:"user-pool-domain"}),h=t(u);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:c,UserPoolId:N.Ref(a),CustomDomainConfig:l}},logicalId:h}}static createIdentityPool(a){let{slug:n,environment:i,identityPoolName:s,allowUnauthenticatedIdentities:c=!1,cognitoIdentityProviders:l,supportedLoginProviders:u,samlProviderARNs:h,openIdConnectProviderARNs:y}=a,f=s||r({slug:n,environment:i,resourceType:"identity-pool"}),S=t(f);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:f,AllowUnauthenticatedIdentities:c,CognitoIdentityProviders:l,SupportedLoginProviders:u,SamlProviderARNs:h,OpenIdConnectProviderARNs:y}},logicalId:S}}static createIdentityPoolRoleAttachment(a,n){let{slug:i,environment:s,authenticatedRole:c,unauthenticatedRole:l,roleMappings:u}=n,h=r({slug:i,environment:s,resourceType:"identity-pool-role-attachment"}),y=t(h),f={authenticated:c};if(l)f.unauthenticated=l;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:N.Ref(a),Roles:f,RoleMappings:u}},logicalId:y}}static createAuthenticatedRole(a){let{slug:n,environment:i,identityPoolLogicalId:s}=a,c=r({slug:n,environment:i,resourceType:"cognito-authenticated-role"}),l=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":N.Ref(s)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i}]}},logicalId:l}}static createUnauthenticatedRole(a){let{slug:n,environment:i,identityPoolLogicalId:s}=a,c=r({slug:n,environment:i,resourceType:"cognito-unauthenticated-role"}),l=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":N.Ref(s)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i}]}},logicalId:l}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(a,n,i)=>{let{userPool:s,logicalId:c}=U.createUserPool({slug:a,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:U.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:l,logicalId:u}=U.createUserPoolClient(c,{slug:a,environment:n,explicitAuthFlows:[...U.AuthFlows.standard],callbackURLs:[i],allowedOAuthFlows:["code"],allowedOAuthScopes:[...U.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:s,poolId:c,client:l,clientId:u}},mobileApp:(a,n)=>{let{userPool:i,logicalId:s}=U.createUserPool({slug:a,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:U.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:c,logicalId:l}=U.createUserPoolClient(s,{slug:a,environment:n,explicitAuthFlows:[...U.AuthFlows.standard]}),{identityPool:u,logicalId:h}=U.createIdentityPool({slug:a,environment:n,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:N.Ref(l),ProviderName:N.GetAtt(s,"ProviderName")}]}),{role:y,logicalId:f}=U.createAuthenticatedRole({slug:a,environment:n,identityPoolLogicalId:h}),{attachment:S,logicalId:b}=U.createIdentityPoolRoleAttachment(h,{slug:a,environment:n,authenticatedRole:N.GetAtt(f,"Arn")});return{userPool:i,poolId:s,client:c,clientId:l,identityPool:u,identityPoolId:h,authRole:y,authRoleId:f,attachment:S,attachmentId:b}}}}class Q{static createApplication(a){let{slug:n,environment:i,applicationName:s,computePlatform:c}=a,l=s||r({slug:n,environment:i,resourceType:"deploy-app"}),u=t(l);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:l,ComputePlatform:c,Tags:[{Key:"Name",Value:l},{Key:"Environment",Value:i}]}},logicalId:u}}static createDeploymentGroup(a,n){let{slug:i,environment:s,deploymentGroupName:c,serviceRoleArn:l,autoScalingGroups:u,ec2TagFilters:h,deploymentConfigName:y,autoRollbackConfiguration:f,alarmConfiguration:S,loadBalancerInfo:b,blueGreenDeploymentConfiguration:C}=n,T=c||r({slug:i,environment:s,resourceType:"deploy-group"}),v=t(T);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:N.Ref(a),DeploymentGroupName:T,ServiceRoleArn:l,AutoScalingGroups:u,Ec2TagFilters:h?.map((w)=>({Key:w.key,Value:w.value,Type:w.type})),DeploymentConfigName:y,AutoRollbackConfiguration:f?{Enabled:f.enabled,Events:f.events}:void 0,AlarmConfiguration:S?{Enabled:S.enabled,Alarms:S.alarms?.map((w)=>({Name:w.name})),IgnorePollAlarmFailure:S.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:b?{TargetGroupInfoList:b.targetGroupInfoList?.map((w)=>({Name:w.name})),ElbInfoList:b.elbInfoList?.map((w)=>({Name:w.name}))}:void 0,BlueGreenDeploymentConfiguration:C?{TerminateBlueInstancesOnDeploymentSuccess:C.terminateBlueInstancesOnDeploymentSuccess?{Action:C.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:C.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:C.deploymentReadyOption?{ActionOnTimeout:C.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:C.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:C.greenFleetProvisioningOption?{Action:C.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:T},{Key:"Environment",Value:s}]}},logicalId:v}}static createDeploymentConfig(a){let{slug:n,environment:i,deploymentConfigName:s,minimumHealthyHosts:c,trafficRoutingConfig:l}=a,u=s||r({slug:n,environment:i,resourceType:"deploy-config"}),h=t(u);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:u,MinimumHealthyHosts:c?{Type:c.type,Value:c.value}:void 0,TrafficRoutingConfig:l?{Type:l.type,TimeBasedCanary:l.timeBasedCanary?{CanaryPercentage:l.timeBasedCanary.canaryPercentage,CanaryInterval:l.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:l.timeBasedLinear?{LinearPercentage:l.timeBasedLinear.linearPercentage,LinearInterval:l.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:h}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(a,n)=>({type:a,value:n})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(a,n)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:a,canaryInterval:n}}),linear:(a,n)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:a,linearInterval:n}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(a)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:a},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(a)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:a},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(a,n,i,s)=>{let{application:c,logicalId:l}=Q.createApplication({slug:a,environment:n,computePlatform:"Server"}),{deploymentGroup:u,logicalId:h}=Q.createDeploymentGroup(l,{slug:a,environment:n,serviceRoleArn:i,autoScalingGroups:s,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Q.RollbackConfigs.onFailure()});return{application:c,appId:l,deploymentGroup:u,groupId:h}},lambdaCanaryDeployment:(a,n,i,s=10,c=5)=>{let{application:l,logicalId:u}=Q.createApplication({slug:a,environment:n,computePlatform:"Lambda"}),{deploymentConfig:h,logicalId:y}=Q.createDeploymentConfig({slug:a,environment:n,trafficRoutingConfig:Q.TrafficRouting.canary(s,c)}),{deploymentGroup:f,logicalId:S}=Q.createDeploymentGroup(u,{slug:a,environment:n,serviceRoleArn:i,deploymentConfigName:N.Ref(y),autoRollbackConfiguration:Q.RollbackConfigs.onAlarmOrFailure()});return{application:l,appId:u,deploymentConfig:h,configId:y,deploymentGroup:f,groupId:S}},ecsBlueGreenDeployment:(a,n,i,s)=>{let{application:c,logicalId:l}=Q.createApplication({slug:a,environment:n,computePlatform:"ECS"}),{deploymentGroup:u,logicalId:h}=Q.createDeploymentGroup(l,{slug:a,environment:n,serviceRoleArn:i,loadBalancerInfo:{targetGroupInfoList:[{name:s}]},blueGreenDeploymentConfiguration:Q.BlueGreenConfigs.standard(),autoRollbackConfiguration:Q.RollbackConfigs.onFailure()});return{application:c,appId:l,deploymentGroup:u,groupId:h}}};static Strategies={rolling:(a=25)=>({type:"rolling",batchPercentage:a}),blueGreen:()=>({type:"blue-green"}),canary:(a=10,n=5)=>({type:"canary",canaryPercentage:a,canaryInterval:n}),allAtOnce:()=>({type:"all-at-once"})}}class D{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(a,n="md5"){let i=rt(a);return br(n).update(i).digest("hex")}static computeShortHash(a){return D.computeFileHash(a).slice(0,8)}static getContentType(a){let n=sa(a).toLowerCase();return D.ContentTypes[n]||"application/octet-stream"}static shouldHashFile(a,n){return![...D.NoHashPatterns,...n||[]].some((i)=>i.test(a))}static generateHashedFilename(a,n){let i=sa(a),s=vr(a,i),c=ia(a);if(c===".")return`${s}.${n}${i}`;return Ke(c,`${s}.${n}${i}`)}static collectFiles(a,n){let i=[],s=n||a;if(!Et(a))return i;let c=Cr(a,{withFileTypes:!0});for(let l of c){let u=Ke(a,l.name);if(l.isDirectory())i.push(...D.collectFiles(u,s));else if(l.isFile())i.push(u)}return i}static hashDirectory(a){let{sourceDir:n,outputDir:i,excludePatterns:s=[],hashAlgorithm:c="md5",copyUnhashed:l=!0}=a,u=D.collectFiles(n),h=[],y={};for(let S of u){let b=S.replace(n,"").replace(/^[/\\]/,""),C=D.shouldHashFile(b,s),T=Tr(S),v=C?D.computeFileHash(S,c).slice(0,8):"",w=C?D.generateHashedFilename(b,v):b,R={originalPath:b,hashedPath:w,hash:v,size:T.size,contentType:D.getContentType(S)};if(h.push(R),y[b]=w,i){let k=Ke(i,w),W=ia(k);if(!Et(W)){let{mkdirSync:P}=Za("node:fs");P(W,{recursive:!0})}if(C||l)Ar(S,k)}}let f={version:"1.0",timestamp:new Date().toISOString(),assets:h,hashMap:y};if(i){let S=Ke(i,"asset-manifest.json");nt(S,JSON.stringify(f,null,2))}return f}static getInvalidationPaths(a,n){let i=[];if(!a)return["/*"];let s=a.hashMap,c=n.hashMap;for(let[l,u]of Object.entries(c)){let h=s[l];if(!h||h!==u){if(i.push(`/${l}`),h&&h!==u)i.push(`/${h}`)}}for(let[l,u]of Object.entries(s))if(!c[l])i.push(`/${l}`),i.push(`/${u}`);if(i.length>100)return["/*"];return[...new Set(i)]}static updateHtmlReferences(a){let{htmlDir:n,manifest:i,basePath:s=""}=a,c=D.collectFiles(n).filter((l)=>l.endsWith(".html")||l.endsWith(".htm"));for(let l of c){let u=rt(l,"utf-8");for(let[h,y]of Object.entries(i.hashMap)){if(h===y)continue;let f=[new RegExp(`(src|href)=["']${s}/?${D.escapeRegExp(h)}["']`,"g"),new RegExp(`url\\(["']?${s}/?${D.escapeRegExp(h)}["']?\\)`,"g")];for(let S of f)u=u.replace(S,(b)=>b.replace(h,y))}nt(l,u)}}static updateCssReferences(a){let{cssDir:n,manifest:i,basePath:s=""}=a,c=D.collectFiles(n).filter((l)=>l.endsWith(".css"));for(let l of c){let u=rt(l,"utf-8");for(let[h,y]of Object.entries(i.hashMap)){if(h===y)continue;let f=new RegExp(`url\\(["']?${s}/?${D.escapeRegExp(h)}["']?\\)`,"g");u=u.replace(f,`url(${s}/${y})`)}nt(l,u)}}static escapeRegExp(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(a){let{sourceDir:n,keyPrefix:i="",excludePatterns:s=[],cacheControl:c={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=a;return D.hashDirectory({sourceDir:n,excludePatterns:s}).assets.map((l)=>{let u=l.hash!=="",h=l.contentType==="text/html",y=c.unhashed||"public, max-age=3600";if(h)y=c.html||"public, max-age=0, must-revalidate";else if(u)y=c.hashed||"public, max-age=31536000, immutable";return{localPath:Ke(n,l.originalPath),s3Key:i?`${i}/${l.hashedPath}`:l.hashedPath,contentType:l.contentType,cacheControl:y,hash:l.hash}})}static compareManifests(a,n){let i={added:[],removed:[],changed:[],unchanged:[]},s=new Set(Object.keys(a.hashMap)),c=new Set(Object.keys(n.hashMap));for(let l of c)if(!s.has(l))i.added.push(l);for(let l of s)if(!c.has(l))i.removed.push(l);for(let l of c)if(s.has(l))if(a.hashMap[l]!==n.hashMap[l])i.changed.push(l);else i.unchanged.push(l);return i}static loadManifest(a){if(!Et(a))return null;try{let n=rt(a,"utf-8");return JSON.parse(n)}catch{return null}}static saveManifest(a,n){nt(n,JSON.stringify(a,null,2))}}class pi{static createSecret(a){let{slug:n,environment:i,secretName:s,description:c,secretString:l,kmsKeyId:u,tags:h}=a,y=s||r({slug:n,environment:i,resourceType:"secret"}),f=t(y),S={Type:"AWS::SecretsManager::Secret",Properties:{Name:y,Description:c,SecretString:l,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:i},...h?Object.entries(h).map(([b,C])=>({Key:b,Value:C})):[]]}};if(u)S.Properties.KmsKeyId=u;return{secret:S,logicalId:f}}static createGeneratedSecret(a){let{slug:n,environment:i,secretName:s,description:c,excludeCharacters:l,excludeLowercase:u,excludeNumbers:h,excludePunctuation:y,excludeUppercase:f,passwordLength:S,requireEachIncludedType:b,kmsKeyId:C,tags:T}=a,v=s||r({slug:n,environment:i,resourceType:"secret"}),w=t(v),R={Type:"AWS::SecretsManager::Secret",Properties:{Name:v,Description:c,GenerateSecretString:{ExcludeCharacters:l,ExcludeLowercase:u,ExcludeNumbers:h,ExcludePunctuation:y,ExcludeUppercase:f,PasswordLength:S||32,RequireEachIncludedType:b!==!1},Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:i},...T?Object.entries(T).map(([k,W])=>({Key:k,Value:W})):[]]}};if(C)R.Properties.KmsKeyId=C;return{secret:R,logicalId:w}}static createDatabaseSecret(a){let{slug:n,environment:i,secretName:s,username:c,dbname:l,engine:u,host:h,port:y,kmsKeyId:f}=a,S=s||r({slug:n,environment:i,resourceType:"db-secret"}),b=t(S),C={username:c};if(l)C.dbname=l;if(u)C.engine=u;if(h)C.host=h;if(y)C.port=y;let T={Type:"AWS::SecretsManager::Secret",Properties:{Name:S,Description:`Database credentials for ${c}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(C),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:i},{Key:"Type",Value:"database"}]}};if(f)T.Properties.KmsKeyId=f;return{secret:T,logicalId:b}}static attachToDatabase(a){let{slug:n,environment:i,secretId:s,targetId:c,targetType:l}=a,u=r({slug:n,environment:i,resourceType:"secret-attachment"}),h=t(u);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:s,TargetId:c,TargetType:l}},logicalId:h}}static enableRotation(a){let{slug:n,environment:i,secretId:s,rotationLambdaArn:c,automaticallyAfterDays:l,rotationType:u,kmsKeyArn:h,vpcSecurityGroupIds:y,vpcSubnetIds:f}=a,S=r({slug:n,environment:i,resourceType:"secret-rotation"}),b=t(S),C={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:s,RotationRules:{AutomaticallyAfterDays:l||30}}};if(c)C.Properties.RotationLambdaARN=c;else if(u)C.Properties.HostedRotationLambda={RotationType:u,KmsKeyArn:h,VpcSecurityGroupIds:y,VpcSubnetIds:f};return{rotation:C,logicalId:b}}static SecretTypes={apiKey:(a,n,i)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-${i}-api-key`,description:`API key for ${i}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(a,n,i)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-${i}-oauth-secret`,description:`OAuth client secret for ${i}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(a,n)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(a,n)=>pi.createGeneratedSecret({slug:a,environment:n,secretName:`${a}-${n}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class E{static createParameter(a){let{slug:n,environment:i,parameterName:s,value:c,type:l="String",description:u,tier:h="Standard",tags:y}=a,f=s||r({slug:n,environment:i,resourceType:"parameter"}),S=t(f);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${n}/${i}/${f}`,Type:l,Value:c,Description:u,Tier:h,Tags:{Name:f,Environment:i,...y}}},logicalId:S}}static createString(a,n,i,s,c){return E.createParameter({slug:a,environment:n,parameterName:i,value:s,type:"String",description:c})}static createSecureString(a,n,i,s,c){return E.createParameter({slug:a,environment:n,parameterName:i,value:s,type:"SecureString",description:c})}static createStringList(a,n,i,s,c){return E.createParameter({slug:a,environment:n,parameterName:i,value:s.join(","),type:"StringList",description:c})}static Parameters={databaseUrl:(a,n,i)=>E.createSecureString(a,n,"database-url",i,"Database connection URL"),apiEndpoint:(a,n,i)=>E.createString(a,n,"api-endpoint",i,"API endpoint URL"),appVersion:(a,n,i)=>E.createString(a,n,"app-version",i,"Application version"),featureFlags:(a,n,i)=>E.createStringList(a,n,"feature-flags",i,"Enabled feature flags"),apiKey:(a,n,i,s)=>E.createSecureString(a,n,`${i}-api-key`,s,`API key for ${i}`),oauthCredentials:(a,n,i,s)=>{let c=E.createString(a,n,"oauth-client-id",i,"OAuth client ID"),l=E.createSecureString(a,n,"oauth-client-secret",s,"OAuth client secret");return{clientId:c,clientSecret:l}},smtpCredentials:(a,n,i,s,c,l)=>{let u=E.createString(a,n,"smtp-username",i,"SMTP username"),h=E.createSecureString(a,n,"smtp-password",s,"SMTP password"),y=E.createString(a,n,"smtp-host",c,"SMTP host"),f=E.createString(a,n,"smtp-port",l.toString(),"SMTP port");return{username:u,password:h,host:y,port:f}},redisUrl:(a,n,i)=>E.createSecureString(a,n,"redis-url",i,"Redis connection URL"),s3Bucket:(a,n,i)=>E.createString(a,n,"s3-bucket",i,"S3 bucket name"),cloudFrontDistribution:(a,n,i)=>E.createString(a,n,"cloudfront-distribution-id",i,"CloudFront distribution ID")}}class Ut{static createDomain(a){let{slug:n,environment:i,domainName:s,engineVersion:c="OpenSearch_2.11",instanceType:l="t3.small.search",instanceCount:u=1,volumeSize:h=10,volumeType:y="gp3",dedicatedMaster:f=!1,dedicatedMasterType:S,dedicatedMasterCount:b=3,multiAz:C=!1,availabilityZoneCount:T=2,vpc:v,encryption:w,enforceHttps:R=!0,tlsSecurityPolicy:k="Policy-Min-TLS-1-2-2019-07",advancedSecurity:W,autoSnapshotHour:P=0,autoTune:V=!0,tags:B={}}=a,j=s||r({slug:n,environment:i,resourceType:"search"}),J=t(j);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:j,EngineVersion:c,ClusterConfig:{InstanceType:l,InstanceCount:u,DedicatedMasterEnabled:f,...f&&{DedicatedMasterType:S||l,DedicatedMasterCount:b},ZoneAwarenessEnabled:C,...C&&{ZoneAwarenessConfig:{AvailabilityZoneCount:T}}},EBSOptions:{EBSEnabled:!0,VolumeType:y,VolumeSize:h},DomainEndpointOptions:{EnforceHTTPS:R,TLSSecurityPolicy:k},SnapshotOptions:{AutomatedSnapshotStartHour:P},...v&&{VPCOptions:{SubnetIds:v.subnetIds,SecurityGroupIds:v.securityGroupIds}},...w&&{EncryptionAtRestOptions:{Enabled:w.atRest??!0,...w.kmsKeyId&&{KmsKeyId:w.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:w.nodeToNode??!0}},...W&&{AdvancedSecurityOptions:{Enabled:W.enabled,InternalUserDatabaseEnabled:W.internalUserDatabase??!0,...W.masterUserName&&W.masterUserPassword&&{MasterUserOptions:{MasterUserName:W.masterUserName,MasterUserPassword:W.masterUserPassword}},...W.masterUserArn&&{MasterUserOptions:{MasterUserARN:W.masterUserArn}}}},...V&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:j},{Key:"Environment",Value:i},...Object.entries(B).map(([K,ee])=>({Key:K,Value:ee}))]}},logicalId:J}}static createAccessPolicy(a,n){let{ipAddresses:i,iamPrincipalArns:s,allowAll:c,vpcEndpoint:l}=n;if(c)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:a}]};let u=[];if(s&&s.length>0)u.push({Effect:"Allow",Principal:{AWS:s},Action:"es:*",Resource:a});if(i&&i.length>0)u.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:a,Condition:{IpAddress:{"aws:SourceIp":i}}});if(l)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:a}]};return{Version:"2012-10-17",Statement:u}}static DomainPresets={development:(a,n)=>Ut.createDomain({slug:a,environment:n,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(a,n,i)=>Ut.createDomain({slug:a,environment:n,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:i,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(a,n)=>Ut.createDomain({slug:a,environment:n,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(a,n,i)=>Ut.createDomain({slug:a,environment:n,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:i,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class dt{static createDomainRedirectBucket(a){let{slug:n,environment:i,sourceDomain:s,targetDomain:c,protocol:l="https"}=a,u=r({slug:n,environment:i,resourceType:"s3",suffix:"redirect"}),h=t(u),y=t(`${u}-policy`),f={Type:"AWS::S3::Bucket",Properties:{BucketName:s,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:l}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i},{Key:"Purpose",Value:"Domain Redirect"}]}},S={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:N.Ref(h),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[N.Join("",[N.GetAtt(h,"Arn"),"/*"])]}]}}};return{bucket:f,bucketPolicy:S,logicalId:h,policyLogicalId:y}}static createPathRedirectFunction(a){let{slug:n,environment:i,rules:s}=a,c=r({slug:n,environment:i,resourceType:"cf-redirect"}),l=t(c),u=dt.generateRedirectFunctionCode(s);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:c,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${n} (${i})`,Runtime:"cloudfront-js-2.0"},FunctionCode:u}},logicalId:l,functionCode:u}}static generateRedirectFunctionCode(a){return`function handler(event) {
2317
2317
  const request = event.request;
2318
2318
  const uri = request.uri;
2319
2319
  const querystring = request.querystring;
@@ -2367,7 +2367,7 @@ ${a.map((n)=>{let i=n.preserveQueryString!==!1,s=n.statusCode||301;return` '${n
2367
2367
  }
2368
2368
 
2369
2369
  return request;
2370
- }`}static CommonRedirects={wwwToApex:(a,n="https")=>({slug:a.replace(/\./g,"-"),environment:"production",sourceDomain:`www.${a}`,targetDomain:a,protocol:n,preservePath:!0}),apexToWww:(a,n="https")=>({slug:a.replace(/\./g,"-"),environment:"production",sourceDomain:a,targetDomain:`www.${a}`,protocol:n,preservePath:!0}),httpToHttps:(a="/")=>({source:a,target:a,statusCode:301}),addTrailingSlash:(a)=>a.map((n)=>({source:n.endsWith("/")?n.slice(0,-1):n,target:n.endsWith("/")?n:`${n}/`,statusCode:301})),removeTrailingSlash:(a)=>a.map((n)=>({source:n.endsWith("/")&&n!=="/"?n:`${n}/`,target:n.endsWith("/")&&n!=="/"?n.slice(0,-1):n,statusCode:301}))};static Patterns={flattenBlogUrls:(a)=>a.map(({oldPath:n,newPath:i})=>({source:n,target:i,statusCode:301,preserveQueryString:!0})),categoryRename:(a,n)=>[{source:`/${a}`,target:`/${n}`,statusCode:301},{source:`/${a}/`,target:`/${n}/`,statusCode:301}],productSlugChange:(a)=>a.map(({oldSlug:n,newSlug:i})=>({source:`/products/${n}`,target:`/products/${i}`,statusCode:301})),apiVersionRedirect:(a,n,i)=>i.map((s)=>({source:`/api/${a}/${s}`,target:`/api/${n}/${s}`,statusCode:307,preserveQueryString:!0})),gonePages:(a)=>a.map((n)=>({source:n,target:"/410",statusCode:301}))};static createRedirectSetup(a){let{slug:n,environment:i,domainRedirects:s=[],pathRedirects:c=[]}=a,l={},u=[];for(let y of s){let{bucket:f,bucketPolicy:S,logicalId:b,policyLogicalId:C}=ct.createDomainRedirectBucket({...y,slug:n,environment:i});l[b]=f,l[C]=S,u.push(b)}let h=null;if(c.length>0){let{function:y,logicalId:f}=ct.createPathRedirectFunction({slug:n,environment:i,rules:c});l[f]=y,h=f}return{resources:l,outputs:{domainRedirectBuckets:u,pathRedirectFunctionLogicalId:h}}}static fromMapping(a,n){return Object.entries(a).map(([i,s])=>({source:i,target:s,statusCode:n?.statusCode||301,preserveQueryString:n?.preserveQueryString??!0}))}static validateRules(a){let n=[],i=[],s=new Set;for(let c of a){if(s.has(c.source))n.push(`Duplicate source path: ${c.source}`);if(s.add(c.source),c.source===c.target)n.push(`Redirect loop detected: ${c.source} -> ${c.target}`);if(!c.target.startsWith("/")&&!c.target.startsWith("http"))i.push(`Target URL should start with / or http: ${c.target}`);if(!c.source||c.source.trim()==="")n.push("Source path cannot be empty");if(!c.target||c.target.trim()==="")n.push("Target path cannot be empty")}for(let c of a){let l=a.find((u)=>u.source===c.target);if(l)i.push(`Potential redirect chain: ${c.source} -> ${c.target} -> ${l.target}`)}return{valid:n.length===0,errors:n,warnings:i}}}class H{static generate(a){let n={},{slug:i,environment:s,region:c="us-east-1"}=a,l=H.createLambdaExecutionRole(i,s);if(Object.assign(n,l.resources),a.email?.enabled){let u=H.generateEmailResources(a,l.roleArn);Object.assign(n,u)}if(a.phone?.enabled){let u=H.generatePhoneResources(a,l.roleArn);Object.assign(n,u)}if(a.sms?.enabled){let u=H.generateSmsResources(a,l.roleArn);Object.assign(n,u)}return n}static createLambdaExecutionRole(a,n){let i=`${a}-${n}-communication-role`,s=t(i);return{resources:{[s]:{Type:"AWS::IAM::Role",Properties:{RoleName:i,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"CommunicationPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish","sns:Subscribe"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchWriteItem","dynamodb:BatchGetItem"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"},{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetEndpoint","mobiletargeting:UpdateEndpoint"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["bedrock:InvokeModel"],Resource:"*"},{Effect:"Allow",Action:["es:ESHttpGet","es:ESHttpPost","es:ESHttpPut","es:ESHttpDelete"],Resource:"*"}]}}]}}},roleArn:N.GetAtt(s,"Arn"),roleName:i}}static generateEmailResources(a,n){let{slug:i,environment:s,email:c}=a;if(!c)return{};let l={},u=`${i}-${s}`,h=`${u}-email-storage`,y=t(h);l[y]={Type:"AWS::S3::Bucket",Properties:{BucketName:h,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:c.server?.storage?.archiveAfterDays?[{StorageClass:"GLACIER",TransitionInDays:c.server.storage.archiveAfterDays}]:[],ExpirationInDays:c.server?.storage?.retentionDays||365}]},NotificationConfiguration:{LambdaConfigurations:[]}}};let f=t(`${u}-ses-identity`);if(l[f]={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:c.domain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:!0}}},c.notifications?.bounces||c.notifications?.complaints){let S=t(`${u}-bounce-topic`);l[S]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-email-bounces`}};let b=t(`${u}-complaint-topic`);l[b]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-email-complaints`}}}if(c.server?.enabled){let S=t(`${u}-inbound-email`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:H.InboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:h,DOMAIN:c.domain}}}};let b=t(`${u}-outbound-email`);l[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-outbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.OutboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:h,DOMAIN:c.domain}}}}}if(c.advanced?.analytics){let S=t(`${u}-email-analytics`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.scheduling){let S=t(`${u}-email-scheduler`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:300,MemorySize:256,Code:{ZipFile:H.EmailSchedulerCode},Environment:{Variables:{EMAIL_BUCKET:h}}}};let b=t(`${u}-email-scheduler-rule`);l[b]={Type:"AWS::Events::Rule",Properties:{Name:`${u}-email-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:N.GetAtt(S,"Arn")}]}}}if(c.advanced?.threading){let S=t(`${u}-email-threading`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:H.EmailThreadingCode},Environment:{Variables:{EMAIL_BUCKET:h}}}}}if(c.advanced?.rules){let S=t(`${u}-email-rules`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}if(c.advanced?.sharedMailboxes){let S=t(`${u}-shared-mailboxes`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-shared-mailboxes`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"},{AttributeName:"type",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"type-index",KeySchema:[{AttributeName:"type",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}]}}}if(c.advanced?.search){let S=t(`${u}-email-search`);l[S]={Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:`${u}-email-search`.toLowerCase().replace(/[^a-z0-9-]/g,"-").substring(0,28),EngineVersion:"OpenSearch_2.11",ClusterConfig:{InstanceType:"t3.small.search",InstanceCount:1},EBSOptions:{EBSEnabled:!0,VolumeType:"gp3",VolumeSize:10},NodeToNodeEncryptionOptions:{Enabled:!0},EncryptionAtRestOptions:{Enabled:!0},DomainEndpointOptions:{EnforceHTTPS:!0}}}}return l}static generatePhoneResources(a,n){let{slug:i,environment:s,phone:c}=a;if(!c)return{};let l={},u=`${i}-${s}`,h=t(`${u}-call-log`);if(l[h]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.voicemail?.enabled){let S=t(`${u}-voicemail`);l[S]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${u}-voicemail`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}}}let y=t(`${u}-phone-notifications`);l[y]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-phone-notifications`}};let f=t(`${u}-incoming-call`);if(l[f]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.IncomingCallCode},Environment:{Variables:{CALL_LOG_TABLE:`${u}-call-log`,NOTIFICATION_TOPIC_ARN:N.Ref(y)}}}},c.voicemail?.enabled){let S=t(`${u}-voicemail-handler`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-voicemail-handler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:c.voicemail.transcription?300:60,MemorySize:256,Code:{ZipFile:H.VoicemailCode},Environment:{Variables:{VOICEMAIL_BUCKET:`${u}-voicemail`,TRANSCRIPTION_ENABLED:String(c.voicemail.transcription||!1),NOTIFICATION_TOPIC_ARN:N.Ref(y)}}}}}if(c.advanced?.recording){let S=t(`${u}-call-recordings`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.callbacks){let S=t(`${u}-callbacks`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.analytics){let S=t(`${u}-call-metrics`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}return l}static generateSmsResources(a,n){let{slug:i,environment:s,sms:c}=a;if(!c)return{};let l={},u=`${i}-${s}`,h=t(`${u}-pinpoint-app`);l[h]={Type:"AWS::Pinpoint::App",Properties:{Name:`${u}-sms`}};let y=t(`${u}-sms-channel`);l[y]={Type:"AWS::Pinpoint::SMSChannel",Properties:{ApplicationId:N.Ref(h),Enabled:!0,SenderId:c.senderId}};let f=t(`${u}-sms-log`);if(l[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.optOut?.enabled){let T=t(`${u}-sms-optout`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-optout`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}let S=t(`${u}-sms-notifications`);l[S]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-sms-notifications`}};let b=t(`${u}-send-sms`);l[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-send-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.SendSmsCode},Environment:{Variables:{PINPOINT_APP_ID:N.Ref(h),MESSAGE_LOG_TABLE:`${u}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${u}-sms-optout`:"",MESSAGE_TYPE:c.messageType||"TRANSACTIONAL"}}}};let C=t(`${u}-receive-sms`);if(l[C]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-receive-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.ReceiveSmsCode},Environment:{Variables:{MESSAGE_LOG_TABLE:`${u}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${u}-sms-optout`:"",NOTIFICATION_TOPIC_ARN:N.Ref(S)}}}},c.advanced?.campaigns){let T=t(`${u}-sms-campaigns`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-campaigns`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.analytics){let T=t(`${u}-sms-analytics`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.linkTracking){let T=t(`${u}-short-links`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.chatbot){let T=t(`${u}-chatbot-sessions`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}};let v=t(`${u}-chatbot-rules`);l[v]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.abTesting){let T=t(`${u}-ab-tests`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.mms){let T=t(`${u}-mms-media`);l[T]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${u}-mms-media`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldMedia",Status:"Enabled",ExpirationInDays:30}]}}}}return l}static InboundEmailCode=`
2370
+ }`}static CommonRedirects={wwwToApex:(a,n="https")=>({slug:a.replace(/\./g,"-"),environment:"production",sourceDomain:`www.${a}`,targetDomain:a,protocol:n,preservePath:!0}),apexToWww:(a,n="https")=>({slug:a.replace(/\./g,"-"),environment:"production",sourceDomain:a,targetDomain:`www.${a}`,protocol:n,preservePath:!0}),httpToHttps:(a="/")=>({source:a,target:a,statusCode:301}),addTrailingSlash:(a)=>a.map((n)=>({source:n.endsWith("/")?n.slice(0,-1):n,target:n.endsWith("/")?n:`${n}/`,statusCode:301})),removeTrailingSlash:(a)=>a.map((n)=>({source:n.endsWith("/")&&n!=="/"?n:`${n}/`,target:n.endsWith("/")&&n!=="/"?n.slice(0,-1):n,statusCode:301}))};static Patterns={flattenBlogUrls:(a)=>a.map(({oldPath:n,newPath:i})=>({source:n,target:i,statusCode:301,preserveQueryString:!0})),categoryRename:(a,n)=>[{source:`/${a}`,target:`/${n}`,statusCode:301},{source:`/${a}/`,target:`/${n}/`,statusCode:301}],productSlugChange:(a)=>a.map(({oldSlug:n,newSlug:i})=>({source:`/products/${n}`,target:`/products/${i}`,statusCode:301})),apiVersionRedirect:(a,n,i)=>i.map((s)=>({source:`/api/${a}/${s}`,target:`/api/${n}/${s}`,statusCode:307,preserveQueryString:!0})),gonePages:(a)=>a.map((n)=>({source:n,target:"/410",statusCode:301}))};static createRedirectSetup(a){let{slug:n,environment:i,domainRedirects:s=[],pathRedirects:c=[]}=a,l={},u=[];for(let y of s){let{bucket:f,bucketPolicy:S,logicalId:b,policyLogicalId:C}=dt.createDomainRedirectBucket({...y,slug:n,environment:i});l[b]=f,l[C]=S,u.push(b)}let h=null;if(c.length>0){let{function:y,logicalId:f}=dt.createPathRedirectFunction({slug:n,environment:i,rules:c});l[f]=y,h=f}return{resources:l,outputs:{domainRedirectBuckets:u,pathRedirectFunctionLogicalId:h}}}static fromMapping(a,n){return Object.entries(a).map(([i,s])=>({source:i,target:s,statusCode:n?.statusCode||301,preserveQueryString:n?.preserveQueryString??!0}))}static validateRules(a){let n=[],i=[],s=new Set;for(let c of a){if(s.has(c.source))n.push(`Duplicate source path: ${c.source}`);if(s.add(c.source),c.source===c.target)n.push(`Redirect loop detected: ${c.source} -> ${c.target}`);if(!c.target.startsWith("/")&&!c.target.startsWith("http"))i.push(`Target URL should start with / or http: ${c.target}`);if(!c.source||c.source.trim()==="")n.push("Source path cannot be empty");if(!c.target||c.target.trim()==="")n.push("Target path cannot be empty")}for(let c of a){let l=a.find((u)=>u.source===c.target);if(l)i.push(`Potential redirect chain: ${c.source} -> ${c.target} -> ${l.target}`)}return{valid:n.length===0,errors:n,warnings:i}}}class H{static generate(a){let n={},{slug:i,environment:s,region:c="us-east-1"}=a,l=H.createLambdaExecutionRole(i,s);if(Object.assign(n,l.resources),a.email?.enabled){let u=H.generateEmailResources(a,l.roleArn);Object.assign(n,u)}if(a.phone?.enabled){let u=H.generatePhoneResources(a,l.roleArn);Object.assign(n,u)}if(a.sms?.enabled){let u=H.generateSmsResources(a,l.roleArn);Object.assign(n,u)}return n}static createLambdaExecutionRole(a,n){let i=`${a}-${n}-communication-role`,s=t(i);return{resources:{[s]:{Type:"AWS::IAM::Role",Properties:{RoleName:i,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"CommunicationPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish","sns:Subscribe"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchWriteItem","dynamodb:BatchGetItem"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"},{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetEndpoint","mobiletargeting:UpdateEndpoint"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["bedrock:InvokeModel"],Resource:"*"},{Effect:"Allow",Action:["es:ESHttpGet","es:ESHttpPost","es:ESHttpPut","es:ESHttpDelete"],Resource:"*"}]}}]}}},roleArn:N.GetAtt(s,"Arn"),roleName:i}}static generateEmailResources(a,n){let{slug:i,environment:s,email:c}=a;if(!c)return{};let l={},u=`${i}-${s}`,h=`${u}-email-storage`,y=t(h);l[y]={Type:"AWS::S3::Bucket",Properties:{BucketName:h,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:c.server?.storage?.archiveAfterDays?[{StorageClass:"GLACIER",TransitionInDays:c.server.storage.archiveAfterDays}]:[],ExpirationInDays:c.server?.storage?.retentionDays||365}]},NotificationConfiguration:{LambdaConfigurations:[]}}};let f=t(`${u}-ses-identity`);if(l[f]={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:c.domain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:!0}}},c.notifications?.bounces||c.notifications?.complaints){let S=t(`${u}-bounce-topic`);l[S]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-email-bounces`}};let b=t(`${u}-complaint-topic`);l[b]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-email-complaints`}}}if(c.server?.enabled){let S=t(`${u}-inbound-email`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:H.InboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:h,DOMAIN:c.domain}}}};let b=t(`${u}-outbound-email`);l[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-outbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.OutboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:h,DOMAIN:c.domain}}}}}if(c.advanced?.analytics){let S=t(`${u}-email-analytics`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.scheduling){let S=t(`${u}-email-scheduler`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:300,MemorySize:256,Code:{ZipFile:H.EmailSchedulerCode},Environment:{Variables:{EMAIL_BUCKET:h}}}};let b=t(`${u}-email-scheduler-rule`);l[b]={Type:"AWS::Events::Rule",Properties:{Name:`${u}-email-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:N.GetAtt(S,"Arn")}]}}}if(c.advanced?.threading){let S=t(`${u}-email-threading`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:H.EmailThreadingCode},Environment:{Variables:{EMAIL_BUCKET:h}}}}}if(c.advanced?.rules){let S=t(`${u}-email-rules`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}if(c.advanced?.sharedMailboxes){let S=t(`${u}-shared-mailboxes`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-shared-mailboxes`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"},{AttributeName:"type",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"type-index",KeySchema:[{AttributeName:"type",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}]}}}if(c.advanced?.search){let S=t(`${u}-email-search`);l[S]={Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:`${u}-email-search`.toLowerCase().replace(/[^a-z0-9-]/g,"-").substring(0,28),EngineVersion:"OpenSearch_2.11",ClusterConfig:{InstanceType:"t3.small.search",InstanceCount:1},EBSOptions:{EBSEnabled:!0,VolumeType:"gp3",VolumeSize:10},NodeToNodeEncryptionOptions:{Enabled:!0},EncryptionAtRestOptions:{Enabled:!0},DomainEndpointOptions:{EnforceHTTPS:!0}}}}return l}static generatePhoneResources(a,n){let{slug:i,environment:s,phone:c}=a;if(!c)return{};let l={},u=`${i}-${s}`,h=t(`${u}-call-log`);if(l[h]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.voicemail?.enabled){let S=t(`${u}-voicemail`);l[S]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${u}-voicemail`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}}}let y=t(`${u}-phone-notifications`);l[y]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-phone-notifications`}};let f=t(`${u}-incoming-call`);if(l[f]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.IncomingCallCode},Environment:{Variables:{CALL_LOG_TABLE:`${u}-call-log`,NOTIFICATION_TOPIC_ARN:N.Ref(y)}}}},c.voicemail?.enabled){let S=t(`${u}-voicemail-handler`);l[S]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-voicemail-handler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:c.voicemail.transcription?300:60,MemorySize:256,Code:{ZipFile:H.VoicemailCode},Environment:{Variables:{VOICEMAIL_BUCKET:`${u}-voicemail`,TRANSCRIPTION_ENABLED:String(c.voicemail.transcription||!1),NOTIFICATION_TOPIC_ARN:N.Ref(y)}}}}}if(c.advanced?.recording){let S=t(`${u}-call-recordings`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.callbacks){let S=t(`${u}-callbacks`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.analytics){let S=t(`${u}-call-metrics`);l[S]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}return l}static generateSmsResources(a,n){let{slug:i,environment:s,sms:c}=a;if(!c)return{};let l={},u=`${i}-${s}`,h=t(`${u}-pinpoint-app`);l[h]={Type:"AWS::Pinpoint::App",Properties:{Name:`${u}-sms`}};let y=t(`${u}-sms-channel`);l[y]={Type:"AWS::Pinpoint::SMSChannel",Properties:{ApplicationId:N.Ref(h),Enabled:!0,SenderId:c.senderId}};let f=t(`${u}-sms-log`);if(l[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.optOut?.enabled){let T=t(`${u}-sms-optout`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-optout`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}let S=t(`${u}-sms-notifications`);l[S]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-sms-notifications`}};let b=t(`${u}-send-sms`);l[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-send-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.SendSmsCode},Environment:{Variables:{PINPOINT_APP_ID:N.Ref(h),MESSAGE_LOG_TABLE:`${u}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${u}-sms-optout`:"",MESSAGE_TYPE:c.messageType||"TRANSACTIONAL"}}}};let C=t(`${u}-receive-sms`);if(l[C]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-receive-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:H.ReceiveSmsCode},Environment:{Variables:{MESSAGE_LOG_TABLE:`${u}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${u}-sms-optout`:"",NOTIFICATION_TOPIC_ARN:N.Ref(S)}}}},c.advanced?.campaigns){let T=t(`${u}-sms-campaigns`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-campaigns`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.analytics){let T=t(`${u}-sms-analytics`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-sms-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.linkTracking){let T=t(`${u}-short-links`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.chatbot){let T=t(`${u}-chatbot-sessions`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}};let v=t(`${u}-chatbot-rules`);l[v]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.abTesting){let T=t(`${u}-ab-tests`);l[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.mms){let T=t(`${u}-mms-media`);l[T]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${u}-mms-media`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldMedia",Status:"Enabled",ExpirationInDays:30}]}}}}return l}static InboundEmailCode=`
2371
2371
  const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
2372
2372
  const s3 = new S3Client({});
2373
2373
  exports.handler = async (event) => {
@@ -2465,7 +2465,7 @@ exports.handler = async (event) => {
2465
2465
  console.log('Receive SMS:', JSON.stringify(event, null, 2));
2466
2466
  // Process inbound SMS, handle opt-out keywords
2467
2467
  return { statusCode: 200 };
2468
- };`}var e={ref:(a)=>({Ref:a}),getAtt:(a,n)=>({"Fn::GetAtt":[a,n]}),join:(a,n)=>({"Fn::Join":[a,n]}),sub:(a,n)=>n?{"Fn::Sub":[a,n]}:{"Fn::Sub":a},select:(a,n)=>({"Fn::Select":[a,n]}),split:(a,n)=>({"Fn::Split":[a,n]}),getAZs:(a="")=>({"Fn::GetAZs":a}),importValue:(a)=>({"Fn::ImportValue":a}),findInMap:(a,n,i)=>({"Fn::FindInMap":[a,n,i]}),base64:(a)=>({"Fn::Base64":a}),cidr:(a,n,i)=>({"Fn::Cidr":[a,n,i]}),equals:(a,n)=>({"Fn::Equals":[a,n]}),if:(a,n,i)=>({"Fn::If":[a,n,i]}),not:(a)=>({"Fn::Not":[a]}),and:(...a)=>({"Fn::And":a}),or:(...a)=>({"Fn::Or":a})},Vs={s3Bucket:(a)=>e.sub(`arn:aws:s3:::${a}`),s3Object:(a,n="*")=>e.sub(`arn:aws:s3:::${a}/${n}`),lambda:(a,n,i)=>e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${a}`,n&&i?{"AWS::Region":n,"AWS::AccountId":i}:void 0),dynamodb:(a)=>e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${a}`),sqs:(a)=>e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${a}`),sns:(a)=>e.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${a}`),kinesis:(a)=>e.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${a}`),iam:(a,n)=>e.sub(`arn:aws:iam::\${AWS::AccountId}:${a}/${n}`),secretsManager:(a)=>e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${a}`),cloudwatch:(a)=>e.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${a}`)},xy={ACCOUNT_ID:{Ref:"AWS::AccountId"},NOTIFICATION_ARNS:{Ref:"AWS::NotificationARNs"},NO_VALUE:{Ref:"AWS::NoValue"},PARTITION:{Ref:"AWS::Partition"},REGION:{Ref:"AWS::Region"},STACK_ID:{Ref:"AWS::StackId"},STACK_NAME:{Ref:"AWS::StackName"},URL_SUFFIX:{Ref:"AWS::URLSuffix"}};function wr(a,n){if(n.type==="http")Er(a,n);else if(n.type==="rest")Pr(a,n);else if(n.type==="websocket")Ir(a,n)}function Er(a,n){let i={Name:e.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(n.cors)i.CorsConfiguration={AllowOrigins:n.cors.allowOrigins,AllowMethods:n.cors.allowMethods,AllowHeaders:n.cors.allowHeaders||["*"],MaxAge:n.cors.maxAge||300};if(a.addResource("HttpApi","AWS::ApiGatewayV2::Api",i),a.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:e.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),a.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:e.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),n.authorizer)Rr(a,"HttpApi",n.authorizer);if(n.customDomain)Bt(a,"HttpApi",n.customDomain,"HTTP");a.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:e.ref("HttpApi"),Export:{Name:e.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-http-api-endpoint")}}})}function Pr(a,n){a.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:e.sub("${AWS::StackName}-rest-api"),Description:e.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),a.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:e.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),a.addResource("ApiGatewayCloudWatchRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"apigateway.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"]}),a.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:e.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let i={RestApiId:e.ref("RestApi"),DeploymentId:e.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(n.throttling)i.MethodSettings[0].ThrottlingBurstLimit=n.throttling.burstLimit,i.MethodSettings[0].ThrottlingRateLimit=n.throttling.rateLimit;if(a.addResource("RestApiStage","AWS::ApiGateway::Stage",i,{dependsOn:["RestApi","RestApiDeployment"]}),n.customDomain)Bt(a,"RestApi",n.customDomain,"REST");a.addOutputs({RestApiId:{Description:"REST API ID",Value:e.ref("RestApi"),Export:{Name:e.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:e.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:e.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Ir(a,n){if(a.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:e.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),n.routes){if(n.routes.connect)st(a,"$connect",n.routes.connect.functionName);if(n.routes.disconnect)st(a,"$disconnect",n.routes.disconnect.functionName);if(n.routes.default)st(a,"$default",n.routes.default.functionName);if(n.routes.custom)n.routes.custom.forEach((i)=>{st(a,i.routeKey,i.functionName)})}if(a.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),n.customDomain)Bt(a,"WebSocketApi",n.customDomain,"WEBSOCKET");a.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:e.ref("WebSocketApi"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:e.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function st(a,n,i){let s=a.toLogicalId(`websocket-route-${n}`),c=a.toLogicalId(`websocket-integration-${n}`),l=a.toLogicalId(`${i}-function`);a.addResource(c,"AWS::ApiGatewayV2::Integration",{ApiId:e.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:e.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${l}.Arn}/invocations`)},{dependsOn:["WebSocketApi",l]}),a.addResource(s,"AWS::ApiGatewayV2::Route",{ApiId:e.ref("WebSocketApi"),RouteKey:n,Target:e.join("/",["integrations",e.ref(c)])},{dependsOn:["WebSocketApi",c]}),a.addResource(`${s}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(l),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[l,"WebSocketApi"]})}function Bt(a,n,i,s){let c={DomainName:i.domain};if(s==="REST")c.CertificateArn=i.certificateArn,c.EndpointConfiguration={Types:["REGIONAL"]},a.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",c),a.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:e.ref("ApiCustomDomain"),RestApiId:e.ref(n),Stage:e.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",n,"RestApiStage"]});else c.DomainNameConfigurations=[{CertificateArn:i.certificateArn,EndpointType:"REGIONAL"}],a.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",c),a.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:e.ref(n),DomainName:e.ref("ApiCustomDomain"),Stage:s==="HTTP"?e.ref("HttpApiStage"):e.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",n]});if(i.dnsProvider!=="external")a.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Dr(i.domain)}.`),Name:i.domain,Type:"A",AliasTarget:{HostedZoneId:e.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:e.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});a.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:i.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:e.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:e.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Rr(a,n,i){if(!i)return;if(i.type==="jwt")a.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(n),AuthorizerType:"JWT",IdentitySource:[i.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:i.issuer,Audience:i.audience},Name:"JWTAuthorizer"},{dependsOn:n});else if(i.type==="lambda")a.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(n),AuthorizerType:"REQUEST",AuthorizerUri:i.authorizerUri,IdentitySource:[i.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:n})}function Dr(a){let n=a.split(".");if(n.length>=2)return n.slice(-2).join(".");return a}function $r(a,n){if(n.redis)Lr(a,n.redis);if(n.memcached)Mr(a,n.memcached);if(n.elasticache)Or(a,n.elasticache)}function Lr(a,n){if(!n)return;if(a.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),a.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||6379,ToPort:n.port||6379,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),n.parameterGroup&&Object.keys(n.parameterGroup).length>0)a.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${n.engineVersion.split(".")[0]}`,Properties:n.parameterGroup});if(n.numCacheNodes>1||n.automaticFailoverEnabled)a.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheClusters:n.numCacheNodes,AutomaticFailoverEnabled:n.automaticFailoverEnabled||!1,MultiAZEnabled:n.automaticFailoverEnabled||!1,Port:n.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),a.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}});else a.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:1,Port:n.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),a.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}})}function Mr(a,n){if(!n)return;if(!a.hasResource("CacheSubnetGroup"))a.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!a.hasResource("CacheSecurityGroup"))a.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||11211,ToPort:n.port||11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});a.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,Port:n.port||11211,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),a.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-memcached-port")}}})}function Or(a,n){if(!n)return;let i=n.engine==="redis";if(!a.hasResource("CacheSubnetGroup"))a.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!a.hasResource("CacheSecurityGroup"))a.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i?6379:11211,ToPort:i?6379:11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});a.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub(`\${AWS::StackName}-${n.engine}`),Engine:n.engine,EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${n.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function Wr(a,n){if(!n.enabled)return;a.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:e.sub("${AWS::StackName} CloudFront OAI")}});let i=[],s=[];if(!n.origins||n.origins.length===0)i.push({Id:"S3Origin",DomainName:e.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else n.origins.forEach((u,h)=>{let y={Id:u.id,DomainName:u.domainName};if(u.originPath)y.OriginPath=u.originPath;if(u.domainName.includes("s3"))y.S3OriginConfig={OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else y.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(i.push(y),h>0||u.pathPattern)s.push({PathPattern:u.pathPattern||`/${u.id}/*`,TargetOriginId:u.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000})});let c={TargetOriginId:i[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000};if(n.edgeFunctions&&n.edgeFunctions.length>0)c.LambdaFunctionAssociations=n.edgeFunctions.map((u)=>({EventType:u.eventType,LambdaFunctionARN:u.functionArn}));let l={Enabled:!0,HttpVersion:n.http3?"http3":"http2",IPV6Enabled:!0,Origins:i,DefaultCacheBehavior:c,PriceClass:n.priceClass||"PriceClass_100",ViewerCertificate:{}};if(s.length>0)l.CacheBehaviors=s;if(n.customDomain)l.Aliases=[n.customDomain.domain],l.ViewerCertificate={AcmCertificateArn:n.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else l.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(n.errorPages)l.CustomErrorResponses=Object.entries(n.errorPages).map(([u,h])=>({ErrorCode:Number.parseInt(u),ResponseCode:200,ResponsePagePath:h,ErrorCachingMinTTL:300}));if(l.DefaultRootObject="index.html",l.Comment=e.sub("${AWS::StackName} CloudFront Distribution"),a.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:l},{dependsOn:"CloudFrontOriginAccessIdentity"}),!n.origins||n.origins.length===0)a.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:e.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:e.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:e.join("",[e.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(n.customDomain)a.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Gr(n.customDomain.domain)}.`),Name:n.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:e.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(a.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:e.ref("CloudFrontDistribution"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:e.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-domain")}}}),n.customDomain)a.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:e.sub(`https://${n.customDomain.domain}`)}})}function Gr(a){let n=a.split(".");if(n.length>=2)return n.slice(-2).join(".");return a}function Ur(a,n){if(n.server)Fr(a,n.server);if(n.fargate)oa(a,"app",n.fargate);if(n.services)n.services.forEach((i)=>{if(i.type==="fargate")oa(a,i.name,{taskDefinition:i.taskDefinition,service:i.service})})}function Fr(a,n){if(!n)return;a.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:e.ref("ALBSecurityGroup")},{IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),a.addResource("EC2InstanceRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-ec2-role")}]}),a.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[e.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let i=n.userData||`#!/bin/bash
2468
+ };`}var e={ref:(a)=>({Ref:a}),getAtt:(a,n)=>({"Fn::GetAtt":[a,n]}),join:(a,n)=>({"Fn::Join":[a,n]}),sub:(a,n)=>n?{"Fn::Sub":[a,n]}:{"Fn::Sub":a},select:(a,n)=>({"Fn::Select":[a,n]}),split:(a,n)=>({"Fn::Split":[a,n]}),getAZs:(a="")=>({"Fn::GetAZs":a}),importValue:(a)=>({"Fn::ImportValue":a}),findInMap:(a,n,i)=>({"Fn::FindInMap":[a,n,i]}),base64:(a)=>({"Fn::Base64":a}),cidr:(a,n,i)=>({"Fn::Cidr":[a,n,i]}),equals:(a,n)=>({"Fn::Equals":[a,n]}),if:(a,n,i)=>({"Fn::If":[a,n,i]}),not:(a)=>({"Fn::Not":[a]}),and:(...a)=>({"Fn::And":a}),or:(...a)=>({"Fn::Or":a})},Vs={s3Bucket:(a)=>e.sub(`arn:aws:s3:::${a}`),s3Object:(a,n="*")=>e.sub(`arn:aws:s3:::${a}/${n}`),lambda:(a,n,i)=>e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${a}`,n&&i?{"AWS::Region":n,"AWS::AccountId":i}:void 0),dynamodb:(a)=>e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${a}`),sqs:(a)=>e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${a}`),sns:(a)=>e.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${a}`),kinesis:(a)=>e.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${a}`),iam:(a,n)=>e.sub(`arn:aws:iam::\${AWS::AccountId}:${a}/${n}`),secretsManager:(a)=>e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${a}`),cloudwatch:(a)=>e.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${a}`)},xy={ACCOUNT_ID:{Ref:"AWS::AccountId"},NOTIFICATION_ARNS:{Ref:"AWS::NotificationARNs"},NO_VALUE:{Ref:"AWS::NoValue"},PARTITION:{Ref:"AWS::Partition"},REGION:{Ref:"AWS::Region"},STACK_ID:{Ref:"AWS::StackId"},STACK_NAME:{Ref:"AWS::StackName"},URL_SUFFIX:{Ref:"AWS::URLSuffix"}};function wr(a,n){if(n.type==="http")Er(a,n);else if(n.type==="rest")Pr(a,n);else if(n.type==="websocket")Ir(a,n)}function Er(a,n){let i={Name:e.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(n.cors)i.CorsConfiguration={AllowOrigins:n.cors.allowOrigins,AllowMethods:n.cors.allowMethods,AllowHeaders:n.cors.allowHeaders||["*"],MaxAge:n.cors.maxAge||300};if(a.addResource("HttpApi","AWS::ApiGatewayV2::Api",i),a.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:e.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),a.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:e.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),n.authorizer)Rr(a,"HttpApi",n.authorizer);if(n.customDomain)Bt(a,"HttpApi",n.customDomain,"HTTP");a.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:e.ref("HttpApi"),Export:{Name:e.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-http-api-endpoint")}}})}function Pr(a,n){a.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:e.sub("${AWS::StackName}-rest-api"),Description:e.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),a.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:e.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),a.addResource("ApiGatewayCloudWatchRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"apigateway.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"]}),a.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:e.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let i={RestApiId:e.ref("RestApi"),DeploymentId:e.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(n.throttling)i.MethodSettings[0].ThrottlingBurstLimit=n.throttling.burstLimit,i.MethodSettings[0].ThrottlingRateLimit=n.throttling.rateLimit;if(a.addResource("RestApiStage","AWS::ApiGateway::Stage",i,{dependsOn:["RestApi","RestApiDeployment"]}),n.customDomain)Bt(a,"RestApi",n.customDomain,"REST");a.addOutputs({RestApiId:{Description:"REST API ID",Value:e.ref("RestApi"),Export:{Name:e.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:e.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:e.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Ir(a,n){if(a.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:e.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),n.routes){if(n.routes.connect)it(a,"$connect",n.routes.connect.functionName);if(n.routes.disconnect)it(a,"$disconnect",n.routes.disconnect.functionName);if(n.routes.default)it(a,"$default",n.routes.default.functionName);if(n.routes.custom)n.routes.custom.forEach((i)=>{it(a,i.routeKey,i.functionName)})}if(a.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),n.customDomain)Bt(a,"WebSocketApi",n.customDomain,"WEBSOCKET");a.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:e.ref("WebSocketApi"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:e.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function it(a,n,i){let s=a.toLogicalId(`websocket-route-${n}`),c=a.toLogicalId(`websocket-integration-${n}`),l=a.toLogicalId(`${i}-function`);a.addResource(c,"AWS::ApiGatewayV2::Integration",{ApiId:e.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:e.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${l}.Arn}/invocations`)},{dependsOn:["WebSocketApi",l]}),a.addResource(s,"AWS::ApiGatewayV2::Route",{ApiId:e.ref("WebSocketApi"),RouteKey:n,Target:e.join("/",["integrations",e.ref(c)])},{dependsOn:["WebSocketApi",c]}),a.addResource(`${s}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(l),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[l,"WebSocketApi"]})}function Bt(a,n,i,s){let c={DomainName:i.domain};if(s==="REST")c.CertificateArn=i.certificateArn,c.EndpointConfiguration={Types:["REGIONAL"]},a.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",c),a.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:e.ref("ApiCustomDomain"),RestApiId:e.ref(n),Stage:e.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",n,"RestApiStage"]});else c.DomainNameConfigurations=[{CertificateArn:i.certificateArn,EndpointType:"REGIONAL"}],a.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",c),a.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:e.ref(n),DomainName:e.ref("ApiCustomDomain"),Stage:s==="HTTP"?e.ref("HttpApiStage"):e.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",n]});if(i.dnsProvider!=="external")a.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Dr(i.domain)}.`),Name:i.domain,Type:"A",AliasTarget:{HostedZoneId:e.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:e.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});a.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:i.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:e.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:e.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Rr(a,n,i){if(!i)return;if(i.type==="jwt")a.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(n),AuthorizerType:"JWT",IdentitySource:[i.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:i.issuer,Audience:i.audience},Name:"JWTAuthorizer"},{dependsOn:n});else if(i.type==="lambda")a.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(n),AuthorizerType:"REQUEST",AuthorizerUri:i.authorizerUri,IdentitySource:[i.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:n})}function Dr(a){let n=a.split(".");if(n.length>=2)return n.slice(-2).join(".");return a}function $r(a,n){if(n.redis)Lr(a,n.redis);if(n.memcached)Mr(a,n.memcached);if(n.elasticache)Or(a,n.elasticache)}function Lr(a,n){if(!n)return;if(a.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),a.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||6379,ToPort:n.port||6379,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),n.parameterGroup&&Object.keys(n.parameterGroup).length>0)a.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${n.engineVersion.split(".")[0]}`,Properties:n.parameterGroup});if(n.numCacheNodes>1||n.automaticFailoverEnabled)a.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheClusters:n.numCacheNodes,AutomaticFailoverEnabled:n.automaticFailoverEnabled||!1,MultiAZEnabled:n.automaticFailoverEnabled||!1,Port:n.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),a.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}});else a.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:1,Port:n.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),a.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}})}function Mr(a,n){if(!n)return;if(!a.hasResource("CacheSubnetGroup"))a.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!a.hasResource("CacheSecurityGroup"))a.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||11211,ToPort:n.port||11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});a.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,Port:n.port||11211,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),a.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-memcached-port")}}})}function Or(a,n){if(!n)return;let i=n.engine==="redis";if(!a.hasResource("CacheSubnetGroup"))a.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!a.hasResource("CacheSecurityGroup"))a.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i?6379:11211,ToPort:i?6379:11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});a.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub(`\${AWS::StackName}-${n.engine}`),Engine:n.engine,EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${n.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function Wr(a,n){if(!n.enabled)return;a.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:e.sub("${AWS::StackName} CloudFront OAI")}});let i=[],s=[];if(!n.origins||n.origins.length===0)i.push({Id:"S3Origin",DomainName:e.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else n.origins.forEach((u,h)=>{let y={Id:u.id,DomainName:u.domainName};if(u.originPath)y.OriginPath=u.originPath;if(u.domainName.includes("s3"))y.S3OriginConfig={OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else y.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(i.push(y),h>0||u.pathPattern)s.push({PathPattern:u.pathPattern||`/${u.id}/*`,TargetOriginId:u.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000})});let c={TargetOriginId:i[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000};if(n.edgeFunctions&&n.edgeFunctions.length>0)c.LambdaFunctionAssociations=n.edgeFunctions.map((u)=>({EventType:u.eventType,LambdaFunctionARN:u.functionArn}));let l={Enabled:!0,HttpVersion:n.http3?"http3":"http2",IPV6Enabled:!0,Origins:i,DefaultCacheBehavior:c,PriceClass:n.priceClass||"PriceClass_100",ViewerCertificate:{}};if(s.length>0)l.CacheBehaviors=s;if(n.customDomain)l.Aliases=[n.customDomain.domain],l.ViewerCertificate={AcmCertificateArn:n.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else l.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(n.errorPages)l.CustomErrorResponses=Object.entries(n.errorPages).map(([u,h])=>({ErrorCode:Number.parseInt(u),ResponseCode:200,ResponsePagePath:h,ErrorCachingMinTTL:300}));if(l.DefaultRootObject="index.html",l.Comment=e.sub("${AWS::StackName} CloudFront Distribution"),a.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:l},{dependsOn:"CloudFrontOriginAccessIdentity"}),!n.origins||n.origins.length===0)a.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:e.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:e.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:e.join("",[e.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(n.customDomain)a.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Gr(n.customDomain.domain)}.`),Name:n.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:e.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(a.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:e.ref("CloudFrontDistribution"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:e.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-domain")}}}),n.customDomain)a.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:e.sub(`https://${n.customDomain.domain}`)}})}function Gr(a){let n=a.split(".");if(n.length>=2)return n.slice(-2).join(".");return a}function Ur(a,n){if(n.server)Fr(a,n.server);if(n.fargate)oa(a,"app",n.fargate);if(n.services)n.services.forEach((i)=>{if(i.type==="fargate")oa(a,i.name,{taskDefinition:i.taskDefinition,service:i.service})})}function Fr(a,n){if(!n)return;a.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:e.ref("ALBSecurityGroup")},{IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),a.addResource("EC2InstanceRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-ec2-role")}]}),a.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[e.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let i=n.userData||`#!/bin/bash
2469
2469
  set -e
2470
2470
  # Update system
2471
2471
  yum update -y || apt-get update -y
@@ -2492,22 +2492,22 @@ rpm -U ./amazon-cloudwatch-agent.rpm || true
2492
2492
  # Mount EFS for shared file storage
2493
2493
  `}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[s||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${i}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:s?{domain:s,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:h==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:y==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${i}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${i}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${i}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${i}-app`,`${i}-nginx`,`${i}-workers`]}},security:{certificate:s?{domain:s,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:h==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...y==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function zy(a){let{name:n,slug:i,domain:s,repository:c,phpVersion:l="8.3",size:u="small",database:h=i.replace(/-/g,"_"),databasePassword:y,sslEmail:f,deployStrategy:S="push",provider:b="hetzner"}=a;return{project:{name:n,slug:i,region:"us-east-1"},mode:"server",cloud:{provider:b},environments:{production:{type:"production",domain:s}},infrastructure:{compute:{mode:"server",size:u,runtime:"php",webServer:"nginx",php:{versions:[l],default:l},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:h,username:h,password:y}},sites:{main:{root:".",type:"laravel",domain:s,phpVersion:l,repository:{...c,strategy:S},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:f}}}}}function Ky(a){let{name:n,slug:i,domain:s,layers:c,phpVersion:l="8.3",architecture:u="x86_64",memory:h=1024,build:y,deploy:f=["migrate --force"],cache:S="dynamodb",scheduler:b="on",region:C="us-east-1"}=a;return{project:{name:n,slug:i,region:C},mode:"serverless",environments:{production:{type:"production",domain:s,app:{kind:"php",runtime:"provided.al2023",phpVersion:l,architecture:u,layers:c,memory:h,build:y,deploy:f,assets:"public",queues:!0,scheduler:b,cache:{driver:S},domain:s}}}}}function Wy(a){return{root:a.root??"packages/ui/dist",deploy:"server",type:"static",domain:a.domain,build:a.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:a.username??"admin",password:a.password}}}var lf=bp,uf="./node_modules/@stacksjs/ts-cloud/dist/bin/dashboard-server.js";function gn(a){let n=a.split(".").filter(Boolean);return n.length<=2?a:n.slice(-2).join(".")}function hn(a){let n=2166136261;for(let i=0;i<a.length;i++)n^=a.charCodeAt(i),n=Math.imul(n,16777619);return n>>>0}var pf=20000,gf=12000;function mf(a){return pf+hn(a)%gf}function Ea(a,n){let i=gn(a);if(i===a)return`dashboard.${i}`;for(let s of n)if(s===i)return`dashboard.${i}`;return`dashboard.${a}`}function Pa(a,n){let i=[],s=a.infrastructure?.dns?.domain;if(s&&!a.cloud?.attachTo)i.push(s);if(n&&a.environments?.[n]?.domain)i.push(a.environments[n].domain);for(let c of Object.values(a.sites??{})){let l=c;if(!l||l.redirect)continue;let u=l.domain;if(typeof u==="string")i.push(u);else if(Array.isArray(u))i.push(...u.filter((h)=>typeof h==="string"))}return i.filter((c)=>c&&!c.startsWith("dashboard."))}function hf(a,n,i){if(i)return i;let s=Pa(a,n),c=s[0];if(!c)return null;return Ea(c,s)}function ff(a,n,i){if(i)return[i];let s=Pa(a,n),c=[];for(let l of s){let u=Ea(l,s);if(!c.includes(u))c.push(u)}return c}function Qt(a){return Object.entries(a.sites??{}).some(([n,i])=>{if(!i)return!1;let s=i.root??"";return Nr(n)||s==="ui/dist"||s.endsWith("/ui/dist")||s.endsWith("/dist/ui")})}var wp="dashboard-";function Rp(a){return wp+a.replace(/^dashboard\./,"").replace(/\./g,"-")}function Nr(a){return a==="dashboard"||a.startsWith(wp)}function gi(a,n,i){if(Qt(a))return[];if(a.cloud?.attachTo)return[];let s=i.password?{auth:{username:i.username||"admin",password:i.password,realm:i.realm}}:{},c=i.build===!1||i.build===void 0?{}:{build:i.build};if(i.live!==!1){let l=hf(a,n,i.domain);if(!l)return[];let u=i.port??mf(l),h=a.infrastructure?.appDatabase??a.infrastructure?.compute?.database,y={root:i.uiRoot,deploy:"server",domain:l,preStart:["bun install --production --no-save"],start:`bun ${uf} --box --host 127.0.0.1 --port ${u}`,port:u,cpuWeight:10,ioWeight:10,tasksMax:128,env:{APP_ENV:"production",NODE_ENV:"production",TS_CLOUD_DASHBOARD_TELEMETRY:"1",...h?.password?{TS_CLOUD_DASHBOARD_DB_PASSWORD:h.password}:{}},zeroDowntime:!1,sharedPaths:[lf],healthCheck:{path:"/login"},ssl:{provider:"letsencrypt"}};return[{name:Rp(l),site:y}]}return ff(a,n,i.domain).map((l)=>({name:Rp(l),site:{root:i.uiRoot,deploy:"server",type:"static",domain:l,ssl:{provider:"letsencrypt"},...c,...s}}))}function Jy(a,n,i){return gi(a,n,i)[0]??null}function _t(a,n){let i={...a};for(let s in n){let c=n[s],l=i[s];if(c===void 0)continue;if(Array.isArray(c)&&Array.isArray(l))i[s]=[...l,...c];else if(typeof c==="object"&&c!==null&&!Array.isArray(c)&&typeof l==="object"&&l!==null&&!Array.isArray(l))i[s]=_t(l,c);else i[s]=c}return i}function Dp(a,n){return _t(a,n)}function Xy(...a){return a.reduce((n,i)=>_t(n,i),{})}function Yy(a,n){return(i)=>{let s=a(i);if(typeof n==="function")return Dp(s,n(s,i));return Dp(s,n)}}function kr(a){return{infrastructure:a}}function Zy(a){return kr({monitoring:a})}function eI(a){return kr({security:a})}function tI(a){return kr({databases:a})}function rI(a){return kr({cache:a})}function nI(a){return kr({cdn:a})}function iI(a){return kr({queues:a})}et();function Af(){let a=process.env.AWS_ACCESS_KEY_ID,n=process.env.AWS_SECRET_ACCESS_KEY;if(!a||!n)return null;return{accessKeyId:a,secretAccessKey:n,sessionToken:process.env.AWS_SESSION_TOKEN}}function yf(a){let n=a?.profile||process.env.AWS_PROFILE||"default",i=a?.credentialsFile||Na(Ra(),".aws","credentials");if(!Ia(i))return null;try{let s=Wt(i,"utf-8");return yn(s,n)}catch{return null}}function yn(a,n){let i=a.split(`
2494
2494
  `),s=null,c,l,u;for(let h of i){let y=h.trim();if(!y||y.startsWith("#")||y.startsWith(";"))continue;let f=y.match(/^\[([^\]]+)\]$/);if(f){if(s===n&&c&&l)return{accessKeyId:c,secretAccessKey:l,sessionToken:u};s=f[1],c=void 0,l=void 0,u=void 0;continue}if(s===n){let[S,...b]=y.split("="),C=b.join("=").trim();switch(S.trim().toLowerCase()){case"aws_access_key_id":c=C;break;case"aws_secret_access_key":l=C;break;case"aws_session_token":u=C;break}}}if(s===n&&c&&l)return{accessKeyId:c,secretAccessKey:l,sessionToken:u};return null}async function If(a){let n=a?.timeout??1000,i="http://169.254.169.254";try{let s=await Ye("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},n);if(!s.ok)return null;let c=await s.text(),l=await Ye("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":c}},n);if(!l.ok)return null;let u=(await l.text()).trim(),h=await Ye(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${u}`,{headers:{"X-aws-ec2-metadata-token":c}},n);if(!h.ok)return null;let y=await h.json();return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,sessionToken:y.Token,expiration:new Date(y.Expiration)}}catch{return null}}async function Sf(a){let n=a?.timeout??1000,i=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,s=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,c=null;if(i)c=`http://169.254.170.2${i}`;else if(s)c=s;if(!c)return null;try{let l={},u=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(u)l.Authorization=u;let h=await Ye(c,{headers:l},n);if(!h.ok)return null;let y=await h.json();return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,sessionToken:y.Token,expiration:new Date(y.Expiration)}}catch{return null}}async function Cf(a){let n=a?.timeout??5000,i=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,s=process.env.AWS_ROLE_ARN,c=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!i||!s)return null;try{let l=Wt(i,"utf-8").trim(),u=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",h=u.startsWith("us-gov")?`https://sts.${u}.amazonaws.com`:u==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${u}.amazonaws.com`,y=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:s,RoleSessionName:c,WebIdentityToken:l}),f=await Ye(`${h}/?${y.toString()}`,{method:"POST"},n);if(!f.ok)return null;let S=await f.text(),b=ze(S,"AccessKeyId"),C=ze(S,"SecretAccessKey"),T=ze(S,"SessionToken"),v=ze(S,"Expiration");if(!b||!C)return null;return{accessKeyId:b,secretAccessKey:C,sessionToken:T??void 0,expiration:v?new Date(v):void 0}}catch{return null}}async function js(a){let n=Af();if(n)return n;let i=yf(a);if(i)return i;let s=await Cf(a);if(s)return s;let c=await Sf(a);if(c)return c;let l=await If(a);if(l)return l;throw Error("Could not find AWS credentials. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials, or run on an EC2 instance with an IAM role.")}function sI(a){let n=null,i=null;return async()=>{if(n){if(!n.expiration)return n;let s=300000;if(n.expiration.getTime()-Date.now()>s)return n}if(i)return i;return i=js(a).then((s)=>(n=s,i=null,s)).catch((s)=>{throw i=null,s}),i}}async function Ye(a,n,i){let s=new AbortController,c=setTimeout(()=>s.abort(),i);try{let l=await fetch(a,{...n,signal:s.signal});return clearTimeout(c),l}catch(l){throw clearTimeout(c),l}}function ze(a,n){let i=new RegExp(`<${n}>([^<]+)</${n}>`),s=a.match(i);return s?s[1]:null}async function bf(a){return js({profile:a})}function Ef(a){let n=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(n)return n;let i=Na(Ra(),".aws","config");if(Ia(i))try{let s=Wt(i,"utf-8"),c=a||process.env.AWS_PROFILE||"default",l=c==="default"?"[default]":`[profile ${c}]`,u=s.split(`
2495
- `),h=!1;for(let y of u){let f=y.trim();if(f.startsWith("[")){h=f===l;continue}if(h&&f.startsWith("region")){let[,S]=f.split("=");if(S)return S.trim()}}}catch{}return"us-east-1"}async function vf(a){let n=a||await js(),i=Ef();await et();let s=i.startsWith("us-gov")?`https://sts.${i}.amazonaws.com`:i==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${i}.amazonaws.com`,c="Action=GetCallerIdentity&Version=2011-06-15",l=x({method:"POST",url:s,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...n,service:"sts",region:i}),u=await fetch(l.url,{method:l.method,headers:l.headers,body:l.body});if(!u.ok)throw Error(`Failed to get account ID: ${await u.text()}`);let h=await u.text(),y=ze(h,"Account");if(!y)throw Error("Failed to parse account ID from response");return y}await et();await et();var fn=5242880,Pt=5242880,Sn=5242880;class Da{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(a={}){this.region=a.region||process.env.AWS_REGION||"us-east-1",this.endpoint=a.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=a.forcePathStyle||!1,this.credentials=a.credentials,this.credentialOptions=a.credentialOptions,this.retryOptions=a.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return js(this.credentialOptions)}buildUrl(a,n){let i=n?encodeURIComponent(n).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return n?`${this.endpoint}/${a}/${i}`:`${this.endpoint}/${a}`;let s=new URL(this.endpoint);return s.hostname=`${a}.${s.hostname}`,n?`${s.origin}/${i}`:s.origin}async get(a,n,i={}){let s=await this.getCredentials(),c=this.buildUrl(a,n),l={};if(i.range)l.Range=i.range;if(i.ifModifiedSince)l["If-Modified-Since"]=i.ifModifiedSince.toUTCString();if(i.ifMatch)l["If-Match"]=i.ifMatch;if(i.ifNoneMatch)l["If-None-Match"]=i.ifNoneMatch;let u=new URL(c);if(i.responseContentType)u.searchParams.set("response-content-type",i.responseContentType);if(i.responseContentDisposition)u.searchParams.set("response-content-disposition",i.responseContentDisposition);let h=x({method:"GET",url:u.toString(),headers:l,...s,service:"s3",region:this.region}),y=await fetch(h.url,{method:h.method,headers:h.headers});if(!y.ok&&y.status!==304){let f=await y.text();throw new G(`Failed to get object: ${f}`,y.status,a,n)}return y}async getText(a,n,i={}){return(await this.get(a,n,i)).text()}async getJSON(a,n,i={}){return(await this.get(a,n,i)).json()}async getBuffer(a,n,i={}){return(await this.get(a,n,i)).arrayBuffer()}async put(a,n,i,s={}){let c,l;if(typeof i==="string")c=new TextEncoder().encode(i).length,l=i;else if(i instanceof ArrayBuffer)c=i.byteLength,l=i;else if(i instanceof Uint8Array)c=i.byteLength,l=i;else if(i instanceof Blob)c=i.size,l=i;else return this.uploadMultipart(a,n,i,{...s,partSize:Pt});if(c>Sn){let u=Cn(l).stream();return this.uploadMultipart(a,n,u,{...s,partSize:Pt})}return this.putSimple(a,n,l,c,s)}async putSimple(a,n,i,s,c){let l=await this.getCredentials(),u=this.buildUrl(a,n),h={"Content-Length":String(s),"Content-Type":c.contentType||la(n)};if(c.contentEncoding)h["Content-Encoding"]=c.contentEncoding;if(c.cacheControl)h["Cache-Control"]=c.cacheControl;if(c.contentDisposition)h["Content-Disposition"]=c.contentDisposition;if(c.storageClass)h["x-amz-storage-class"]=c.storageClass;if(c.serverSideEncryption)h["x-amz-server-side-encryption"]=c.serverSideEncryption;if(c.acl)h["x-amz-acl"]=c.acl;if(c.tagging)h["x-amz-tagging"]=c.tagging;if(c.metadata)for(let[b,C]of Object.entries(c.metadata))h[`x-amz-meta-${b.toLowerCase()}`]=C;let y;if(typeof i==="string")y=i;else if(i instanceof Blob)y=await i.text();else y=new TextDecoder().decode(i instanceof ArrayBuffer?new Uint8Array(i):i);let f=x({method:"PUT",url:u,headers:h,body:y,...l,service:"s3",region:this.region}),S=await fetch(f.url,{method:f.method,headers:f.headers,body:i});if(!S.ok){let b=await S.text();throw new G(`Failed to put object: ${b}`,S.status,a,n)}return{etag:(S.headers.get("ETag")||"").replace(/"/g,"")}}async delete(a,n){let i=await this.getCredentials(),s=this.buildUrl(a,n),c=x({method:"DELETE",url:s,...i,service:"s3",region:this.region}),l=await fetch(c.url,{method:c.method,headers:c.headers});if(!l.ok&&l.status!==204){let u=await l.text();throw new G(`Failed to delete object: ${u}`,l.status,a,n)}}async deleteMany(a,n){let i=await this.getCredentials(),s=`${this.buildUrl(a)}?delete`,c=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${n.map((T)=>`<Object><Key>${An(T)}</Key></Object>`).join("")}</Delete>`,l=x({method:"POST",url:s,headers:{"Content-Type":"application/xml"},body:c,...i,service:"s3",region:this.region}),u=await fetch(l.url,{method:l.method,headers:l.headers,body:c});if(!u.ok){let T=await u.text();throw new G(`Failed to delete objects: ${T}`,u.status,a)}let h=await u.text(),y=[],f=[],S=/<Deleted><Key>([^<]+)<\/Key>/g,b;while((b=S.exec(h))!==null)y.push(b[1]);let C=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((b=C.exec(h))!==null)f.push({key:b[1],error:`${b[2]}: ${b[3]}`});return{deleted:y,errors:f}}async list(a,n={}){let i=await this.getCredentials(),s=new URL(this.buildUrl(a));if(s.searchParams.set("list-type","2"),n.prefix)s.searchParams.set("prefix",n.prefix);if(n.delimiter)s.searchParams.set("delimiter",n.delimiter);if(n.maxKeys)s.searchParams.set("max-keys",String(n.maxKeys));if(n.continuationToken)s.searchParams.set("continuation-token",n.continuationToken);if(n.startAfter)s.searchParams.set("start-after",n.startAfter);let c=x({method:"GET",url:s.toString(),...i,service:"s3",region:this.region}),l=await fetch(c.url,{method:c.method,headers:c.headers});if(!l.ok){let h=await l.text();throw new G(`Failed to list objects: ${h}`,l.status,a)}let u=await l.text();return bn(u)}async*listAll(a,n={}){let i;do{let s=await this.list(a,{...n,continuationToken:i});for(let c of s.contents)yield c;i=s.nextContinuationToken}while(i)}async head(a,n){let i=await this.getCredentials(),s=this.buildUrl(a,n),c=x({method:"HEAD",url:s,...i,service:"s3",region:this.region}),l=await fetch(c.url,{method:c.method,headers:c.headers});if(l.status===404)return null;if(!l.ok){let h=await l.text();throw new G(`Failed to head object: ${h}`,l.status,a,n)}let u={};return l.headers.forEach((h,y)=>{if(y.toLowerCase().startsWith("x-amz-meta-"))u[y.slice(11)]=h}),{contentLength:Number(l.headers.get("Content-Length")||0),contentType:l.headers.get("Content-Type")||"application/octet-stream",etag:(l.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(l.headers.get("Last-Modified")||0),metadata:u,storageClass:l.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:l.headers.get("x-amz-server-side-encryption")||void 0}}async exists(a,n){return await this.head(a,n)!==null}async copy(a,n,i,s,c={}){let l=await this.getCredentials(),u=this.buildUrl(i,s),h={"x-amz-copy-source":`/${a}/${encodeURIComponent(n)}`};if(c.metadataDirective)h["x-amz-metadata-directive"]=c.metadataDirective;if(c.contentType)h["Content-Type"]=c.contentType;if(c.storageClass)h["x-amz-storage-class"]=c.storageClass;if(c.acl)h["x-amz-acl"]=c.acl;if(c.metadata)for(let[b,C]of Object.entries(c.metadata))h[`x-amz-meta-${b.toLowerCase()}`]=C;let y=x({method:"PUT",url:u,headers:h,...l,service:"s3",region:this.region}),f=await fetch(y.url,{method:y.method,headers:y.headers});if(!f.ok){let b=await f.text();throw new G(`Failed to copy object: ${b}`,f.status,i,s)}let S=(await f.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:S?S[1]:""}}async getPresignedUrl(a,n,i={}){let s=await this.getCredentials(),c=this.buildUrl(a,n);return rf({url:c,method:i.method||"GET",expiresIn:i.expiresIn||3600,...s,service:"s3",region:this.region})}async uploadMultipart(a,n,i,s={}){let c=await this.getCredentials(),l=Math.max(s.partSize||Pt,fn),u,h;if(i instanceof ReadableStream)u=i;else if(i instanceof Blob)u=i.stream(),h=i.size;else{let S=new Blob([i]);u=S.stream(),h=S.size}let{uploadId:y,baseUrl:f}=await this.initiateMultipartUpload(a,n,s);try{let S=await this.uploadParts(a,n,f,y,u,l,c,h,s.concurrency||4,s.onProgress);return await this.completeMultipartUpload(a,n,f,y,S)}catch(S){throw await this.abortMultipartUpload(a,n,y,f).catch(()=>{}),S}}async initiateMultipartUpload(a,n,i){let s=await this.getCredentials(),c=this.buildUrl(a,n),l=`${c}?uploads`,u={"Content-Type":i.contentType||la(n)};if(i.storageClass)u["x-amz-storage-class"]=i.storageClass;if(i.serverSideEncryption)u["x-amz-server-side-encryption"]=i.serverSideEncryption;if(i.acl)u["x-amz-acl"]=i.acl;if(i.metadata)for(let[b,C]of Object.entries(i.metadata))u[`x-amz-meta-${b.toLowerCase()}`]=C;let h=x({method:"POST",url:l,headers:u,...s,service:"s3",region:this.region}),y=await fetch(h.url,{method:h.method,headers:h.headers});if(!y.ok){let b=await y.text();throw new G(`Failed to initiate multipart upload: ${b}`,y.status,a,n)}let f=(await y.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!f)throw new G("Failed to parse upload ID from response",0,a,n);let S=c;if(y.url)try{let b=new URL(y.url);b.search="",S=b.toString()}catch{}return{uploadId:f[1],baseUrl:S}}async uploadParts(a,n,i,s,c,l,u,h,y,f){let S=[],b=c.getReader(),C=1,T=new Uint8Array(0),v=0,w=h?Math.ceil(h/l):void 0,R=new Map,k=async(P,V)=>{let B=`${i}?partNumber=${V}&uploadId=${encodeURIComponent(s)}`,j={"Content-Length":String(P.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},Z=x({method:"PUT",url:B,headers:j,...u,service:"s3",region:this.region}),K=await fetch(Z.url,{method:Z.method,headers:Z.headers,body:P,redirect:"error"});if(!K.ok){let te=await K.text();throw new G(`Failed to upload part ${V}: ${te}`,K.status,a,n)}let ee=(K.headers.get("ETag")||"").replace(/"/g,"");if(!ee)throw new G(`Missing ETag for part ${V}`,K.status,a,n);return{partNumber:V,etag:ee}},W=async()=>{let P=await Promise.race(R.values());R.delete(P.partNumber),S.push(P)};while(!0){let{done:P,value:V}=await b.read();if(V){let B=new Uint8Array(T.length+V.length);B.set(T),B.set(V,T.length),T=B}while(T.length>=l||P&&T.length>0){let B=T.slice(0,l);T=T.slice(l);let j=C++;if(R.size>=y)await W();if(R.set(j,k(B,j)),v+=B.byteLength,f)f({loaded:v,total:h||v,part:j,totalParts:w||j})}if(P)break}while(R.size>0)await W();return S.sort((P,V)=>P.partNumber-V.partNumber),S}async completeMultipartUpload(a,n,i,s,c){let l=await this.getCredentials(),u=`${i}?uploadId=${encodeURIComponent(s)}`,h=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${c.map((b)=>`<Part><PartNumber>${b.partNumber}</PartNumber><ETag>"${b.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,y=x({method:"POST",url:u,headers:{"Content-Type":"application/xml"},body:h,...l,service:"s3",region:this.region}),f=await fetch(y.url,{method:y.method,headers:y.headers,body:h});if(!f.ok){let b=await f.text();throw new G(`Failed to complete multipart upload: ${b}`,f.status,a,n)}let S=(await f.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:S?S[1]:""}}async abortMultipartUpload(a,n,i,s){let c=await this.getCredentials(),l=`${s??this.buildUrl(a,n)}?uploadId=${encodeURIComponent(i)}`,u=x({method:"DELETE",url:l,...c,service:"s3",region:this.region});await fetch(u.url,{method:u.method,headers:u.headers})}async emptyAndDeleteBucket(a){let n=[];for await(let l of this.listAll(a,{}))if(n.push(l.key),n.length>=1000)await this.deleteMany(a,n),n=[];if(n.length>0)await this.deleteMany(a,n);let i=await this.getCredentials(),s=this.buildUrl(a),c=x({method:"DELETE",url:s,...i,service:"s3",region:this.region});await fetch(c.url,{method:c.method,headers:c.headers})}}class G extends Error{statusCode;bucket;key;constructor(a,n,i,s){super(a);this.statusCode=n,this.bucket=i,this.key=s,this.name="S3Error"}}function bn(a){let n=[],i=[],s=/<Contents>([\s\S]*?)<\/Contents>/g,c;while((c=s.exec(a))!==null){let u=c[1];n.push({key:le(u,"Key")||"",lastModified:new Date(le(u,"LastModified")||0),etag:(le(u,"ETag")||"").replace(/"/g,""),size:Number(le(u,"Size")||0),storageClass:le(u,"StorageClass")||"STANDARD"})}let l=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((c=l.exec(a))!==null)i.push(c[1]);return{contents:n,commonPrefixes:i,isTruncated:le(a,"IsTruncated")==="true",continuationToken:le(a,"ContinuationToken")||void 0,nextContinuationToken:le(a,"NextContinuationToken")||void 0,keyCount:Number(le(a,"KeyCount")||0),maxKeys:Number(le(a,"MaxKeys")||1000),prefix:le(a,"Prefix")||void 0,delimiter:le(a,"Delimiter")||void 0}}function le(a,n){let i=new RegExp(`<${n}>([^<]*)</${n}>`),s=a.match(i);return s?s[1]:null}function An(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function la(a){let n=a.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[n||""]||"application/octet-stream"}function Cn(a){if(a instanceof Blob)return a;if(typeof a==="string")return new Blob([a],{type:"text/plain"});return new Blob([a])}function oI(a){return new Da(a)}await et();class Qe extends Error{code;solution;details;constructor(a,n,i,s){super(a);this.code=n,this.solution=i,this.details=s,this.name="CloudError",Error.captureStackTrace?.(this,Qe)}toString(){let a=`${this.name} [${this.code}]: ${this.message}`;if(this.solution)a+=`
2495
+ `),h=!1;for(let y of u){let f=y.trim();if(f.startsWith("[")){h=f===l;continue}if(h&&f.startsWith("region")){let[,S]=f.split("=");if(S)return S.trim()}}}catch{}return"us-east-1"}async function vf(a){let n=a||await js(),i=Ef();await et();let s=i.startsWith("us-gov")?`https://sts.${i}.amazonaws.com`:i==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${i}.amazonaws.com`,c="Action=GetCallerIdentity&Version=2011-06-15",l=x({method:"POST",url:s,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...n,service:"sts",region:i}),u=await fetch(l.url,{method:l.method,headers:l.headers,body:l.body});if(!u.ok)throw Error(`Failed to get account ID: ${await u.text()}`);let h=await u.text(),y=ze(h,"Account");if(!y)throw Error("Failed to parse account ID from response");return y}await et();await et();var fn=5242880,Pt=5242880,Sn=5242880;class Da{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(a={}){this.region=a.region||process.env.AWS_REGION||"us-east-1",this.endpoint=a.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=a.forcePathStyle||!1,this.credentials=a.credentials,this.credentialOptions=a.credentialOptions,this.retryOptions=a.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return js(this.credentialOptions)}buildUrl(a,n){let i=n?encodeURIComponent(n).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return n?`${this.endpoint}/${a}/${i}`:`${this.endpoint}/${a}`;let s=new URL(this.endpoint);return s.hostname=`${a}.${s.hostname}`,n?`${s.origin}/${i}`:s.origin}async get(a,n,i={}){let s=await this.getCredentials(),c=this.buildUrl(a,n),l={};if(i.range)l.Range=i.range;if(i.ifModifiedSince)l["If-Modified-Since"]=i.ifModifiedSince.toUTCString();if(i.ifMatch)l["If-Match"]=i.ifMatch;if(i.ifNoneMatch)l["If-None-Match"]=i.ifNoneMatch;let u=new URL(c);if(i.responseContentType)u.searchParams.set("response-content-type",i.responseContentType);if(i.responseContentDisposition)u.searchParams.set("response-content-disposition",i.responseContentDisposition);let h=x({method:"GET",url:u.toString(),headers:l,...s,service:"s3",region:this.region}),y=await fetch(h.url,{method:h.method,headers:h.headers});if(!y.ok&&y.status!==304){let f=await y.text();throw new G(`Failed to get object: ${f}`,y.status,a,n)}return y}async getText(a,n,i={}){return(await this.get(a,n,i)).text()}async getJSON(a,n,i={}){return(await this.get(a,n,i)).json()}async getBuffer(a,n,i={}){return(await this.get(a,n,i)).arrayBuffer()}async put(a,n,i,s={}){let c,l;if(typeof i==="string")c=new TextEncoder().encode(i).length,l=i;else if(i instanceof ArrayBuffer)c=i.byteLength,l=i;else if(i instanceof Uint8Array)c=i.byteLength,l=i;else if(i instanceof Blob)c=i.size,l=i;else return this.uploadMultipart(a,n,i,{...s,partSize:Pt});if(c>Sn){let u=Cn(l).stream();return this.uploadMultipart(a,n,u,{...s,partSize:Pt})}return this.putSimple(a,n,l,c,s)}async putSimple(a,n,i,s,c){let l=await this.getCredentials(),u=this.buildUrl(a,n),h={"Content-Length":String(s),"Content-Type":c.contentType||la(n)};if(c.contentEncoding)h["Content-Encoding"]=c.contentEncoding;if(c.cacheControl)h["Cache-Control"]=c.cacheControl;if(c.contentDisposition)h["Content-Disposition"]=c.contentDisposition;if(c.storageClass)h["x-amz-storage-class"]=c.storageClass;if(c.serverSideEncryption)h["x-amz-server-side-encryption"]=c.serverSideEncryption;if(c.acl)h["x-amz-acl"]=c.acl;if(c.tagging)h["x-amz-tagging"]=c.tagging;if(c.metadata)for(let[b,C]of Object.entries(c.metadata))h[`x-amz-meta-${b.toLowerCase()}`]=C;let y;if(typeof i==="string")y=i;else if(i instanceof Blob)y=await i.text();else y=new TextDecoder().decode(i instanceof ArrayBuffer?new Uint8Array(i):i);let f=x({method:"PUT",url:u,headers:h,body:y,...l,service:"s3",region:this.region}),S=await fetch(f.url,{method:f.method,headers:f.headers,body:i});if(!S.ok){let b=await S.text();throw new G(`Failed to put object: ${b}`,S.status,a,n)}return{etag:(S.headers.get("ETag")||"").replace(/"/g,"")}}async delete(a,n){let i=await this.getCredentials(),s=this.buildUrl(a,n),c=x({method:"DELETE",url:s,...i,service:"s3",region:this.region}),l=await fetch(c.url,{method:c.method,headers:c.headers});if(!l.ok&&l.status!==204){let u=await l.text();throw new G(`Failed to delete object: ${u}`,l.status,a,n)}}async deleteMany(a,n){let i=await this.getCredentials(),s=`${this.buildUrl(a)}?delete`,c=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${n.map((T)=>`<Object><Key>${An(T)}</Key></Object>`).join("")}</Delete>`,l=x({method:"POST",url:s,headers:{"Content-Type":"application/xml"},body:c,...i,service:"s3",region:this.region}),u=await fetch(l.url,{method:l.method,headers:l.headers,body:c});if(!u.ok){let T=await u.text();throw new G(`Failed to delete objects: ${T}`,u.status,a)}let h=await u.text(),y=[],f=[],S=/<Deleted><Key>([^<]+)<\/Key>/g,b;while((b=S.exec(h))!==null)y.push(b[1]);let C=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((b=C.exec(h))!==null)f.push({key:b[1],error:`${b[2]}: ${b[3]}`});return{deleted:y,errors:f}}async list(a,n={}){let i=await this.getCredentials(),s=new URL(this.buildUrl(a));if(s.searchParams.set("list-type","2"),n.prefix)s.searchParams.set("prefix",n.prefix);if(n.delimiter)s.searchParams.set("delimiter",n.delimiter);if(n.maxKeys)s.searchParams.set("max-keys",String(n.maxKeys));if(n.continuationToken)s.searchParams.set("continuation-token",n.continuationToken);if(n.startAfter)s.searchParams.set("start-after",n.startAfter);let c=x({method:"GET",url:s.toString(),...i,service:"s3",region:this.region}),l=await fetch(c.url,{method:c.method,headers:c.headers});if(!l.ok){let h=await l.text();throw new G(`Failed to list objects: ${h}`,l.status,a)}let u=await l.text();return bn(u)}async*listAll(a,n={}){let i;do{let s=await this.list(a,{...n,continuationToken:i});for(let c of s.contents)yield c;i=s.nextContinuationToken}while(i)}async head(a,n){let i=await this.getCredentials(),s=this.buildUrl(a,n),c=x({method:"HEAD",url:s,...i,service:"s3",region:this.region}),l=await fetch(c.url,{method:c.method,headers:c.headers});if(l.status===404)return null;if(!l.ok){let h=await l.text();throw new G(`Failed to head object: ${h}`,l.status,a,n)}let u={};return l.headers.forEach((h,y)=>{if(y.toLowerCase().startsWith("x-amz-meta-"))u[y.slice(11)]=h}),{contentLength:Number(l.headers.get("Content-Length")||0),contentType:l.headers.get("Content-Type")||"application/octet-stream",etag:(l.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(l.headers.get("Last-Modified")||0),metadata:u,storageClass:l.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:l.headers.get("x-amz-server-side-encryption")||void 0}}async exists(a,n){return await this.head(a,n)!==null}async copy(a,n,i,s,c={}){let l=await this.getCredentials(),u=this.buildUrl(i,s),h={"x-amz-copy-source":`/${a}/${encodeURIComponent(n)}`};if(c.metadataDirective)h["x-amz-metadata-directive"]=c.metadataDirective;if(c.contentType)h["Content-Type"]=c.contentType;if(c.storageClass)h["x-amz-storage-class"]=c.storageClass;if(c.acl)h["x-amz-acl"]=c.acl;if(c.metadata)for(let[b,C]of Object.entries(c.metadata))h[`x-amz-meta-${b.toLowerCase()}`]=C;let y=x({method:"PUT",url:u,headers:h,...l,service:"s3",region:this.region}),f=await fetch(y.url,{method:y.method,headers:y.headers});if(!f.ok){let b=await f.text();throw new G(`Failed to copy object: ${b}`,f.status,i,s)}let S=(await f.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:S?S[1]:""}}async getPresignedUrl(a,n,i={}){let s=await this.getCredentials(),c=this.buildUrl(a,n);return rf({url:c,method:i.method||"GET",expiresIn:i.expiresIn||3600,...s,service:"s3",region:this.region})}async uploadMultipart(a,n,i,s={}){let c=await this.getCredentials(),l=Math.max(s.partSize||Pt,fn),u,h;if(i instanceof ReadableStream)u=i;else if(i instanceof Blob)u=i.stream(),h=i.size;else{let S=new Blob([i]);u=S.stream(),h=S.size}let{uploadId:y,baseUrl:f}=await this.initiateMultipartUpload(a,n,s);try{let S=await this.uploadParts(a,n,f,y,u,l,c,h,s.concurrency||4,s.onProgress);return await this.completeMultipartUpload(a,n,f,y,S)}catch(S){throw await this.abortMultipartUpload(a,n,y,f).catch(()=>{}),S}}async initiateMultipartUpload(a,n,i){let s=await this.getCredentials(),c=this.buildUrl(a,n),l=`${c}?uploads`,u={"Content-Type":i.contentType||la(n)};if(i.storageClass)u["x-amz-storage-class"]=i.storageClass;if(i.serverSideEncryption)u["x-amz-server-side-encryption"]=i.serverSideEncryption;if(i.acl)u["x-amz-acl"]=i.acl;if(i.metadata)for(let[b,C]of Object.entries(i.metadata))u[`x-amz-meta-${b.toLowerCase()}`]=C;let h=x({method:"POST",url:l,headers:u,...s,service:"s3",region:this.region}),y=await fetch(h.url,{method:h.method,headers:h.headers});if(!y.ok){let b=await y.text();throw new G(`Failed to initiate multipart upload: ${b}`,y.status,a,n)}let f=(await y.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!f)throw new G("Failed to parse upload ID from response",0,a,n);let S=c;if(y.url)try{let b=new URL(y.url);b.search="",S=b.toString()}catch{}return{uploadId:f[1],baseUrl:S}}async uploadParts(a,n,i,s,c,l,u,h,y,f){let S=[],b=c.getReader(),C=1,T=new Uint8Array(0),v=0,w=h?Math.ceil(h/l):void 0,R=new Map,k=async(P,V)=>{let B=`${i}?partNumber=${V}&uploadId=${encodeURIComponent(s)}`,j={"Content-Length":String(P.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},J=x({method:"PUT",url:B,headers:j,...u,service:"s3",region:this.region}),K=await fetch(J.url,{method:J.method,headers:J.headers,body:P,redirect:"error"});if(!K.ok){let te=await K.text();throw new G(`Failed to upload part ${V}: ${te}`,K.status,a,n)}let ee=(K.headers.get("ETag")||"").replace(/"/g,"");if(!ee)throw new G(`Missing ETag for part ${V}`,K.status,a,n);return{partNumber:V,etag:ee}},W=async()=>{let P=await Promise.race(R.values());R.delete(P.partNumber),S.push(P)};while(!0){let{done:P,value:V}=await b.read();if(V){let B=new Uint8Array(T.length+V.length);B.set(T),B.set(V,T.length),T=B}while(T.length>=l||P&&T.length>0){let B=T.slice(0,l);T=T.slice(l);let j=C++;if(R.size>=y)await W();if(R.set(j,k(B,j)),v+=B.byteLength,f)f({loaded:v,total:h||v,part:j,totalParts:w||j})}if(P)break}while(R.size>0)await W();return S.sort((P,V)=>P.partNumber-V.partNumber),S}async completeMultipartUpload(a,n,i,s,c){let l=await this.getCredentials(),u=`${i}?uploadId=${encodeURIComponent(s)}`,h=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${c.map((b)=>`<Part><PartNumber>${b.partNumber}</PartNumber><ETag>"${b.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,y=x({method:"POST",url:u,headers:{"Content-Type":"application/xml"},body:h,...l,service:"s3",region:this.region}),f=await fetch(y.url,{method:y.method,headers:y.headers,body:h});if(!f.ok){let b=await f.text();throw new G(`Failed to complete multipart upload: ${b}`,f.status,a,n)}let S=(await f.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:S?S[1]:""}}async abortMultipartUpload(a,n,i,s){let c=await this.getCredentials(),l=`${s??this.buildUrl(a,n)}?uploadId=${encodeURIComponent(i)}`,u=x({method:"DELETE",url:l,...c,service:"s3",region:this.region});await fetch(u.url,{method:u.method,headers:u.headers})}async emptyAndDeleteBucket(a){let n=[];for await(let l of this.listAll(a,{}))if(n.push(l.key),n.length>=1000)await this.deleteMany(a,n),n=[];if(n.length>0)await this.deleteMany(a,n);let i=await this.getCredentials(),s=this.buildUrl(a),c=x({method:"DELETE",url:s,...i,service:"s3",region:this.region});await fetch(c.url,{method:c.method,headers:c.headers})}}class G extends Error{statusCode;bucket;key;constructor(a,n,i,s){super(a);this.statusCode=n,this.bucket=i,this.key=s,this.name="S3Error"}}function bn(a){let n=[],i=[],s=/<Contents>([\s\S]*?)<\/Contents>/g,c;while((c=s.exec(a))!==null){let u=c[1];n.push({key:le(u,"Key")||"",lastModified:new Date(le(u,"LastModified")||0),etag:(le(u,"ETag")||"").replace(/"/g,""),size:Number(le(u,"Size")||0),storageClass:le(u,"StorageClass")||"STANDARD"})}let l=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((c=l.exec(a))!==null)i.push(c[1]);return{contents:n,commonPrefixes:i,isTruncated:le(a,"IsTruncated")==="true",continuationToken:le(a,"ContinuationToken")||void 0,nextContinuationToken:le(a,"NextContinuationToken")||void 0,keyCount:Number(le(a,"KeyCount")||0),maxKeys:Number(le(a,"MaxKeys")||1000),prefix:le(a,"Prefix")||void 0,delimiter:le(a,"Delimiter")||void 0}}function le(a,n){let i=new RegExp(`<${n}>([^<]*)</${n}>`),s=a.match(i);return s?s[1]:null}function An(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function la(a){let n=a.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[n||""]||"application/octet-stream"}function Cn(a){if(a instanceof Blob)return a;if(typeof a==="string")return new Blob([a],{type:"text/plain"});return new Blob([a])}function oI(a){return new Da(a)}await et();class He extends Error{code;solution;details;constructor(a,n,i,s){super(a);this.code=n,this.solution=i,this.details=s,this.name="CloudError",Error.captureStackTrace?.(this,He)}toString(){let a=`${this.name} [${this.code}]: ${this.message}`;if(this.solution)a+=`
2496
2496
 
2497
2497
  \uD83D\uDCA1 Solution: ${this.solution}`;if(this.details&&Object.keys(this.details).length>0){a+=`
2498
2498
 
2499
2499
  Details:`;for(let[n,i]of Object.entries(this.details))a+=`
2500
- ${n}: ${JSON.stringify(i)}`}return a}}class zs extends Qe{constructor(a,n,i){super(a,"CONFIG_ERROR",n,i);this.name="ConfigurationError"}}class Ht extends Qe{constructor(a,n,i){super(a,"CREDENTIAL_ERROR",n,i);this.name="CredentialError"}}class Tf extends Qe{constructor(a,n,i){super(a,"DEPLOYMENT_ERROR",n,i);this.name="DeploymentError"}}class Pp extends Qe{constructor(a,n,i){super(a,"VALIDATION_ERROR",n,i);this.name="ValidationError"}}class wf extends Qe{statusCode;constructor(a,n,i,s){super(a,"AWS_API_ERROR",i,s);this.statusCode=n,this.name="AWSAPIError"}}var Rf={NO_CREDENTIALS:{message:"AWS credentials not found",solution:`Configure AWS credentials using one of these methods:
2500
+ ${n}: ${JSON.stringify(i)}`}return a}}class zs extends He{constructor(a,n,i){super(a,"CONFIG_ERROR",n,i);this.name="ConfigurationError"}}class Ht extends He{constructor(a,n,i){super(a,"CREDENTIAL_ERROR",n,i);this.name="CredentialError"}}class Tf extends He{constructor(a,n,i){super(a,"DEPLOYMENT_ERROR",n,i);this.name="DeploymentError"}}class Pp extends He{constructor(a,n,i){super(a,"VALIDATION_ERROR",n,i);this.name="ValidationError"}}class wf extends He{statusCode;constructor(a,n,i,s){super(a,"AWS_API_ERROR",i,s);this.statusCode=n,this.name="AWSAPIError"}}var Rf={NO_CREDENTIALS:{message:"AWS credentials not found",solution:`Configure AWS credentials using one of these methods:
2501
2501
  1. Set environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
2502
2502
  2. Create ~/.aws/credentials file with your credentials
2503
2503
  3. Use an IAM role (for EC2 instances)
2504
- 4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};function Df(a){return Rf[a]}function Np(a,n){let i=Df(a);return new Qe(i.message,a,i.solution,n)}class Y{static verboseMode=!1;static debugMode=!1;static setVerbose(a){this.verboseMode=a}static setDebug(a){this.debugMode=a}static verbose(a,...n){if(this.verboseMode)console.log(`[VERBOSE] ${a}`,...n)}static debug(a,...n){if(this.debugMode)console.log(`[DEBUG] ${a}`,...n)}static info(a,...n){console.log(`ℹ ${a}`,...n)}static warn(a,...n){console.warn(`⚠ ${a}`,...n)}static error(a,n){if(console.error(`✖ ${a}`),n){if(n instanceof Qe)console.error(n.toString());else console.error(n.message);if(this.debugMode&&n.stack)console.error(`
2505
- Stack trace:`),console.error(n.stack)}}static success(a){console.log(`✔ ${a}`)}}function aI(a){if(!a)throw Np("MISSING_CONFIG");if(!a.project)throw new zs("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!a.project.name)throw new zs("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!a.project.slug)throw new zs("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test(a.project.slug))throw new Pp("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:a.project.slug});if(a.project.region){if(!["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"].includes(a.project.region))throw Np("INVALID_REGION",{region:a.project.region})}Y.success("Configuration validation passed")}function cI(a){let n=[];if(a.environments?.production&&a.infrastructure?.database){let i=a.infrastructure.database;if((i.postgres||i.mysql)&&!i.postgres?.multiAZ&&!i.mysql?.multiAZ)n.push("Production database should use Multi-AZ for high availability")}if(a.infrastructure?.storage){for(let[i,s]of Object.entries(a.infrastructure.storage))if(s.encryption===!1)n.push(`Storage "${i}" is not encrypted - consider enabling encryption for security`)}if(a.infrastructure?.storage){for(let[i,s]of Object.entries(a.infrastructure.storage))if(s.public===!0)n.push(`Storage "${i}" is publicly accessible - ensure this is intentional`)}if(a.infrastructure?.database){let i=a.infrastructure.database;if(i.postgres||i.mysql){let s=i.postgres?.backupRetentionDays||i.mysql?.backupRetentionDays;if(!s||s<7)n.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!a.infrastructure?.monitoring)n.push("No monitoring configured - consider adding CloudWatch alarms");return n}async function dI(a="default"){try{Y.verbose("Resolving AWS credentials...");let n=await bf(a);if(!n.accessKeyId||!n.secretAccessKey)throw new Ht("AWS credentials are incomplete","Ensure both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set");Y.verbose("Credentials resolved successfully"),Y.debug("Access Key ID:",n.accessKeyId.substring(0,8)+"..."),Y.verbose("Testing credentials with GetCallerIdentity...");let i;try{i=await vf(n),Y.verbose("Credentials are valid"),Y.debug("Account ID:",i)}catch(s){if(s instanceof Error)if(s.message.includes("InvalidClientTokenId"))throw new Ht("Invalid AWS access key ID","Check that your AWS_ACCESS_KEY_ID is correct");else if(s.message.includes("SignatureDoesNotMatch"))throw new Ht("Invalid AWS secret access key","Check that your AWS_SECRET_ACCESS_KEY is correct");else if(s.message.includes("ExpiredToken"))throw new Ht("AWS credentials have expired","Refresh your temporary credentials or use long-term credentials");else throw new Ht(`Failed to validate credentials: ${s.message}`,"Verify your AWS credentials are correct and have the necessary permissions");throw s}return{valid:!0,accountId:i,region:n.region}}catch(n){if(n instanceof Ht)throw n;return{valid:!1,error:n instanceof Error?n.message:"Unknown error"}}}async function lI(a,n){return{allowed:n,denied:[]}}function Pf(a){let n=new Set(["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate","cloudformation:ListStacks"]);if(a.infrastructure){if(a.infrastructure.storage)n.add("s3:CreateBucket"),n.add("s3:DeleteBucket"),n.add("s3:PutBucketPolicy"),n.add("s3:PutBucketVersioning"),n.add("s3:PutBucketEncryption"),n.add("s3:PutObject"),n.add("s3:GetObject");if(a.infrastructure.compute){if(a.infrastructure.compute.server)n.add("ec2:RunInstances"),n.add("ec2:TerminateInstances"),n.add("ec2:DescribeInstances"),n.add("autoscaling:CreateAutoScalingGroup"),n.add("autoscaling:UpdateAutoScalingGroup"),n.add("autoscaling:DeleteAutoScalingGroup"),n.add("elasticloadbalancing:CreateLoadBalancer"),n.add("elasticloadbalancing:DeleteLoadBalancer");if(a.infrastructure.compute.fargate)n.add("ecs:CreateCluster"),n.add("ecs:DeleteCluster"),n.add("ecs:CreateService"),n.add("ecs:UpdateService"),n.add("ecs:DeleteService"),n.add("ecs:RegisterTaskDefinition")}if(a.infrastructure.database){if(a.infrastructure.database.postgres||a.infrastructure.database.mysql)n.add("rds:CreateDBInstance"),n.add("rds:DeleteDBInstance"),n.add("rds:ModifyDBInstance"),n.add("rds:DescribeDBInstances");if(a.infrastructure.database.dynamodb)n.add("dynamodb:CreateTable"),n.add("dynamodb:DeleteTable"),n.add("dynamodb:UpdateTable"),n.add("dynamodb:DescribeTable")}if(a.infrastructure.functions)n.add("lambda:CreateFunction"),n.add("lambda:DeleteFunction"),n.add("lambda:UpdateFunctionCode"),n.add("lambda:UpdateFunctionConfiguration"),n.add("lambda:AddPermission");if(a.infrastructure.cdn)n.add("cloudfront:CreateDistribution"),n.add("cloudfront:UpdateDistribution"),n.add("cloudfront:DeleteDistribution"),n.add("cloudfront:GetDistribution");if(a.infrastructure.network)n.add("ec2:CreateVpc"),n.add("ec2:DeleteVpc"),n.add("ec2:CreateSubnet"),n.add("ec2:DeleteSubnet"),n.add("ec2:CreateInternetGateway"),n.add("ec2:DeleteInternetGateway"),n.add("ec2:CreateNatGateway"),n.add("ec2:DeleteNatGateway"),n.add("ec2:CreateRouteTable"),n.add("ec2:DeleteRouteTable"),n.add("ec2:CreateSecurityGroup"),n.add("ec2:DeleteSecurityGroup")}return n.add("iam:CreateRole"),n.add("iam:DeleteRole"),n.add("iam:AttachRolePolicy"),n.add("iam:DetachRolePolicy"),n.add("iam:PutRolePolicy"),n.add("iam:GetRole"),n.add("iam:PassRole"),Array.from(n).sort()}function uI(a){let n=Pf(a);return JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n,Resource:"*"}]},null,2)}var q={ec2:{"Running On-Demand Instances":20,"Elastic IPs":5,VPCs:5,"Internet Gateways":5,"NAT Gateways":5,"Security Groups":500},rds:{"DB Instances":40,"DB Snapshots":100,"DB Parameter Groups":50},lambda:{"Concurrent Executions":1000,"Function Storage":80530636800},s3:{Buckets:100},cloudformation:{Stacks:200,StackSets:100},elasticache:{Nodes:100,Clusters:100},dynamodb:{Tables:256},ecs:{Clusters:1e4,"Services per Cluster":2000}};async function pI(a){let n=[];if(Y.verbose("Checking AWS service quotas..."),a.infrastructure?.compute?.server){let s=a.infrastructure.compute.server.autoScaling?.max||1;n.push({service:"EC2",quotaName:"Running On-Demand Instances",currentValue:s,limit:q.ec2["Running On-Demand Instances"],percentage:s/q.ec2["Running On-Demand Instances"]*100,warning:s>q.ec2["Running On-Demand Instances"]*0.8})}if(a.infrastructure?.network?.vpc)n.push({service:"EC2",quotaName:"VPCs",currentValue:1,limit:q.ec2.VPCs,percentage:1/q.ec2.VPCs*100,warning:!1});if(a.infrastructure?.database?.postgres||a.infrastructure?.database?.mysql)n.push({service:"RDS",quotaName:"DB Instances",currentValue:1,limit:q.rds["DB Instances"],percentage:1/q.rds["DB Instances"]*100,warning:!1});if(a.infrastructure?.storage){let s=Object.keys(a.infrastructure.storage).length;n.push({service:"S3",quotaName:"Buckets",currentValue:s,limit:q.s3.Buckets,percentage:s/q.s3.Buckets*100,warning:s>q.s3.Buckets*0.8})}if(a.infrastructure?.functions){let s=0;for(let c of Object.values(a.infrastructure.functions))if(Array.isArray(c))s+=c.length;n.push({service:"Lambda",quotaName:"Functions (estimated)",currentValue:s,limit:1000,percentage:s/1000*100,warning:s>800})}if(a.infrastructure?.database?.dynamodb){let s=a.infrastructure.database.dynamodb.tables?.length||0;n.push({service:"DynamoDB",quotaName:"Tables",currentValue:s,limit:q.dynamodb.Tables,percentage:s/q.dynamodb.Tables*100,warning:s>q.dynamodb.Tables*0.8})}let i=n.filter((s)=>s.warning);if(i.length>0){Y.warn("Service quota warnings detected:");for(let s of i)Y.warn(` ${s.service} - ${s.quotaName}: ${s.currentValue}/${s.limit} (${s.percentage.toFixed(1)}%)`)}else Y.verbose("All service quotas are within limits");return n}function gI(a){if(a.length===0)return"No quotas to check";let n=`Service Quota Usage:
2504
+ 4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};function Df(a){return Rf[a]}function Np(a,n){let i=Df(a);return new He(i.message,a,i.solution,n)}class Z{static verboseMode=!1;static debugMode=!1;static setVerbose(a){this.verboseMode=a}static setDebug(a){this.debugMode=a}static verbose(a,...n){if(this.verboseMode)console.log(`[VERBOSE] ${a}`,...n)}static debug(a,...n){if(this.debugMode)console.log(`[DEBUG] ${a}`,...n)}static info(a,...n){console.log(`ℹ ${a}`,...n)}static warn(a,...n){console.warn(`⚠ ${a}`,...n)}static error(a,n){if(console.error(`✖ ${a}`),n){if(n instanceof He)console.error(n.toString());else console.error(n.message);if(this.debugMode&&n.stack)console.error(`
2505
+ Stack trace:`),console.error(n.stack)}}static success(a){console.log(`✔ ${a}`)}}function aI(a){if(!a)throw Np("MISSING_CONFIG");if(!a.project)throw new zs("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!a.project.name)throw new zs("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!a.project.slug)throw new zs("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test(a.project.slug))throw new Pp("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:a.project.slug});if(a.project.region){if(!["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"].includes(a.project.region))throw Np("INVALID_REGION",{region:a.project.region})}Z.success("Configuration validation passed")}function cI(a){let n=[];if(a.environments?.production&&a.infrastructure?.database){let i=a.infrastructure.database;if((i.postgres||i.mysql)&&!i.postgres?.multiAZ&&!i.mysql?.multiAZ)n.push("Production database should use Multi-AZ for high availability")}if(a.infrastructure?.storage){for(let[i,s]of Object.entries(a.infrastructure.storage))if(s.encryption===!1)n.push(`Storage "${i}" is not encrypted - consider enabling encryption for security`)}if(a.infrastructure?.storage){for(let[i,s]of Object.entries(a.infrastructure.storage))if(s.public===!0)n.push(`Storage "${i}" is publicly accessible - ensure this is intentional`)}if(a.infrastructure?.database){let i=a.infrastructure.database;if(i.postgres||i.mysql){let s=i.postgres?.backupRetentionDays||i.mysql?.backupRetentionDays;if(!s||s<7)n.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!a.infrastructure?.monitoring)n.push("No monitoring configured - consider adding CloudWatch alarms");return n}async function dI(a="default"){try{Z.verbose("Resolving AWS credentials...");let n=await bf(a);if(!n.accessKeyId||!n.secretAccessKey)throw new Ht("AWS credentials are incomplete","Ensure both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set");Z.verbose("Credentials resolved successfully"),Z.debug("Access Key ID:",n.accessKeyId.substring(0,8)+"..."),Z.verbose("Testing credentials with GetCallerIdentity...");let i;try{i=await vf(n),Z.verbose("Credentials are valid"),Z.debug("Account ID:",i)}catch(s){if(s instanceof Error)if(s.message.includes("InvalidClientTokenId"))throw new Ht("Invalid AWS access key ID","Check that your AWS_ACCESS_KEY_ID is correct");else if(s.message.includes("SignatureDoesNotMatch"))throw new Ht("Invalid AWS secret access key","Check that your AWS_SECRET_ACCESS_KEY is correct");else if(s.message.includes("ExpiredToken"))throw new Ht("AWS credentials have expired","Refresh your temporary credentials or use long-term credentials");else throw new Ht(`Failed to validate credentials: ${s.message}`,"Verify your AWS credentials are correct and have the necessary permissions");throw s}return{valid:!0,accountId:i,region:n.region}}catch(n){if(n instanceof Ht)throw n;return{valid:!1,error:n instanceof Error?n.message:"Unknown error"}}}async function lI(a,n){return{allowed:n,denied:[]}}function Pf(a){let n=new Set(["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate","cloudformation:ListStacks"]);if(a.infrastructure){if(a.infrastructure.storage)n.add("s3:CreateBucket"),n.add("s3:DeleteBucket"),n.add("s3:PutBucketPolicy"),n.add("s3:PutBucketVersioning"),n.add("s3:PutBucketEncryption"),n.add("s3:PutObject"),n.add("s3:GetObject");if(a.infrastructure.compute){if(a.infrastructure.compute.server)n.add("ec2:RunInstances"),n.add("ec2:TerminateInstances"),n.add("ec2:DescribeInstances"),n.add("autoscaling:CreateAutoScalingGroup"),n.add("autoscaling:UpdateAutoScalingGroup"),n.add("autoscaling:DeleteAutoScalingGroup"),n.add("elasticloadbalancing:CreateLoadBalancer"),n.add("elasticloadbalancing:DeleteLoadBalancer");if(a.infrastructure.compute.fargate)n.add("ecs:CreateCluster"),n.add("ecs:DeleteCluster"),n.add("ecs:CreateService"),n.add("ecs:UpdateService"),n.add("ecs:DeleteService"),n.add("ecs:RegisterTaskDefinition")}if(a.infrastructure.database){if(a.infrastructure.database.postgres||a.infrastructure.database.mysql)n.add("rds:CreateDBInstance"),n.add("rds:DeleteDBInstance"),n.add("rds:ModifyDBInstance"),n.add("rds:DescribeDBInstances");if(a.infrastructure.database.dynamodb)n.add("dynamodb:CreateTable"),n.add("dynamodb:DeleteTable"),n.add("dynamodb:UpdateTable"),n.add("dynamodb:DescribeTable")}if(a.infrastructure.functions)n.add("lambda:CreateFunction"),n.add("lambda:DeleteFunction"),n.add("lambda:UpdateFunctionCode"),n.add("lambda:UpdateFunctionConfiguration"),n.add("lambda:AddPermission");if(a.infrastructure.cdn)n.add("cloudfront:CreateDistribution"),n.add("cloudfront:UpdateDistribution"),n.add("cloudfront:DeleteDistribution"),n.add("cloudfront:GetDistribution");if(a.infrastructure.network)n.add("ec2:CreateVpc"),n.add("ec2:DeleteVpc"),n.add("ec2:CreateSubnet"),n.add("ec2:DeleteSubnet"),n.add("ec2:CreateInternetGateway"),n.add("ec2:DeleteInternetGateway"),n.add("ec2:CreateNatGateway"),n.add("ec2:DeleteNatGateway"),n.add("ec2:CreateRouteTable"),n.add("ec2:DeleteRouteTable"),n.add("ec2:CreateSecurityGroup"),n.add("ec2:DeleteSecurityGroup")}return n.add("iam:CreateRole"),n.add("iam:DeleteRole"),n.add("iam:AttachRolePolicy"),n.add("iam:DetachRolePolicy"),n.add("iam:PutRolePolicy"),n.add("iam:GetRole"),n.add("iam:PassRole"),Array.from(n).sort()}function uI(a){let n=Pf(a);return JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n,Resource:"*"}]},null,2)}var q={ec2:{"Running On-Demand Instances":20,"Elastic IPs":5,VPCs:5,"Internet Gateways":5,"NAT Gateways":5,"Security Groups":500},rds:{"DB Instances":40,"DB Snapshots":100,"DB Parameter Groups":50},lambda:{"Concurrent Executions":1000,"Function Storage":80530636800},s3:{Buckets:100},cloudformation:{Stacks:200,StackSets:100},elasticache:{Nodes:100,Clusters:100},dynamodb:{Tables:256},ecs:{Clusters:1e4,"Services per Cluster":2000}};async function pI(a){let n=[];if(Z.verbose("Checking AWS service quotas..."),a.infrastructure?.compute?.server){let s=a.infrastructure.compute.server.autoScaling?.max||1;n.push({service:"EC2",quotaName:"Running On-Demand Instances",currentValue:s,limit:q.ec2["Running On-Demand Instances"],percentage:s/q.ec2["Running On-Demand Instances"]*100,warning:s>q.ec2["Running On-Demand Instances"]*0.8})}if(a.infrastructure?.network?.vpc)n.push({service:"EC2",quotaName:"VPCs",currentValue:1,limit:q.ec2.VPCs,percentage:1/q.ec2.VPCs*100,warning:!1});if(a.infrastructure?.database?.postgres||a.infrastructure?.database?.mysql)n.push({service:"RDS",quotaName:"DB Instances",currentValue:1,limit:q.rds["DB Instances"],percentage:1/q.rds["DB Instances"]*100,warning:!1});if(a.infrastructure?.storage){let s=Object.keys(a.infrastructure.storage).length;n.push({service:"S3",quotaName:"Buckets",currentValue:s,limit:q.s3.Buckets,percentage:s/q.s3.Buckets*100,warning:s>q.s3.Buckets*0.8})}if(a.infrastructure?.functions){let s=0;for(let c of Object.values(a.infrastructure.functions))if(Array.isArray(c))s+=c.length;n.push({service:"Lambda",quotaName:"Functions (estimated)",currentValue:s,limit:1000,percentage:s/1000*100,warning:s>800})}if(a.infrastructure?.database?.dynamodb){let s=a.infrastructure.database.dynamodb.tables?.length||0;n.push({service:"DynamoDB",quotaName:"Tables",currentValue:s,limit:q.dynamodb.Tables,percentage:s/q.dynamodb.Tables*100,warning:s>q.dynamodb.Tables*0.8})}let i=n.filter((s)=>s.warning);if(i.length>0){Z.warn("Service quota warnings detected:");for(let s of i)Z.warn(` ${s.service} - ${s.quotaName}: ${s.currentValue}/${s.limit} (${s.percentage.toFixed(1)}%)`)}else Z.verbose("All service quotas are within limits");return n}function gI(a){if(a.length===0)return"No quotas to check";let n=`Service Quota Usage:
2506
2506
 
2507
2507
  `,i=a.reduce((s,c)=>{if(!s[c.service])s[c.service]=[];return s[c.service].push(c),s},{});for(let[s,c]of Object.entries(i)){n+=`${s}:
2508
2508
  `;for(let l of c){let u=l.warning?"⚠":"✓";n+=` ${u} ${l.quotaName}: ${l.currentValue}/${l.limit} (${l.percentage.toFixed(1)}%)
2509
2509
  `}n+=`
2510
- `}return n}function mI(a){let n=[];for(let i of a)if(i.percentage>=100)n.push(`Request quota increase for ${i.service} - ${i.quotaName} (currently ${i.limit})`);else if(i.warning)n.push(`Consider requesting quota increase for ${i.service} - ${i.quotaName} (${i.percentage.toFixed(1)}% used)`);return n}class kp{cacheDir;ttl;constructor(a,n={}){this.cacheDir=a,this.ttl=n.ttl||86400000}ensureCacheDir(){if(!ot(this.cacheDir))Tn(this.cacheDir,{recursive:!0})}getCachePath(a){let n=ka("sha256").update(a).digest("hex");return It(this.cacheDir,`${n}.json`)}get(a){let n=this.getCachePath(a);if(!ot(n))return;try{let i=da(n,"utf-8"),s=JSON.parse(i);if(Date.now()-s.timestamp>this.ttl){qe(n);return}return s.value}catch{qe(n);return}}set(a,n,i){this.ensureCacheDir();let s=this.getCachePath(a),c={value:n,timestamp:Date.now(),hash:i};vn(s,JSON.stringify(c),"utf-8")}has(a){return this.get(a)!==void 0}clear(){if(!ot(this.cacheDir))return;let a=ua(this.cacheDir);for(let n of a)qe(It(this.cacheDir,n))}prune(){if(!ot(this.cacheDir))return;let a=ua(this.cacheDir),n=Date.now();for(let i of a){let s=It(this.cacheDir,i);try{let c=da(s,"utf-8"),l=JSON.parse(c);if(n-l.timestamp>this.ttl)qe(s)}catch{qe(s)}}}}class Bp{cache;constructor(a=_("cache","templates")){this.cache=new kp(a,{ttl:86400000})}getTemplate(a){return this.cache.get(`template:${a}`)}setTemplate(a,n){let i=this.hashTemplate(n);this.cache.set(`template:${a}`,n,i)}hasChanged(a,n){let i=this.cache.get(`template:${a}`);if(!i)return!0;let s=this.hashTemplate(i),c=this.hashTemplate(n);return s!==c}hashTemplate(a){return ka("sha256").update(a).digest("hex")}clear(){this.cache.clear()}prune(){this.cache.prune()}}var Rt=null;function hI(){if(!Rt)Rt=new Bp;return Rt}async function xp(a,n={}){let i=n.algorithm||"sha256",s=n.chunkSize||65536;return new Promise((c,l)=>{let u=Vt(i),h=wn(a,{highWaterMark:s});h.on("data",(y)=>u.update(y)),h.on("end",()=>c(u.digest("hex"))),h.on("error",l)})}function _p(a,n="sha256"){return Vt(n).update(a).digest("hex")}function fI(a,n="sha256"){return Vt(n).update(a).digest("hex")}async function yI(a,n={}){let i=n.ignorePatterns||["node_modules",".git","dist","build",Qs()],s=[];async function c(l){let u=En(l,{withFileTypes:!0});for(let h of u){let y=Pn(l,h.name),f=In(a,y);if(i.some((S)=>f.includes(S)))continue;if(h.isDirectory())await c(y);else if(h.isFile()){let S=ht(y),b=await xp(y,n);s.push({path:f,hash:b,size:S.size,mtime:S.mtimeMs})}}}return await c(a),s}function II(a){let n=[...a].sort((i,s)=>i.path.localeCompare(s.path)).map((i)=>`${i.path}:${i.hash}`).join(`
2510
+ `}return n}function mI(a){let n=[];for(let i of a)if(i.percentage>=100)n.push(`Request quota increase for ${i.service} - ${i.quotaName} (currently ${i.limit})`);else if(i.warning)n.push(`Consider requesting quota increase for ${i.service} - ${i.quotaName} (${i.percentage.toFixed(1)}% used)`);return n}class kp{cacheDir;ttl;constructor(a,n={}){this.cacheDir=a,this.ttl=n.ttl||86400000}ensureCacheDir(){if(!st(this.cacheDir))Tn(this.cacheDir,{recursive:!0})}getCachePath(a){let n=ka("sha256").update(a).digest("hex");return It(this.cacheDir,`${n}.json`)}get(a){let n=this.getCachePath(a);if(!st(n))return;try{let i=da(n,"utf-8"),s=JSON.parse(i);if(Date.now()-s.timestamp>this.ttl){qe(n);return}return s.value}catch{qe(n);return}}set(a,n,i){this.ensureCacheDir();let s=this.getCachePath(a),c={value:n,timestamp:Date.now(),hash:i};vn(s,JSON.stringify(c),"utf-8")}has(a){return this.get(a)!==void 0}clear(){if(!st(this.cacheDir))return;let a=ua(this.cacheDir);for(let n of a)qe(It(this.cacheDir,n))}prune(){if(!st(this.cacheDir))return;let a=ua(this.cacheDir),n=Date.now();for(let i of a){let s=It(this.cacheDir,i);try{let c=da(s,"utf-8"),l=JSON.parse(c);if(n-l.timestamp>this.ttl)qe(s)}catch{qe(s)}}}}class Bp{cache;constructor(a=_("cache","templates")){this.cache=new kp(a,{ttl:86400000})}getTemplate(a){return this.cache.get(`template:${a}`)}setTemplate(a,n){let i=this.hashTemplate(n);this.cache.set(`template:${a}`,n,i)}hasChanged(a,n){let i=this.cache.get(`template:${a}`);if(!i)return!0;let s=this.hashTemplate(i),c=this.hashTemplate(n);return s!==c}hashTemplate(a){return ka("sha256").update(a).digest("hex")}clear(){this.cache.clear()}prune(){this.cache.prune()}}var Rt=null;function hI(){if(!Rt)Rt=new Bp;return Rt}async function xp(a,n={}){let i=n.algorithm||"sha256",s=n.chunkSize||65536;return new Promise((c,l)=>{let u=Vt(i),h=wn(a,{highWaterMark:s});h.on("data",(y)=>u.update(y)),h.on("end",()=>c(u.digest("hex"))),h.on("error",l)})}function _p(a,n="sha256"){return Vt(n).update(a).digest("hex")}function fI(a,n="sha256"){return Vt(n).update(a).digest("hex")}async function yI(a,n={}){let i=n.ignorePatterns||["node_modules",".git","dist","build",Qs()],s=[];async function c(l){let u=En(l,{withFileTypes:!0});for(let h of u){let y=Pn(l,h.name),f=In(a,y);if(i.some((S)=>f.includes(S)))continue;if(h.isDirectory())await c(y);else if(h.isFile()){let S=ht(y),b=await xp(y,n);s.push({path:f,hash:b,size:S.size,mtime:S.mtimeMs})}}}return await c(a),s}function II(a){let n=[...a].sort((i,s)=>i.path.localeCompare(s.path)).map((i)=>`${i.path}:${i.hash}`).join(`
2511
2511
  `);return _p(n)}function SI(a){let n=ht(a);return _p(`${a}:${n.size}:${n.mtimeMs}`)}function CI(a,n){let i=new Map(a.map((h)=>[h.path,h])),s=new Map(n.map((h)=>[h.path,h])),c=[],l=[],u=[];for(let[h,y]of s){let f=i.get(h);if(!f)c.push(y);else if(f.hash!==y.hash)l.push(y)}for(let[h,y]of i)if(!s.has(h))u.push(y);return{added:c,modified:l,deleted:u}}class Nf{cache;constructor(){this.cache=new Map}get(a){let n=ht(a),i=this.cache.get(a);if(i&&i.mtime===n.mtimeMs&&i.size===n.size)return i.hash;return}set(a,n){let i=ht(a);this.cache.set(a,{hash:n,mtime:i.mtimeMs,size:i.size})}async getOrCompute(a,n={}){let i=this.get(a);if(i)return i;let s=await xp(a,n);return this.set(a,s),s}clear(){this.cache.clear()}}async function ad(a,n={}){let i=n.concurrency||5,s=n.stopOnError??!0,c=[],l=[],u=Date.now(),h=[...a],y=[];async function f(C,T){try{let v=await C();c[T]=v}catch(v){let w=v instanceof Error?v:Error(String(v));if(l.push(w),s)throw h.length=0,w}}let S=0;while(h.length>0||y.length>0){while(y.length<i&&h.length>0){let C=h.shift(),T=S++,v=f(C,T);y.push(v)}if(y.length>0){await Promise.race(y);for(let C=y.length-1;C>=0;C--)if(await Promise.race([y[C].then(()=>!0),Promise.resolve(!1)]))y.splice(C,1)}if(s&&l.length>0)break}let b=Date.now()-u;return{results:c.filter((C)=>C!==void 0),errors:l,duration:b}}async function bI(a,n,i={}){let s=a.map((c)=>()=>n(c));return ad(s,i)}async function EI(a,n,i=5){let s=a.map((l,u)=>()=>n(l,u)),c=await ad(s,{concurrency:i,stopOnError:!1});if(c.errors.length>0)throw AggregateError(c.errors,"Parallel map failed");return c.results}async function vI(a,n={}){let i=n.retries||3,s=n.retryDelay||1000,c=a.map((l)=>async()=>{let u;for(let h=0;h<=i;h++)try{return await l()}catch(y){if(u=y instanceof Error?y:Error(String(y)),h<i)await $a(s*(h+1))}throw u});return ad(c,n)}async function TI(a){let n=[];for(let i of a){let s=await i();n.push(s)}return n}function $a(a){return new Promise((n)=>setTimeout(n,a))}async function wI(a,n,i="Operation timed out"){return Promise.race([a(),new Promise((s,c)=>setTimeout(()=>c(Error(i)),n))])}class kf{maxConcurrent;minInterval;queue=[];running=0;lastExecution=0;constructor(a=5,n=100){this.maxConcurrent=a,this.minInterval=n}async execute(a){await this.waitForSlot(),this.running++,this.lastExecution=Date.now();try{return await a()}finally{this.running--,this.processQueue()}}waitForSlot(){if(this.running<this.maxConcurrent){let a=Date.now()-this.lastExecution;if(a>=this.minInterval)return Promise.resolve();return $a(this.minInterval-a)}return new Promise((a)=>this.queue.push(a))}processQueue(){if(this.queue.length>0&&this.running<this.maxConcurrent)this.queue.shift()()}stats(){return{running:this.running,queued:this.queue.length}}}function Bf(a,n){let i=[];for(let s=0;s<a.length;s+=n)i.push(a.slice(s,s+n));return i}async function RI(a,n,i){let s=Bf(a,n),c=[];for(let l of s){let u=await i(l);c.push(...u)}return c}function DI(a,n){let i=[],s=[],c=[],l=[],u=a.Resources||{},h=n.Resources||{},y=new Set(Object.keys(u)),f=new Set(Object.keys(h));for(let C of f)if(!y.has(C))i.push(C);for(let C of y)if(!f.has(C))c.push(C);for(let C of f)if(y.has(C)){let T=u[C],v=h[C];if(JSON.stringify(T)!==JSON.stringify(v))s.push(C);else l.push(C)}let S=JSON.stringify(a.Parameters||{})!==JSON.stringify(n.Parameters||{}),b=JSON.stringify(a.Outputs||{})!==JSON.stringify(n.Outputs||{});return{added:i,modified:s,deleted:c,unchanged:l,parametersChanged:S,outputsChanged:b,hasChanges:i.length>0||s.length>0||c.length>0||S||b}}function PI(a){let n=[];if(!a.hasChanges)return"No changes detected";if(a.added.length>0){n.push(`Added resources (${a.added.length}):`);for(let i of a.added)n.push(` + ${i}`)}if(a.modified.length>0){n.push(`Modified resources (${a.modified.length}):`);for(let i of a.modified)n.push(` ~ ${i}`)}if(a.deleted.length>0){n.push(`Deleted resources (${a.deleted.length}):`);for(let i of a.deleted)n.push(` - ${i}`)}if(a.parametersChanged)n.push("Parameters changed");if(a.outputsChanged)n.push("Outputs changed");return n.join(`
2512
2512
  `)}function NI(a,n,i){if(a.deleted.length>0)return!0;for(let s of a.modified){let c=n.Resources[s],l=i.Resources[s];if(c.Type!==l.Type)return!0;let u=Rn(l.Type);for(let h of u){let y=c.Properties?.[h],f=l.Properties?.[h];if(JSON.stringify(y)!==JSON.stringify(f))return!0}}return!1}function Rn(a){return{"AWS::S3::Bucket":["BucketName"],"AWS::EC2::Instance":["ImageId","InstanceType","KeyName"],"AWS::RDS::DBInstance":["DBInstanceIdentifier","Engine"],"AWS::DynamoDB::Table":["TableName","KeySchema"],"AWS::Lambda::Function":["FunctionName"],"AWS::ECS::Service":["ServiceName"],"AWS::ElasticLoadBalancingV2::LoadBalancer":["Name","Type"]}[a]||[]}function kI(a){let n=[],i=[],s=[];n.push(...a.added);for(let c of a.modified)i.push(c);return s.push(...a.deleted),{safe:n,caution:i,dangerous:s}}function BI(a){if(!a.hasChanges)return{strategy:"skip",reason:"No changes detected"};if(a.deleted.length>0)return{strategy:"replace",reason:"Resources will be deleted"};if(a.added.length>0&&a.modified.length===0)return{strategy:"update",reason:"Only new resources added"};return{strategy:"update",reason:"Resources will be updated"}}function xI(a){let n=a.added.length+a.modified.length+a.deleted.length+a.unchanged.length,i=a.added.length+a.modified.length+a.deleted.length,s=n>0?i/n*100:0;return{total:n,added:a.added.length,modified:a.modified.length,deleted:a.deleted.length,unchanged:a.unchanged.length,changePercentage:s}}var _I={$schema:"http://json-schema.org/draft-07/schema#",title:"ts-cloud Configuration",description:"Configuration schema for ts-cloud infrastructure-as-code",type:"object",required:["project"],properties:{project:{type:"object",description:"Project configuration",required:["name","slug"],properties:{name:{type:"string",description:"Human-readable project name",minLength:1},slug:{type:"string",description:"URL-safe project identifier (lowercase, alphanumeric, hyphens only)",pattern:"^[a-z0-9-]+$",minLength:1,maxLength:63},region:{type:"string",description:"Default AWS region",enum:["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"]}}},mode:{type:"string",description:"Deployment mode (server and serverless are mutually exclusive; auto-detected when omitted)",enum:["server","serverless"]},environments:{type:"object",description:"Environment-specific configurations",properties:{production:{$ref:"#/definitions/environment"},staging:{$ref:"#/definitions/environment"},development:{$ref:"#/definitions/environment"}}},infrastructure:{type:"object",description:"Infrastructure configuration",properties:{network:{$ref:"#/definitions/network"},storage:{type:"object",description:"S3 storage configuration",additionalProperties:{$ref:"#/definitions/storage"}},compute:{$ref:"#/definitions/compute"},database:{$ref:"#/definitions/database"},cache:{$ref:"#/definitions/cache"},cdn:{$ref:"#/definitions/cdn"},sftp:{$ref:"#/definitions/sftp"},functions:{type:"object",description:"Lambda functions configuration",additionalProperties:{type:"array",items:{$ref:"#/definitions/function"}}},monitoring:{$ref:"#/definitions/monitoring"},security:{$ref:"#/definitions/security"},queue:{type:"object",description:"SQS queue configuration",additionalProperties:{$ref:"#/definitions/queue"}}}}},definitions:{environment:{type:"object",properties:{domain:{type:"string",description:"Custom domain for this environment"},region:{type:"string",description:"AWS region override for this environment"},app:{type:"object",description:"Serverless application manifest (Laravel-Vapor-equivalent). Defining this opts the environment into the serverless app deploy pipeline (http/queue/cli Lambda functions, assets, build/deploy hooks).",properties:{runtime:{type:"string",description:"Lambda runtime override (usually derived from kind + runtimeVersion)"},runtimeVersion:{type:"string",description:"Node major (18/20/22 managed, 24+ custom layer) or Bun release for node/bun apps"},kind:{type:"string",enum:["node","bun","php"],description:"Application kind (drives packaging + runtime)"},entry:{type:"string",description:"Entry file exporting the request handler"},memory:{type:"number",description:"HTTP function memory in MB"},timeout:{type:"number",description:"HTTP request timeout in seconds"},gatewayVersion:{type:"number",enum:[1,2],description:"API Gateway version (2 = HTTP API, 1 = REST)"},warm:{type:"number",description:"Keep-warm / provisioned concurrency count"},lambdaInsights:{type:"object",description:"CloudWatch Lambda Insights extension configuration for zip deployments",required:["layerArn"],properties:{layerArn:{type:"string",description:"Region- and architecture-specific Lambda Insights extension layer ARN"}}},queues:{description:"Queue names (true = single default queue, false = disabled)"},scheduler:{type:"string",enum:["off","on","sub-minute"],description:"Task scheduler mode"},build:{type:"array",items:{type:"string"},description:"Commands run locally before packaging"},deploy:{type:"array",items:{type:"string"},description:"Commands run remotely after activation (e.g. migrations)"},octane:{type:"boolean",description:"Persistent application mode (Laravel Octane)"},packaging:{type:"string",enum:["zip","image"],description:"Deployment package format (zip or container image)"},phpVersion:{type:"string",description:"PHP version for the runtime layer (kind: php)"},architecture:{type:"string",enum:["x86_64","arm64"],description:"CPU architecture"}}}}},network:{type:"object",properties:{vpc:{type:"object",properties:{cidr:{type:"string",description:"VPC CIDR block",pattern:"^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$",default:"10.0.0.0/16"},availabilityZones:{type:"number",description:"Number of availability zones",minimum:1,maximum:3,default:2},natGateways:{type:"number",description:"Number of NAT gateways (0 for no NAT, saves cost)",minimum:0,maximum:3,default:1}}}}},storage:{type:"object",properties:{public:{type:"boolean",description:"Allow public access",default:!1},versioning:{type:"boolean",description:"Enable versioning",default:!1},encryption:{type:"boolean",description:"Enable server-side encryption",default:!0},website:{type:"boolean",description:"Enable static website hosting",default:!1},cors:{type:"object",description:"CORS configuration",properties:{allowedOrigins:{type:"array",items:{type:"string"}},allowedMethods:{type:"array",items:{type:"string",enum:["GET","PUT","POST","DELETE","HEAD"]}}}}}},compute:{type:"object",properties:{server:{type:"object",description:"EC2 server configuration",properties:{instanceType:{type:"string",description:"EC2 instance type",enum:["t3.micro","t3.small","t3.medium","t3.large","t3.xlarge","t3.2xlarge"]},autoScaling:{type:"object",properties:{min:{type:"number",minimum:1},max:{type:"number",minimum:1},desired:{type:"number",minimum:1}}}}},fargate:{type:"object",description:"ECS Fargate configuration",properties:{cpu:{type:"number",description:"CPU units (256, 512, 1024, 2048, 4096)",enum:[256,512,1024,2048,4096]},memory:{type:"number",description:"Memory in MB"},desiredCount:{type:"number",description:"Desired number of tasks",minimum:1}}}}},database:{type:"object",properties:{postgres:{type:"object",properties:{instanceClass:{type:"string",description:"RDS instance class",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"postgres"},version:{type:"string",description:"PostgreSQL version"},multiAZ:{type:"boolean",description:"Enable Multi-AZ deployment",default:!1},backupRetentionDays:{type:"number",description:"Backup retention period in days",minimum:0,maximum:35,default:7}}},mysql:{type:"object",properties:{instanceClass:{type:"string",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"mysql"},version:{type:"string"},multiAZ:{type:"boolean",default:!1},backupRetentionDays:{type:"number",minimum:0,maximum:35,default:7}}},dynamodb:{type:"object",properties:{tables:{type:"array",items:{type:"object",required:["name","partitionKey"],properties:{name:{type:"string"},partitionKey:{type:"string"},sortKey:{type:"string"},billingMode:{type:"string",enum:["PAY_PER_REQUEST","PROVISIONED"],default:"PAY_PER_REQUEST"}}}}}}}},cache:{type:"object",properties:{redis:{type:"object",properties:{nodeType:{type:"string",description:"ElastiCache node type",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1},engineVersion:{type:"string",description:"Redis engine version"}}},memcached:{type:"object",properties:{nodeType:{type:"string",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1}}}}},cdn:{type:"object",properties:{enabled:{type:"boolean",default:!0},originShield:{type:"boolean",description:"Enable CloudFront Origin Shield",default:!1},originShieldRegion:{type:"string",description:"AWS region used by CloudFront Origin Shield"},compress:{type:"boolean",description:"Enable automatic compression",default:!0},http3:{type:"boolean",description:"Enable HTTP/3 support",default:!0},customDomain:{type:"object",properties:{domain:{type:"string"},certificateArn:{type:"string"}}},cachePolicy:{type:"object",properties:{minTTL:{type:"number",minimum:0},defaultTTL:{type:"number",minimum:0},maxTTL:{type:"number",minimum:0}}}}},sftp:{type:"object",required:["bucket","users"],properties:{bucket:{type:"string",description:"S3 bucket backing the SFTP server"},endpointType:{type:"string",enum:["PUBLIC","VPC"],default:"PUBLIC"},endpointDetails:{type:"object",required:["vpcId","subnetIds"],properties:{vpcId:{type:"string"},subnetIds:{type:"array",items:{type:"string"},minItems:1},securityGroupIds:{type:"array",items:{type:"string"}},addressAllocationIds:{type:"array",items:{type:"string"}}}},securityPolicyName:{type:"string"},logging:{type:"boolean",default:!0},users:{type:"object",additionalProperties:{type:"object",required:["sshPublicKeys"],properties:{sshPublicKeys:{type:"array",items:{type:"string"},minItems:1},homeDirectory:{type:"string"},roleArn:{type:"string"}}}}}},function:{type:"object",required:["name","runtime"],properties:{name:{type:"string"},runtime:{type:"string",enum:["nodejs18.x","nodejs20.x","python3.10","python3.11","python3.12"]},handler:{type:"string",default:"index.handler"},timeout:{type:"number",minimum:1,maximum:900,default:30},memory:{type:"number",minimum:128,maximum:10240,default:1024}}},monitoring:{type:"object",properties:{alarms:{type:"array",items:{type:"object",required:["metric","threshold"],properties:{metric:{type:"string"},threshold:{type:"number"},evaluationPeriods:{type:"number",minimum:1,default:2}}}},dashboard:{type:"object",properties:{name:{type:"string"},widgets:{type:"array"}}}}},security:{type:"object",properties:{waf:{type:"boolean",description:"Enable AWS WAF",default:!1},certificates:{type:"array",items:{type:"object",required:["domain"],properties:{domain:{type:"string"},subdomains:{type:"array",items:{type:"string"}}}}}}},queue:{type:"object",properties:{fifo:{type:"boolean",default:!1},deadLetterQueue:{type:"boolean",default:!0},visibilityTimeout:{type:"number",minimum:0,maximum:43200,default:30},messageRetentionPeriod:{type:"number",minimum:60,maximum:1209600,default:345600}}}}};function OI(a){let n=[];if(!a.project)n.push("Missing required field: project");else{if(!a.project.name)n.push("Missing required field: project.name");if(!a.project.slug)n.push("Missing required field: project.slug")}if(a.project?.slug&&!/^[a-z0-9-]+$/.test(a.project.slug))n.push("Invalid project.slug: must contain only lowercase letters, numbers, and hyphens");let i=["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"];if(a.project?.region&&!i.includes(a.project.region))n.push(`Invalid region: ${a.project.region}. Must be one of: ${i.join(", ")}`);if(a.mode&&!["server","serverless"].includes(a.mode))n.push("Invalid mode: must be one of server or serverless");return{valid:n.length===0,errors:n}}var Op={enabled:process.env.TS_CLOUD_LOCAL==="true"||!0,localstackEndpoint:process.env.LOCALSTACK_ENDPOINT||"http://localhost:4566",postgresUrl:process.env.POSTGRES_URL||"postgresql://tscloud:tscloud@localhost:5432/tscloud",redisUrl:process.env.REDIS_URL||"redis://localhost:6379",dynamodbEndpoint:process.env.DYNAMODB_ENDPOINT||"http://localhost:8000",s3Endpoint:process.env.S3_ENDPOINT||"http://localhost:9000",emailEndpoint:process.env.EMAIL_ENDPOINT||"smtp://localhost:1025",awsRegion:process.env.AWS_REGION||"us-east-1",awsAccessKeyId:process.env.AWS_ACCESS_KEY_ID||"test",awsSecretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||"test"};function cd(){return Op}function LI(){return Op.enabled}function $I(a){let n=cd();if(!n.enabled)return"";switch(a.toLowerCase()){case"dynamodb":return n.dynamodbEndpoint;case"s3":return n.s3Endpoint;case"localstack":case"cloudformation":case"lambda":case"apigateway":case"sns":case"sqs":case"cloudwatch":case"iam":case"sts":return n.localstackEndpoint;default:return n.localstackEndpoint}}function MI(){let a=cd();return{accessKeyId:a.awsAccessKeyId,secretAccessKey:a.awsSecretAccessKey,region:a.awsRegion}}function FI(){let a=cd();if(!a.enabled)return{};return{AWS_ACCESS_KEY_ID:a.awsAccessKeyId,AWS_SECRET_ACCESS_KEY:a.awsSecretAccessKey,AWS_REGION:a.awsRegion,AWS_ENDPOINT_URL:a.localstackEndpoint,LOCALSTACK_ENDPOINT:a.localstackEndpoint,TS_CLOUD_LOCAL:"true"}}class Lp{stacks=new Map;stackEvents=new Map;async createStack(a){let n=`arn:aws:cloudformation:${a.region||"us-east-1"}:123456789012:stack/${a.StackName}/${Date.now()}`;return this.stacks.set(a.StackName,{StackId:n,StackName:a.StackName,StackStatus:"CREATE_IN_PROGRESS",CreationTime:new Date().toISOString(),TemplateBody:a.TemplateBody,Parameters:a.Parameters||[]}),this.addEvent(a.StackName,{EventId:Date.now().toString(),StackName:a.StackName,LogicalResourceId:a.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_IN_PROGRESS"}),setTimeout(()=>{let i=this.stacks.get(a.StackName);if(i)i.StackStatus="CREATE_COMPLETE",this.addEvent(a.StackName,{EventId:(Date.now()+1).toString(),StackName:a.StackName,LogicalResourceId:a.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_COMPLETE"})},100),{StackId:n}}async updateStack(a){let n=this.stacks.get(a.StackName);if(!n)throw Error(`Stack ${a.StackName} does not exist`);return n.StackStatus="UPDATE_IN_PROGRESS",n.TemplateBody=a.TemplateBody||n.TemplateBody,this.addEvent(a.StackName,{EventId:Date.now().toString(),StackName:a.StackName,LogicalResourceId:a.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_IN_PROGRESS"}),setTimeout(()=>{n.StackStatus="UPDATE_COMPLETE",this.addEvent(a.StackName,{EventId:(Date.now()+1).toString(),StackName:a.StackName,LogicalResourceId:a.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_COMPLETE"})},100),{StackId:n.StackId}}async deleteStack(a){let n=this.stacks.get(a.StackName);if(!n)throw Error(`Stack ${a.StackName} does not exist`);n.StackStatus="DELETE_IN_PROGRESS",this.addEvent(a.StackName,{EventId:Date.now().toString(),StackName:a.StackName,LogicalResourceId:a.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_IN_PROGRESS"}),setTimeout(()=>{this.stacks.delete(a.StackName),this.addEvent(a.StackName,{EventId:(Date.now()+1).toString(),StackName:a.StackName,LogicalResourceId:a.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_COMPLETE"})},100)}async describeStacks(a){if(a.StackName){let n=this.stacks.get(a.StackName);if(!n)throw Error(`Stack ${a.StackName} does not exist`);return{Stacks:[n]}}return{Stacks:Array.from(this.stacks.values())}}async describeStackEvents(a){return{StackEvents:this.stackEvents.get(a.StackName)||[]}}addEvent(a,n){if(!this.stackEvents.has(a))this.stackEvents.set(a,[]);this.stackEvents.get(a).unshift(n)}reset(){this.stacks.clear(),this.stackEvents.clear()}}class $p{buckets=new Map;async createBucket(a){return this.buckets.set(a.Bucket,new Map),{Location:`/${a.Bucket}`}}async deleteBucket(a){this.buckets.delete(a.Bucket)}async putObject(a){let n=this.buckets.get(a.Bucket);if(!n)n=new Map,this.buckets.set(a.Bucket,n);return n.set(a.Key,Buffer.from(a.Body||"")),{ETag:`"${Date.now()}"`}}async getObject(a){let n=this.buckets.get(a.Bucket);if(!n)throw Error(`Bucket ${a.Bucket} does not exist`);let i=n.get(a.Key);if(!i)throw Error(`Object ${a.Key} does not exist`);return{Body:i,ContentLength:i.length}}async deleteObject(a){let n=this.buckets.get(a.Bucket);if(n)n.delete(a.Key)}async listObjects(a){let n=this.buckets.get(a.Bucket);if(!n)throw Error(`Bucket ${a.Bucket} does not exist`);return{Contents:Array.from(n.keys()).map((i)=>({Key:i,Size:n.get(i).length,LastModified:new Date().toISOString()}))}}reset(){this.buckets.clear()}}class Mp{tables=new Map;data=new Map;async createTable(a){return this.tables.set(a.TableName,{TableName:a.TableName,KeySchema:a.KeySchema,AttributeDefinitions:a.AttributeDefinitions,TableStatus:"ACTIVE",CreationDateTime:new Date().toISOString()}),this.data.set(a.TableName,new Map),{TableDescription:this.tables.get(a.TableName)}}async deleteTable(a){this.tables.delete(a.TableName),this.data.delete(a.TableName)}async putItem(a){let n=this.data.get(a.TableName);if(!n)n=new Map,this.data.set(a.TableName,n);let i=JSON.stringify(a.Item);n.set(i,a.Item)}async getItem(a){let n=this.data.get(a.TableName);if(!n)return{};let i=JSON.stringify(a.Key),s=n.get(i);return s?{Item:s}:{}}async deleteItem(a){let n=this.data.get(a.TableName);if(n){let i=JSON.stringify(a.Key);n.delete(i)}}async scan(a){let n=this.data.get(a.TableName);if(!n)return{Items:[]};return{Items:Array.from(n.values())}}reset(){this.tables.clear(),this.data.clear()}}function UI(a){return{cloudformation:new Lp,s3:new $p,dynamodb:new Mp}}class Fp{environments=new Map;async createPreviewEnvironment(a){let{branch:n,pr:i,commitSha:s,ttl:c=24,baseConfig:l,region:u="us-east-1"}=a,h=this.generatePreviewId(n,i,s),y=this.generatePreviewName(n,i),f=`preview-${y}`,S=new Date,b=new Date(S.getTime()+c*60*60*1000),C={id:h,name:y,branch:n,pr:i,commitSha:s,createdAt:S,expiresAt:b,status:"creating",stackName:f,region:u,resources:[]};this.environments.set(h,C);try{let T=this.createPreviewConfig(l,y);return C.status="active",C.url=`https://${y}.preview.example.com`,C}catch(T){throw C.status="failed",T}}async destroyPreviewEnvironment(a){let n=this.environments.get(a);if(!n)throw Error(`Preview environment ${a} not found`);n.status="destroying";try{n.status="destroyed",this.environments.delete(a)}catch(i){throw Error(`Failed to destroy preview environment: ${i}`)}}getPreviewEnvironment(a){return this.environments.get(a)}getPreviewEnvironmentByBranch(a){return Array.from(this.environments.values()).find((n)=>n.branch===a)}getPreviewEnvironmentByPR(a){return Array.from(this.environments.values()).find((n)=>n.pr===a)}listPreviewEnvironments(){return Array.from(this.environments.values())}listActivePreviewEnvironments(){return this.listPreviewEnvironments().filter((a)=>a.status==="active")}async cleanupExpiredEnvironments(a={}){let{maxAge:n,keepCount:i,dryRun:s=!1}=a,c=[],l=[],u=new Date,h=this.listPreviewEnvironments().sort((y,f)=>f.createdAt.getTime()-y.createdAt.getTime());for(let y=0;y<h.length;y++){let f=h[y];if(f.status!=="active")continue;let S=!1;if(f.expiresAt<u)S=!0;if(n){if((u.getTime()-f.createdAt.getTime())/3600000>n)S=!0}if(i&&y>=i)S=!0;if(S)if(s)c.push(f.id);else try{await this.destroyPreviewEnvironment(f.id),c.push(f.id)}catch(b){l.push(f.id)}}return{destroyed:c,failed:l}}async updatePreviewEnvironment(a,n){let i=this.environments.get(a);if(!i)throw Error(`Preview environment ${a} not found`);i.commitSha=n,i.status="creating";try{return i.status="active",i}catch(s){throw i.status="failed",s}}async getPreviewEnvironmentsCost(){let a={},n=0;for(let i of this.environments.values())a[i.id]=0,n+=0;return{total:n,byEnvironment:a}}generatePreviewId(a,n,i){let s=a.replace(/[^a-z0-9-]/gi,"-").toLowerCase(),c=i?.substring(0,7)||Date.now().toString();return n?`pr-${n}-${c}`:`${s}-${c}`}generatePreviewName(a,n){let i=a.replace(/[^a-z0-9-]/gi,"-").toLowerCase();return n?`pr-${n}`:i}createPreviewConfig(a,n){return{...a,project:{...a.project,name:`${a.project.name} Preview (${n})`,slug:`${a.project.slug}-preview-${n}`}}}}var QI=new Fp;function HI(a={}){let{workflowName:n="Preview Environment",trigger:i="pull_request",branches:s=["main","develop"],awsRegion:c="us-east-1",awsRole:l,configFile:u="cloud.config.ts",ttl:h=24}=a;return`name: ${n}
2513
2513
 
@@ -3793,7 +3793,7 @@ COPY . .`,impact:"Improve build time by 60-80% on subsequent builds"});let h={si
3793
3793
  <p>If you didn't request this, please ignore this email.</p>
3794
3794
  </body>
3795
3795
  </html>
3796
- `,textPart:"Hi {{userName}}, reset your password at: {{resetUrl}}. This link expires in {{expirationHours}} hours."})}updateTemplate(a,n,i){let s=this.templates.get(a);if(!s)throw Error(`Template not found: ${a}`);if(n.subject)s.subject=n.subject;if(n.htmlPart)s.htmlPart=n.htmlPart;if(n.textPart)s.textPart=n.textPart;return s.version++,s.updatedAt=new Date,s.variables=this.extractVariables(s.subject+s.htmlPart+s.textPart),this.addVersion({templateId:a,version:s.version,subject:s.subject,htmlPart:s.htmlPart,textPart:s.textPart,createdBy:"system",changelog:i}),s}addVersion(a){let n={id:`version-${a.templateId}-${a.version}`,createdAt:new Date,...a},i=this.versions.get(a.templateId)||[];return i.push(n),this.versions.set(a.templateId,i),n}extractVariables(a){let n=/\{\{([^}]+)\}\}/g,i=new Set,s;while((s=n.exec(a))!==null)i.add(s[1].trim());return Array.from(i)}renderTemplate(a,n){let i=this.templates.get(a);if(!i)throw Error(`Template not found: ${a}`);let s=(c)=>c.replace(/\{\{([^}]+)\}\}/g,(l,u)=>{let h=u.trim();return n[h]!==void 0?String(n[h]):l});return{subject:s(i.subject),html:s(i.htmlPart),text:s(i.textPart)}}testTemplate(a,n){let i=`test-${Date.now()}-${this.testCounter++}`,s=this.renderTemplate(a,n),c={id:i,templateId:a,testData:n,renderedSubject:s.subject,renderedHtml:s.html,renderedText:s.text,timestamp:new Date};return this.tests.set(i,c),c}getTemplate(a){return this.templates.get(a)}listTemplates(){return Array.from(this.templates.values())}getTemplateVersions(a){return this.versions.get(a)||[]}revertToVersion(a,n){let i=this.templates.get(a);if(!i)throw Error(`Template not found: ${a}`);let s=(this.versions.get(a)||[]).find((c)=>c.version===n);if(!s)throw Error(`Version ${n} not found for template ${a}`);return i.subject=s.subject,i.htmlPart=s.htmlPart,i.textPart=s.textPart,i.version++,i.updatedAt=new Date,this.addVersion({templateId:a,version:i.version,subject:i.subject,htmlPart:i.htmlPart,textPart:i.textPart,createdBy:"system",changelog:`Reverted to version ${n}`}),i}generateTemplateCF(a){return{Type:"AWS::SES::Template",Properties:{Template:{TemplateName:a.name,SubjectPart:a.subject,HtmlPart:a.htmlPart,TextPart:a.textPart}}}}clear(){this.templates.clear(),this.versions.clear(),this.tests.clear(),this.templateCounter=0,this.testCounter=0}}var BC=new Ng,Gf={};_e(Gf,{EmailAnalyticsModule:()=>Ze,EmailRules:()=>Jt,EmailScheduling:()=>qt,EmailSearch:()=>jt,EmailTemplates:()=>Ne,EmailThreading:()=>Kt,SharedMailboxes:()=>zt});class jt{static createSearchDomain(a){let{slug:n,environment:i,domainName:s,instanceType:c="t3.small.search",instanceCount:l=1,ebsVolumeSize:u=10,masterUserName:h="admin",masterUserPassword:y}=a,f=s||`${n}-${i}-email-search`;return{[`${n}EmailSearchDomain`]:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:f,EngineVersion:"OpenSearch_2.11",ClusterConfig:{InstanceType:c,InstanceCount:l,DedicatedMasterEnabled:!1,ZoneAwarenessEnabled:!1},EBSOptions:{EBSEnabled:!0,VolumeType:"gp3",VolumeSize:u},NodeToNodeEncryptionOptions:{Enabled:!0},EncryptionAtRestOptions:{Enabled:!0},DomainEndpointOptions:{EnforceHTTPS:!0},AdvancedSecurityOptions:{Enabled:!0,InternalUserDatabaseEnabled:!0,MasterUserOptions:{MasterUserName:h,MasterUserPassword:y||`${n}-search-${Date.now()}`}},AccessPolicies:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:`arn:aws:es:*:*:domain/${f}/*`}]}}}}}static createIndexerLambda(a){return{[`${a.slug}EmailIndexerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-email-indexer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:60,MemorySize:512,Code:{ZipFile:jt.IndexerLambdaCode},Environment:{Variables:{OPENSEARCH_ENDPOINT:a.searchDomainEndpoint,EMAIL_BUCKET:a.emailBucket}}}}}}static IndexerLambdaCode=`
3796
+ `,textPart:"Hi {{userName}}, reset your password at: {{resetUrl}}. This link expires in {{expirationHours}} hours."})}updateTemplate(a,n,i){let s=this.templates.get(a);if(!s)throw Error(`Template not found: ${a}`);if(n.subject)s.subject=n.subject;if(n.htmlPart)s.htmlPart=n.htmlPart;if(n.textPart)s.textPart=n.textPart;return s.version++,s.updatedAt=new Date,s.variables=this.extractVariables(s.subject+s.htmlPart+s.textPart),this.addVersion({templateId:a,version:s.version,subject:s.subject,htmlPart:s.htmlPart,textPart:s.textPart,createdBy:"system",changelog:i}),s}addVersion(a){let n={id:`version-${a.templateId}-${a.version}`,createdAt:new Date,...a},i=this.versions.get(a.templateId)||[];return i.push(n),this.versions.set(a.templateId,i),n}extractVariables(a){let n=/\{\{([^}]+)\}\}/g,i=new Set,s;while((s=n.exec(a))!==null)i.add(s[1].trim());return Array.from(i)}renderTemplate(a,n){let i=this.templates.get(a);if(!i)throw Error(`Template not found: ${a}`);let s=(c)=>c.replace(/\{\{([^}]+)\}\}/g,(l,u)=>{let h=u.trim();return n[h]!==void 0?String(n[h]):l});return{subject:s(i.subject),html:s(i.htmlPart),text:s(i.textPart)}}testTemplate(a,n){let i=`test-${Date.now()}-${this.testCounter++}`,s=this.renderTemplate(a,n),c={id:i,templateId:a,testData:n,renderedSubject:s.subject,renderedHtml:s.html,renderedText:s.text,timestamp:new Date};return this.tests.set(i,c),c}getTemplate(a){return this.templates.get(a)}listTemplates(){return Array.from(this.templates.values())}getTemplateVersions(a){return this.versions.get(a)||[]}revertToVersion(a,n){let i=this.templates.get(a);if(!i)throw Error(`Template not found: ${a}`);let s=(this.versions.get(a)||[]).find((c)=>c.version===n);if(!s)throw Error(`Version ${n} not found for template ${a}`);return i.subject=s.subject,i.htmlPart=s.htmlPart,i.textPart=s.textPart,i.version++,i.updatedAt=new Date,this.addVersion({templateId:a,version:i.version,subject:i.subject,htmlPart:i.htmlPart,textPart:i.textPart,createdBy:"system",changelog:`Reverted to version ${n}`}),i}generateTemplateCF(a){return{Type:"AWS::SES::Template",Properties:{Template:{TemplateName:a.name,SubjectPart:a.subject,HtmlPart:a.htmlPart,TextPart:a.textPart}}}}clear(){this.templates.clear(),this.versions.clear(),this.tests.clear(),this.templateCounter=0,this.testCounter=0}}var BC=new Ng,Gf={};Be(Gf,{EmailAnalyticsModule:()=>Ze,EmailRules:()=>Jt,EmailScheduling:()=>qt,EmailSearch:()=>jt,EmailTemplates:()=>Ne,EmailThreading:()=>Kt,SharedMailboxes:()=>zt});class jt{static createSearchDomain(a){let{slug:n,environment:i,domainName:s,instanceType:c="t3.small.search",instanceCount:l=1,ebsVolumeSize:u=10,masterUserName:h="admin",masterUserPassword:y}=a,f=s||`${n}-${i}-email-search`;return{[`${n}EmailSearchDomain`]:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:f,EngineVersion:"OpenSearch_2.11",ClusterConfig:{InstanceType:c,InstanceCount:l,DedicatedMasterEnabled:!1,ZoneAwarenessEnabled:!1},EBSOptions:{EBSEnabled:!0,VolumeType:"gp3",VolumeSize:u},NodeToNodeEncryptionOptions:{Enabled:!0},EncryptionAtRestOptions:{Enabled:!0},DomainEndpointOptions:{EnforceHTTPS:!0},AdvancedSecurityOptions:{Enabled:!0,InternalUserDatabaseEnabled:!0,MasterUserOptions:{MasterUserName:h,MasterUserPassword:y||`${n}-search-${Date.now()}`}},AccessPolicies:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:`arn:aws:es:*:*:domain/${f}/*`}]}}}}}static createIndexerLambda(a){return{[`${a.slug}EmailIndexerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-email-indexer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:60,MemorySize:512,Code:{ZipFile:jt.IndexerLambdaCode},Environment:{Variables:{OPENSEARCH_ENDPOINT:a.searchDomainEndpoint,EMAIL_BUCKET:a.emailBucket}}}}}}static IndexerLambdaCode=`
3797
3797
  const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
3798
3798
  const https = require('https');
3799
3799
 
@@ -5164,7 +5164,7 @@ async function invokeLambda(functionName, metadata) {
5164
5164
  Payload: JSON.stringify(metadata),
5165
5165
  }));
5166
5166
  }
5167
- `;static createRulesTable(a){return{[`${a.slug}EmailRulesTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}}static createRuleProcessorLambda(a){return{[`${a.slug}EmailRuleProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-email-rule-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:Jt.RuleProcessorCode},Environment:{Variables:{EMAIL_BUCKET:a.emailBucket,RULES_TABLE:a.rulesTable}}}}}}static RuleTemplates={spamFilter:{name:"Spam Filter",conditions:[{field:"subject",operator:"regex",value:"(viagra|lottery|winner|prince|inheritance)",caseSensitive:!1}],conditionOperator:"or",actions:[{type:"move",params:{folder:"spam"}},{type:"mark-read",params:{}}]},autoLabel:{name:"Auto Label Invoices",conditions:[{field:"subject",operator:"contains",value:"invoice",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"label",params:{label:"invoices"}}]},forwardUrgent:{name:"Forward Urgent",conditions:[{field:"subject",operator:"contains",value:"urgent",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"forward",params:{to:"admin@example.com"}},{type:"label",params:{label:"urgent"}}]}}}var qf={};_e(qf,{default:()=>On,handler:()=>xn});var xn=`
5167
+ `;static createRulesTable(a){return{[`${a.slug}EmailRulesTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}}static createRuleProcessorLambda(a){return{[`${a.slug}EmailRuleProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-email-rule-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:Jt.RuleProcessorCode},Environment:{Variables:{EMAIL_BUCKET:a.emailBucket,RULES_TABLE:a.rulesTable}}}}}}static RuleTemplates={spamFilter:{name:"Spam Filter",conditions:[{field:"subject",operator:"regex",value:"(viagra|lottery|winner|prince|inheritance)",caseSensitive:!1}],conditionOperator:"or",actions:[{type:"move",params:{folder:"spam"}},{type:"mark-read",params:{}}]},autoLabel:{name:"Auto Label Invoices",conditions:[{field:"subject",operator:"contains",value:"invoice",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"label",params:{label:"invoices"}}]},forwardUrgent:{name:"Forward Urgent",conditions:[{field:"subject",operator:"contains",value:"urgent",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"forward",params:{to:"admin@example.com"}},{type:"label",params:{label:"urgent"}}]}}}var qf={};Be(qf,{default:()=>On,handler:()=>xn});var xn=`
5168
5168
  const { S3Client, GetObjectCommand, PutObjectCommand, CopyObjectCommand } = require('@aws-sdk/client-s3');
5169
5169
  const s3 = new S3Client({});
5170
5170
 
@@ -5480,7 +5480,7 @@ catch (error) {
5480
5480
 
5481
5481
  return { statusCode: 200, body: 'OK' };
5482
5482
  };
5483
- `,Vf={};_e(Vf,{CallAnalytics:()=>Zt,CallRecording:()=>Yt,Callbacks:()=>yt,IVRBuilder:()=>Oe});class Yt{static RecordingProcessorCode=`
5483
+ `,Vf={};Be(Vf,{CallAnalytics:()=>Zt,CallRecording:()=>Yt,Callbacks:()=>yt,IVRBuilder:()=>xe});class Yt{static RecordingProcessorCode=`
5484
5484
  const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
5485
5485
  const { TranscribeClient, StartTranscriptionJobCommand } = require('@aws-sdk/client-transcribe');
5486
5486
  const { DynamoDBClient, PutItemCommand, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
@@ -5672,7 +5672,7 @@ else if (jobStatus === 'FAILED') {
5672
5672
 
5673
5673
  return { statusCode: 200 };
5674
5674
  };
5675
- `;static createRecordingsTable(a){return{[`${a.slug}CallRecordingsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"},{AttributeName:"transcriptionJobName",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"job-index",KeySchema:[{AttributeName:"transcriptionJobName",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRecordingProcessorLambda(a){return{[`${a.slug}RecordingProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-recording-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:Yt.RecordingProcessorCode},Environment:{Variables:{RECORDING_BUCKET:a.recordingBucket,RECORDINGS_TABLE:a.recordingsTable}}}}}}}class Oe{nodes=[];connections=[];startNodeId="";static create(a){return new Oe}start(){let a={id:this.generateId(),type:"start",position:{x:0,y:0},config:{}};return this.nodes.push(a),this.startNodeId=a.id,this}playPrompt(a,n){let i={id:this.generateId(),type:"play-prompt",position:{x:0,y:0},config:{text:a,textType:n?.ssml?"ssml":"text",voice:n?.voice||"Joanna"}};return this.nodes.push(i),this.connectToLast(i.id),this}getInput(a,n){let i={id:this.generateId(),type:"get-input",position:{x:0,y:0},config:{prompt:a,maxDigits:n?.maxDigits||1,timeout:n?.timeout||5,errorPrompt:n?.errorPrompt||"Sorry, I didn't get that."}};return this.nodes.push(i),this.connectToLast(i.id),this}menu(a,n){let i={id:this.generateId(),type:"menu",position:{x:0,y:0},config:{prompt:a,options:n}};return this.nodes.push(i),this.connectToLast(i.id),this}transferToQueue(a,n){let i={id:this.generateId(),type:"transfer-queue",position:{x:0,y:0},config:{queueArn:a,priority:n?.priority||5}};return this.nodes.push(i),this.connectToLast(i.id),this}transferToPhone(a){let n={id:this.generateId(),type:"transfer-phone",position:{x:0,y:0},config:{phoneNumber:a}};return this.nodes.push(n),this.connectToLast(n.id),this}invokeLambda(a,n){let i={id:this.generateId(),type:"invoke-lambda",position:{x:0,y:0},config:{functionArn:a,timeout:n?.timeout||8}};return this.nodes.push(i),this.connectToLast(i.id),this}setAttribute(a,n){let i={id:this.generateId(),type:"set-attribute",position:{x:0,y:0},config:{key:a,value:n}};return this.nodes.push(i),this.connectToLast(i.id),this}checkHours(a){let n={id:this.generateId(),type:"check-hours",position:{x:0,y:0},config:{hoursOfOperationArn:a}};return this.nodes.push(n),this.connectToLast(n.id),this}recordVoicemail(a){let n={id:this.generateId(),type:"record-voicemail",position:{x:0,y:0},config:{maxDuration:a?.maxDuration||120,greeting:a?.greeting||"Please leave a message after the beep.",beep:a?.beep!==!1}};return this.nodes.push(n),this.connectToLast(n.id),this}wait(a){let n={id:this.generateId(),type:"wait",position:{x:0,y:0},config:{seconds:a}};return this.nodes.push(n),this.connectToLast(n.id),this}disconnect(){let a={id:this.generateId(),type:"disconnect",position:{x:0,y:0},config:{}};return this.nodes.push(a),this.connectToLast(a.id),this}build(){return{id:this.generateId(),name:"IVR Flow",nodes:this.nodes,connections:this.connections,startNodeId:this.startNodeId,version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}toContactFlow(){let a=[],n=new Map(this.nodes.map((s)=>[s.id,s]));for(let s of this.nodes){let c=this.nodeToAction(s,n);if(c)a.push(c)}let i={Version:"2019-10-30",StartAction:this.startNodeId,Actions:a};return JSON.stringify(i,null,2)}nodeToAction(a,n){let i=this.getNextNodeId(a.id),s={NextAction:i||"disconnect",Errors:[{NextAction:"disconnect"}]};switch(a.type){case"start":return null;case"play-prompt":return{Identifier:a.id,Type:"MessageParticipant",Parameters:{Text:a.config.text,TextType:a.config.textType},Transitions:s};case"get-input":return{Identifier:a.id,Type:"GetParticipantInput",Parameters:{Text:a.config.prompt,InputTimeLimitSeconds:a.config.timeout,MaxDigits:a.config.maxDigits},Transitions:{...s,Conditions:[]}};case"transfer-queue":return{Identifier:a.id,Type:"TransferToQueue",Parameters:{QueueId:a.config.queueArn},Transitions:s};case"transfer-phone":return{Identifier:a.id,Type:"TransferToPhoneNumber",Parameters:{PhoneNumber:a.config.phoneNumber},Transitions:s};case"invoke-lambda":return{Identifier:a.id,Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:a.config.functionArn,InvocationTimeLimitSeconds:a.config.timeout},Transitions:s};case"set-attribute":return{Identifier:a.id,Type:"UpdateContactAttributes",Parameters:{Attributes:{[a.config.key]:a.config.value}},Transitions:s};case"check-hours":return{Identifier:a.id,Type:"CheckHoursOfOperation",Parameters:{HoursOfOperationId:a.config.hoursOfOperationArn},Transitions:{NextAction:i,Conditions:[{NextAction:i,Condition:{Operator:"Equals",Operands:["True"]}}],Errors:[{NextAction:"disconnect"}]}};case"wait":return{Identifier:a.id,Type:"Wait",Parameters:{Seconds:a.config.seconds},Transitions:s};case"disconnect":return{Identifier:a.id,Type:"DisconnectParticipant",Parameters:{},Transitions:{}};default:return null}}connectToLast(a){if(this.nodes.length>1){let n=this.nodes[this.nodes.length-2];this.connections.push({id:this.generateId(),sourceNodeId:n.id,targetNodeId:a,sourcePort:"default"})}}getNextNodeId(a){return this.connections.find((n)=>n.sourceNodeId===a)?.targetNodeId||null}generateId(){return`node-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static Templates={basicSupport:()=>Oe.create("Basic Support").start().playPrompt("Welcome to customer support.").menu("Press 1 for sales, 2 for support, or 3 to leave a message.",{"1":"sales","2":"support","3":"voicemail"}),afterHours:(a)=>Oe.create("After Hours").start().playPrompt(a).recordVoicemail({greeting:"Please leave your name, number, and a brief message.",maxDuration:120}).playPrompt("Thank you for your message. Goodbye.").disconnect(),callbackRequest:(a)=>Oe.create("Callback Request").start().playPrompt("All agents are currently busy.").getInput("Press 1 to request a callback, or 2 to wait.",{maxDigits:1}).invokeLambda(a).playPrompt("We will call you back shortly. Goodbye.").disconnect()}}class Zt{static MetricsAggregatorCode=`
5675
+ `;static createRecordingsTable(a){return{[`${a.slug}CallRecordingsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"},{AttributeName:"transcriptionJobName",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"job-index",KeySchema:[{AttributeName:"transcriptionJobName",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRecordingProcessorLambda(a){return{[`${a.slug}RecordingProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-recording-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:Yt.RecordingProcessorCode},Environment:{Variables:{RECORDING_BUCKET:a.recordingBucket,RECORDINGS_TABLE:a.recordingsTable}}}}}}}class xe{nodes=[];connections=[];startNodeId="";static create(a){return new xe}start(){let a={id:this.generateId(),type:"start",position:{x:0,y:0},config:{}};return this.nodes.push(a),this.startNodeId=a.id,this}playPrompt(a,n){let i={id:this.generateId(),type:"play-prompt",position:{x:0,y:0},config:{text:a,textType:n?.ssml?"ssml":"text",voice:n?.voice||"Joanna"}};return this.nodes.push(i),this.connectToLast(i.id),this}getInput(a,n){let i={id:this.generateId(),type:"get-input",position:{x:0,y:0},config:{prompt:a,maxDigits:n?.maxDigits||1,timeout:n?.timeout||5,errorPrompt:n?.errorPrompt||"Sorry, I didn't get that."}};return this.nodes.push(i),this.connectToLast(i.id),this}menu(a,n){let i={id:this.generateId(),type:"menu",position:{x:0,y:0},config:{prompt:a,options:n}};return this.nodes.push(i),this.connectToLast(i.id),this}transferToQueue(a,n){let i={id:this.generateId(),type:"transfer-queue",position:{x:0,y:0},config:{queueArn:a,priority:n?.priority||5}};return this.nodes.push(i),this.connectToLast(i.id),this}transferToPhone(a){let n={id:this.generateId(),type:"transfer-phone",position:{x:0,y:0},config:{phoneNumber:a}};return this.nodes.push(n),this.connectToLast(n.id),this}invokeLambda(a,n){let i={id:this.generateId(),type:"invoke-lambda",position:{x:0,y:0},config:{functionArn:a,timeout:n?.timeout||8}};return this.nodes.push(i),this.connectToLast(i.id),this}setAttribute(a,n){let i={id:this.generateId(),type:"set-attribute",position:{x:0,y:0},config:{key:a,value:n}};return this.nodes.push(i),this.connectToLast(i.id),this}checkHours(a){let n={id:this.generateId(),type:"check-hours",position:{x:0,y:0},config:{hoursOfOperationArn:a}};return this.nodes.push(n),this.connectToLast(n.id),this}recordVoicemail(a){let n={id:this.generateId(),type:"record-voicemail",position:{x:0,y:0},config:{maxDuration:a?.maxDuration||120,greeting:a?.greeting||"Please leave a message after the beep.",beep:a?.beep!==!1}};return this.nodes.push(n),this.connectToLast(n.id),this}wait(a){let n={id:this.generateId(),type:"wait",position:{x:0,y:0},config:{seconds:a}};return this.nodes.push(n),this.connectToLast(n.id),this}disconnect(){let a={id:this.generateId(),type:"disconnect",position:{x:0,y:0},config:{}};return this.nodes.push(a),this.connectToLast(a.id),this}build(){return{id:this.generateId(),name:"IVR Flow",nodes:this.nodes,connections:this.connections,startNodeId:this.startNodeId,version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}toContactFlow(){let a=[],n=new Map(this.nodes.map((s)=>[s.id,s]));for(let s of this.nodes){let c=this.nodeToAction(s,n);if(c)a.push(c)}let i={Version:"2019-10-30",StartAction:this.startNodeId,Actions:a};return JSON.stringify(i,null,2)}nodeToAction(a,n){let i=this.getNextNodeId(a.id),s={NextAction:i||"disconnect",Errors:[{NextAction:"disconnect"}]};switch(a.type){case"start":return null;case"play-prompt":return{Identifier:a.id,Type:"MessageParticipant",Parameters:{Text:a.config.text,TextType:a.config.textType},Transitions:s};case"get-input":return{Identifier:a.id,Type:"GetParticipantInput",Parameters:{Text:a.config.prompt,InputTimeLimitSeconds:a.config.timeout,MaxDigits:a.config.maxDigits},Transitions:{...s,Conditions:[]}};case"transfer-queue":return{Identifier:a.id,Type:"TransferToQueue",Parameters:{QueueId:a.config.queueArn},Transitions:s};case"transfer-phone":return{Identifier:a.id,Type:"TransferToPhoneNumber",Parameters:{PhoneNumber:a.config.phoneNumber},Transitions:s};case"invoke-lambda":return{Identifier:a.id,Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:a.config.functionArn,InvocationTimeLimitSeconds:a.config.timeout},Transitions:s};case"set-attribute":return{Identifier:a.id,Type:"UpdateContactAttributes",Parameters:{Attributes:{[a.config.key]:a.config.value}},Transitions:s};case"check-hours":return{Identifier:a.id,Type:"CheckHoursOfOperation",Parameters:{HoursOfOperationId:a.config.hoursOfOperationArn},Transitions:{NextAction:i,Conditions:[{NextAction:i,Condition:{Operator:"Equals",Operands:["True"]}}],Errors:[{NextAction:"disconnect"}]}};case"wait":return{Identifier:a.id,Type:"Wait",Parameters:{Seconds:a.config.seconds},Transitions:s};case"disconnect":return{Identifier:a.id,Type:"DisconnectParticipant",Parameters:{},Transitions:{}};default:return null}}connectToLast(a){if(this.nodes.length>1){let n=this.nodes[this.nodes.length-2];this.connections.push({id:this.generateId(),sourceNodeId:n.id,targetNodeId:a,sourcePort:"default"})}}getNextNodeId(a){return this.connections.find((n)=>n.sourceNodeId===a)?.targetNodeId||null}generateId(){return`node-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static Templates={basicSupport:()=>xe.create("Basic Support").start().playPrompt("Welcome to customer support.").menu("Press 1 for sales, 2 for support, or 3 to leave a message.",{"1":"sales","2":"support","3":"voicemail"}),afterHours:(a)=>xe.create("After Hours").start().playPrompt(a).recordVoicemail({greeting:"Please leave your name, number, and a brief message.",maxDuration:120}).playPrompt("Thank you for your message. Goodbye.").disconnect(),callbackRequest:(a)=>xe.create("Callback Request").start().playPrompt("All agents are currently busy.").getInput("Press 1 to request a callback, or 2 to wait.",{maxDigits:1}).invokeLambda(a).playPrompt("We will call you back shortly. Goodbye.").disconnect()}}class Zt{static MetricsAggregatorCode=`
5676
5676
  const { DynamoDBClient, PutItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
5677
5677
 
5678
5678
  const dynamodb = new DynamoDBClient({});
@@ -6161,7 +6161,7 @@ catch (error) {
6161
6161
  return { statusCode: 500, error: error.message };
6162
6162
  }
6163
6163
  };
6164
- `;static createCallbacksTable(a){return{[`${a.slug}CallbacksTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCallbackRequestLambda(a){return{[`${a.slug}CallbackRequestLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-callback-request`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:yt.CallbackRequestCode},Environment:{Variables:{CALLBACKS_TABLE:a.callbacksTable,NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||""}}}}}}static createCallbackProcessorLambda(a){return{[`${a.slug}CallbackProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-callback-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:yt.CallbackProcessorCode},Environment:{Variables:{CALLBACKS_TABLE:a.callbacksTable,CONNECT_INSTANCE_ID:a.connectInstanceId,CONTACT_FLOW_ID:a.contactFlowId,SOURCE_PHONE_NUMBER:a.sourcePhoneNumber,QUEUE_ID:a.queueId||""}}}}}}}var jf={};_e(jf,{AbTesting:()=>we,LinkTracking:()=>ra,MmsSupport:()=>ta,SmsAnalytics:()=>ea,SmsCampaigns:()=>Xt,SmsChatbot:()=>aa});class Xt{static CampaignManagerCode=`
6164
+ `;static createCallbacksTable(a){return{[`${a.slug}CallbacksTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${a.slug}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCallbackRequestLambda(a){return{[`${a.slug}CallbackRequestLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-callback-request`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:yt.CallbackRequestCode},Environment:{Variables:{CALLBACKS_TABLE:a.callbacksTable,NOTIFICATION_TOPIC_ARN:a.notificationTopicArn||""}}}}}}static createCallbackProcessorLambda(a){return{[`${a.slug}CallbackProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${a.slug}-callback-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:a.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:yt.CallbackProcessorCode},Environment:{Variables:{CALLBACKS_TABLE:a.callbacksTable,CONNECT_INSTANCE_ID:a.connectInstanceId,CONTACT_FLOW_ID:a.contactFlowId,SOURCE_PHONE_NUMBER:a.sourcePhoneNumber,QUEUE_ID:a.queueId||""}}}}}}}var jf={};Be(jf,{AbTesting:()=>we,LinkTracking:()=>ra,MmsSupport:()=>ta,SmsAnalytics:()=>ea,SmsCampaigns:()=>Xt,SmsChatbot:()=>aa});class Xt{static CampaignManagerCode=`
6165
6165
  const { DynamoDBClient, PutItemCommand, GetItemCommand, UpdateItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
6166
6166
 
6167
6167
  const dynamodb = new DynamoDBClient({});
@@ -7273,7 +7273,7 @@ export const queue = __handlers.queue
7273
7273
  export const cli = __handlers.cli
7274
7274
  `}var Xn=["adapter.ts","recursion.ts","auto-recursion.ts"];function ei(){return Le(Qn(Zn(import.meta.url)),"runtime")}function Kf(a,n,i){for(let s of a??[])i?.(`build: ${s}`),Fn(s,{stdio:"inherit",cwd:n})}function Ws(a){return Vn("sha256").update(a).digest("hex")}function dd(a,n,i){return`deployments/${a}/${n}/${i}.zip`}async function _r(a){let n=Yn(a.projectRoot??process.cwd()),{app:i}=a;if(!a.skipBuild)Kf(i.build,n,a.onStep);let s=i.entry;if(!s)throw Error("serverless app: `entry` is required to package a Node/Bun application");let c=Jn(s)?s:Le(n,s),l=Kn(Le(zn(),"tscloud-pkg-"));try{for(let C of Xn)jn(Le(ei(),C),Le(l,C));let u=Le(l,"bootstrap.ts");qn(u,zf({entryImport:c,adapterImport:"./adapter"})),a.onStep?.("bundling application");let h=await Bun.build({entrypoints:[u],target:i.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!h.success){let C=h.logs.map((T)=>String(T)).join(`
7275
7275
  `);throw Error(`serverless app bundle failed:
7276
- ${C}`)}let y=h.outputs[0],f=Buffer.from(await y.arrayBuffer()),S="index",b=hi([{name:`${S}.mjs`,data:f}]);return{zip:b,bundle:f,sha256:Ws(b),handlerFile:S,handlers:{http:i.handlers?.http??`${S}.http`,queue:i.handlers?.queue??`${S}.queue`,cli:i.handlers?.cli??`${S}.cli`},bundleBytes:f.length}}finally{Hn(l,{recursive:!0,force:!0})}}var Wf=["18","20","22"];function ti(a){if(!a)return"22";let n=String(a).match(/(\d+)/);return n?n[1]:"22"}function Js(a){let n=a.kind??"node";if(n==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:a.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(n==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:a.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let i=ti(a.runtimeVersion);if(a.runtime!=="provided.al2023"&&Wf.includes(i))return{lambdaRuntime:a.runtime&&a.runtime.startsWith("nodejs")?a.runtime:`nodejs${i}.x`,kind:"node",version:i,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:i,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function Gt(a,n,i){if(a.queues===!1)return[];if(a.queues===void 0||a.queues===!0)return[{name:`${n}-${i}-default`}];return a.queues.map((s)=>{if(typeof s==="string")return{name:`${n}-${i}-${s}`};let[c,l]=Object.entries(s)[0];return{name:`${n}-${i}-${c}`,concurrency:l}})}function ld(a,n,i){return Gt(a,n,i).map((s)=>s.name)}function ud(a){let{app:n,environment:i,handlers:s}=a,c=a.config.project.slug,l=Js(n).lambdaRuntime,u=n.architecture??"x86_64",h=a.config.project.region,y={http:`${c}-${i}-http`,queue:`${c}-${i}-queue`,cli:`${c}-${i}-cli`};if(n.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let f=Gt(n,c,i),S=f.map((z)=>z.name),b=S.length>0,C=n.logRetention??14,T=n.packaging==="image";if(T&&n.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let v=(n.scheduler??"on")!=="off",w=(n.cache?.driver??"dynamodb")==="dynamodb",R=Boolean(n.assets),k=Hs(c,i),W=n.tmpStorage??512,P={},V={},B=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:e.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${c}-${i}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${c}/${i}/*`),e.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${c}/${i}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[e.sub(`arn:aws:s3:::${k}`),e.sub(`arn:aws:s3:::${k}/*`),...n.storage?.bucket?[e.sub(`arn:aws:s3:::${n.storage.bucket}`),e.sub(`arn:aws:s3:::${n.storage.bucket}/*`)]:[]]}]}}];if(b)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${c}-${i}-*`)});if(w)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${c}-${i}-cache*`)});let j=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(n.vpc?.subnets?.length)j.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(n.lambdaInsights)j.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");P.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${c}-${i}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:j,Policies:B}};let Z=(z)=>({TSCLOUD_LAMBDA_MODE:z,TSCLOUD_ENV:i,...n.octane?{TSCLOUD_OCTANE:"1"}:{},...n.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...w?{TSCLOUD_CACHE_TABLE:`${c}-${i}-cache`}:{},...b?{TSCLOUD_QUEUE:S[0]}:{},...n.env??{}}),K=Boolean(n.efs),ee=typeof n.efs==="object"?n.efs:{},te=ee.mountPath??"/mnt/local",ie=K&&!ee.accessPointArn,me=ee.accessPointArn??(ie?e.getAtt("EfsAccessPoint","Arn"):void 0),ce=n.vpc?.subnets??[],ue=ce.length>0,se=n.cache?.driver==="elasticache"||n.database?.connection==="aurora-serverless"||Boolean(n.rdsProxy)||K;if(se&&!ue)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let Ie=ue?{VpcConfig:{SubnetIds:ce,SecurityGroupIds:[...n.vpc?.securityGroups??[],...se?[e.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},We=ie?ce.map((z,ne)=>`EfsMountTarget${ne}`):[],Ct=K?{FileSystemConfigs:[{Arn:me,LocalMountPath:te}]}:{};if(K)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function pe(z,ne,re,oe,ye,tt,Te,rt=W){P[`${z}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${ne}`,RetentionInDays:C}};let Tt=[...a.runtimeLayers??[],...n.lambdaInsights?[n.lambdaInsights.layerArn]:[]],vt=T?{PackageType:"Image",Code:{ImageUri:e.ref("ImageUri")},...n.kind==="php"?{}:{ImageConfig:{Command:[re]}}}:{Runtime:l,Handler:re,Code:{S3Bucket:e.ref("ArtifactBucket"),S3Key:e.ref("ArtifactKey")},...Tt.length?{Layers:[...new Set(Tt)]}:{}};P[z]={Type:"AWS::Lambda::Function",DependsOn:[`${z}LogGroup`,...We],Properties:{FunctionName:ne,Architectures:[u],MemorySize:ye,Timeout:tt,Role:e.getAtt("AppRole","Arn"),Environment:{Variables:Z(oe)},EphemeralStorage:{Size:rt},...vt,...Te!==void 0?{ReservedConcurrentExecutions:Te}:{},...Ie,...Ct}}}if(pe("HttpFunction",y.http,s.http,"http",n.memory??1024,n.timeout??28,n.concurrency,W),pe("CliFunction",y.cli,s.cli,"cli",n.cliMemory??1024,n.cliTimeout??900,void 0,n.cliTmpStorage??W),b)pe("QueueFunction",y.queue,s.queue,"queue",n.queueMemory??1024,n.queueTimeout??120,void 0,n.queueTmpStorage??W);let de=(n.provisionedConcurrency??0)>0?n.provisionedConcurrency:0,ge=["HttpFunction","CliFunction",...b?["QueueFunction"]:[]];if(de)for(let z of ge)P[`${z}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:e.ref(z)}},P[`${z}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:e.ref(z),Name:"live",FunctionVersion:e.getAtt(`${z}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:de}}};let Re=(z)=>de?e.ref(`${z}Alias`):e.getAtt(z,"Arn"),he=(z)=>de?e.ref(`${z}Alias`):e.ref(z);P.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${c}-${i}`,ProtocolType:"HTTP"}},P.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:e.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:Re("HttpFunction"),PayloadFormatVersion:"2.0"}},P.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:e.ref("HttpApi"),RouteKey:"$default",Target:e.join("/",["integrations",e.ref("HttpIntegration")])}},P.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},P.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:he("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},V.HttpApiEndpoint={Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint")},V.HttpApiId={Description:"HTTP API id",Value:e.ref("HttpApi")};let Ae=(Array.isArray(n.domain)?n.domain:n.domain?[n.domain]:[]).filter(Boolean);if(Ae.length){if(!n.certificateArn&&!n.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let z=n.certificateArn;if(!z)P.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:Ae[0],...Ae.length>1?{SubjectAlternativeNames:Ae.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:Ae.map((ne)=>({DomainName:ne,HostedZoneId:n.hostedZoneId}))}},z=e.ref("HttpCertificate");Ae.forEach((ne,re)=>{let oe=`HttpDomain${re}`;if(P[oe]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:ne,DomainNameConfigurations:[{CertificateArn:z,EndpointType:"REGIONAL"}]}},P[`HttpApiMapping${re}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:e.ref("HttpApi"),DomainName:e.ref(oe),Stage:"$default"}},n.hostedZoneId)P[`HttpDomainRecord${re}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:ne,Type:"A",AliasTarget:{DNSName:e.getAtt(oe,"RegionalDomainName"),HostedZoneId:e.getAtt(oe,"RegionalHostedZoneId")}}};V[`CustomDomain${re}`]={Description:`Custom domain ${ne}`,Value:ne},V[`CustomDomainTarget${re}`]={Description:`Point ${ne} (CNAME/alias) at this APIGW regional domain`,Value:e.getAtt(oe,"RegionalDomainName")}})}if(b)P.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${c}-${i}-dlq`,MessageRetentionPeriod:1209600}},f.forEach((z,ne)=>{let re=`AppQueue${ne}`,oe=n.queueTimeout??120;P[re]={Type:"AWS::SQS::Queue",Properties:{QueueName:z.name,VisibilityTimeout:Math.min(43200,oe*6),RedrivePolicy:{deadLetterTargetArn:e.getAtt("AppQueueDlq","Arn"),maxReceiveCount:n.queueTries??3}}};let ye=z.concurrency??n.queueConcurrency;P[`${re}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:e.getAtt(re,"Arn"),FunctionName:he("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...ye?{ScalingConfig:{MaximumConcurrency:Math.max(2,ye)}}:{}}},V[`QueueUrl${ne}`]={Description:`Queue URL: ${z.name}`,Value:e.ref(re)}});if(v)P.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${i}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:Re("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},P.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:he("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt("SchedulerRule","Arn")}};if(n.warm&&n.warm>0){let z={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},ne=(n.warmFunctions??["http"]).filter((re)=>re!=="queue"||b);for(let re of ne){let oe=re.charAt(0).toUpperCase()+re.slice(1),ye=Math.ceil(n.warm/5),tt=0;for(let Te=0;Te<ye;Te++){let rt=Math.min(5,n.warm-tt);P[`Warmer${oe}Rule${Te}`]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${i}-warmer-${re}-${Te}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:rt},(Tt,vt)=>({Id:`warm-${re}-${Te}-${vt}`,Arn:e.getAtt(z[re],"Arn"),Input:JSON.stringify({warmer:!0})}))}},tt+=rt}P[`Warmer${oe}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:e.ref(z[re]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${c}-${i}-warmer-${re}-*`)}}}}if(w)P.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-${i}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},V.CacheTableName={Description:"DynamoDB cache table",Value:e.ref("CacheTable")};if(R){if(P.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:k,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},P.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${c}-${i}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},P.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:e.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:e.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...n.assetDomain?{Aliases:[n.assetDomain],ViewerCertificate:{AcmCertificateArn:n.assetCertificateArn??e.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},n.assetDomain){if(!n.assetCertificateArn){if(!n.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(h!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${h}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);P.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:n.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:n.assetDomain,HostedZoneId:n.hostedZoneId}]}}}if(n.hostedZoneId)P.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:n.assetDomain,Type:"A",AliasTarget:{DNSName:e.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};V.AssetDomain={Description:"Custom asset CDN host",Value:n.assetDomain}}P.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:e.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:e.sub(`arn:aws:s3:::${k}/*`),Condition:{StringEquals:{"AWS:SourceArn":e.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},V.AssetsBucketName={Description:"Assets bucket",Value:e.ref("AssetsBucket")},V.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:e.getAtt("AssetsDistribution","DomainName")}}if(n.firewall?.enabled){let z=[],ne=0;if(n.firewall.rateLimit)z.push({Name:"rate-limit",Priority:ne++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:n.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${i}-rate`}});let re={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let oe of n.firewall.rules??[]){let ye=re[oe];if(!ye)continue;z.push({Name:`managed-${oe}`,Priority:ne++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:ye}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${i}-${oe}`}})}P.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${c}-${i}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:z,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${i}-waf`}}},V.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:e.getAtt("WebAcl","Arn")}}if(ue&&se){if(!n.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");P.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:n.vpc.id,GroupDescription:`${c}-${i} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(ie)P.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${c}-${i}-efs`}]}},ce.forEach((z,ne)=>{P[`EfsMountTarget${ne}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:e.ref("EfsFileSystem"),SubnetId:z,SecurityGroups:[e.getAtt("DataSecurityGroup","GroupId")]}}}),P.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:e.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},V.EfsFileSystemId={Description:"EFS file system id",Value:e.ref("EfsFileSystem")};if(n.cache?.driver==="elasticache")P.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${c}-${i} cache subnets`,SubnetIds:ce}},P.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${c}-${i}-cache`,ReplicationGroupDescription:`${c}-${i} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},V.CacheEndpoint={Description:"Redis primary endpoint",Value:e.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(n.database?.connection==="aurora-serverless")P.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${c}-${i} db subnets`,SubnetIds:ce}},P.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${c}/${i}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},P.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${c}-${i}-db`,DatabaseName:"app",MasterUsername:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:n.database?.minCapacity??0.5,MaxCapacity:n.database?.maxCapacity??4},DBSubnetGroupName:e.ref("DbSubnetGroup"),VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")]}},P.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:e.ref("DbCluster")}},V.DbEndpoint={Description:"Aurora cluster endpoint",Value:e.getAtt("DbCluster","Endpoint.Address")};if(n.rdsProxy&&n.database?.connection==="aurora-serverless")P.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:e.ref("DbSecret")}]}}]}},P.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof n.rdsProxy==="object"&&n.rdsProxy.name?n.rdsProxy.name:`${c}-${i}-proxy`,EngineFamily:"MYSQL",RoleArn:e.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:e.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:ce,VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},P.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:e.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[e.ref("DbCluster")]}},V.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:e.getAtt("DbProxy","Endpoint")};if(V.HttpFunctionName={Description:"HTTP function name",Value:e.ref("HttpFunction")},V.CliFunctionName={Description:"CLI function name",Value:e.ref("CliFunction")},b)V.QueueFunctionName={Description:"Queue function name",Value:e.ref("QueueFunction")};let $e={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${a.config.project.name} (${c}-${i})`,Parameters:T?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:P,Outputs:V},Ge={};for(let z of Object.values(P))Ge[z.Type]=(Ge[z.Type]??0)+1;return{template:$e,functionNames:y,queueNames:S,resourceSummary:Ge}}var Jf=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function Xf(a){let n=`php${a.replace(".","")}`;return Jf.map((i)=>`${n}-php-${i}`)}function Og(a,n){let i=`php${a.replace(".","")}`,s=Xf(a).join(" \\\n "),c=`/opt/remi/${i}/root`,l=`/etc/opt/remi/${i}`;return`${n?`FROM almalinux:9 AS ${n}`:"FROM almalinux:9"}
7276
+ ${C}`)}let y=h.outputs[0],f=Buffer.from(await y.arrayBuffer()),S="index",b=hi([{name:`${S}.mjs`,data:f}]);return{zip:b,bundle:f,sha256:Ws(b),handlerFile:S,handlers:{http:i.handlers?.http??`${S}.http`,queue:i.handlers?.queue??`${S}.queue`,cli:i.handlers?.cli??`${S}.cli`},bundleBytes:f.length}}finally{Hn(l,{recursive:!0,force:!0})}}var Wf=["18","20","22"];function ti(a){if(!a)return"22";let n=String(a).match(/(\d+)/);return n?n[1]:"22"}function Js(a){let n=a.kind??"node";if(n==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:a.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(n==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:a.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let i=ti(a.runtimeVersion);if(a.runtime!=="provided.al2023"&&Wf.includes(i))return{lambdaRuntime:a.runtime&&a.runtime.startsWith("nodejs")?a.runtime:`nodejs${i}.x`,kind:"node",version:i,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:i,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function Gt(a,n,i){if(a.queues===!1)return[];if(a.queues===void 0||a.queues===!0)return[{name:`${n}-${i}-default`}];return a.queues.map((s)=>{if(typeof s==="string")return{name:`${n}-${i}-${s}`};let[c,l]=Object.entries(s)[0];return{name:`${n}-${i}-${c}`,concurrency:l}})}function ld(a,n,i){return Gt(a,n,i).map((s)=>s.name)}function ud(a){let{app:n,environment:i,handlers:s}=a,c=a.config.project.slug,l=Js(n).lambdaRuntime,u=n.architecture??"x86_64",h=a.config.project.region,y={http:`${c}-${i}-http`,queue:`${c}-${i}-queue`,cli:`${c}-${i}-cli`};if(n.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let f=Gt(n,c,i),S=f.map((z)=>z.name),b=S.length>0,C=n.logRetention??14,T=n.packaging==="image";if(T&&n.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let v=(n.scheduler??"on")!=="off",w=(n.cache?.driver??"dynamodb")==="dynamodb",R=Boolean(n.assets),k=Hs(c,i),W=n.tmpStorage??512,P={},V={},B=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:e.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${c}-${i}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${c}/${i}/*`),e.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${c}/${i}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[e.sub(`arn:aws:s3:::${k}`),e.sub(`arn:aws:s3:::${k}/*`),...n.storage?.bucket?[e.sub(`arn:aws:s3:::${n.storage.bucket}`),e.sub(`arn:aws:s3:::${n.storage.bucket}/*`)]:[]]}]}}];if(b)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${c}-${i}-*`)});if(w)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${c}-${i}-cache*`)});let j=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(n.vpc?.subnets?.length)j.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(n.lambdaInsights)j.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");P.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${c}-${i}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:j,Policies:B}};let J=(z)=>({TSCLOUD_LAMBDA_MODE:z,TSCLOUD_ENV:i,...n.octane?{TSCLOUD_OCTANE:"1"}:{},...n.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...w?{TSCLOUD_CACHE_TABLE:`${c}-${i}-cache`}:{},...b?{TSCLOUD_QUEUE:S[0]}:{},...n.env??{}}),K=Boolean(n.efs),ee=typeof n.efs==="object"?n.efs:{},te=ee.mountPath??"/mnt/local",ne=K&&!ee.accessPointArn,me=ee.accessPointArn??(ne?e.getAtt("EfsAccessPoint","Arn"):void 0),oe=n.vpc?.subnets??[],ue=oe.length>0,ie=n.cache?.driver==="elasticache"||n.database?.connection==="aurora-serverless"||Boolean(n.rdsProxy)||K;if(ie&&!ue)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let Ie=ue?{VpcConfig:{SubnetIds:oe,SecurityGroupIds:[...n.vpc?.securityGroups??[],...ie?[e.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},_e=ne?oe.map((z,re)=>`EfsMountTarget${re}`):[],Ct=K?{FileSystemConfigs:[{Arn:me,LocalMountPath:te}]}:{};if(K)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function pe(z,re,ae,se,ye,tt,Te,at=W){P[`${z}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${re}`,RetentionInDays:C}};let Tt=[...a.runtimeLayers??[],...n.lambdaInsights?[n.lambdaInsights.layerArn]:[]],vt=T?{PackageType:"Image",Code:{ImageUri:e.ref("ImageUri")},...n.kind==="php"?{}:{ImageConfig:{Command:[ae]}}}:{Runtime:l,Handler:ae,Code:{S3Bucket:e.ref("ArtifactBucket"),S3Key:e.ref("ArtifactKey")},...Tt.length?{Layers:[...new Set(Tt)]}:{}};P[z]={Type:"AWS::Lambda::Function",DependsOn:[`${z}LogGroup`,..._e],Properties:{FunctionName:re,Architectures:[u],MemorySize:ye,Timeout:tt,Role:e.getAtt("AppRole","Arn"),Environment:{Variables:J(se)},EphemeralStorage:{Size:at},...vt,...Te!==void 0?{ReservedConcurrentExecutions:Te}:{},...Ie,...Ct}}}if(pe("HttpFunction",y.http,s.http,"http",n.memory??1024,n.timeout??28,n.concurrency,W),pe("CliFunction",y.cli,s.cli,"cli",n.cliMemory??1024,n.cliTimeout??900,void 0,n.cliTmpStorage??W),b)pe("QueueFunction",y.queue,s.queue,"queue",n.queueMemory??1024,n.queueTimeout??120,void 0,n.queueTmpStorage??W);let de=(n.provisionedConcurrency??0)>0?n.provisionedConcurrency:0,ge=["HttpFunction","CliFunction",...b?["QueueFunction"]:[]];if(de)for(let z of ge)P[`${z}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:e.ref(z)}},P[`${z}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:e.ref(z),Name:"live",FunctionVersion:e.getAtt(`${z}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:de}}};let Re=(z)=>de?e.ref(`${z}Alias`):e.getAtt(z,"Arn"),he=(z)=>de?e.ref(`${z}Alias`):e.ref(z);P.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${c}-${i}`,ProtocolType:"HTTP"}},P.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:e.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:Re("HttpFunction"),PayloadFormatVersion:"2.0"}},P.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:e.ref("HttpApi"),RouteKey:"$default",Target:e.join("/",["integrations",e.ref("HttpIntegration")])}},P.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},P.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:he("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},V.HttpApiEndpoint={Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint")},V.HttpApiId={Description:"HTTP API id",Value:e.ref("HttpApi")};let Ae=(Array.isArray(n.domain)?n.domain:n.domain?[n.domain]:[]).filter(Boolean);if(Ae.length){if(!n.certificateArn&&!n.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let z=n.certificateArn;if(!z)P.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:Ae[0],...Ae.length>1?{SubjectAlternativeNames:Ae.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:Ae.map((re)=>({DomainName:re,HostedZoneId:n.hostedZoneId}))}},z=e.ref("HttpCertificate");Ae.forEach((re,ae)=>{let se=`HttpDomain${ae}`;if(P[se]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:re,DomainNameConfigurations:[{CertificateArn:z,EndpointType:"REGIONAL"}]}},P[`HttpApiMapping${ae}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:e.ref("HttpApi"),DomainName:e.ref(se),Stage:"$default"}},n.hostedZoneId)P[`HttpDomainRecord${ae}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:re,Type:"A",AliasTarget:{DNSName:e.getAtt(se,"RegionalDomainName"),HostedZoneId:e.getAtt(se,"RegionalHostedZoneId")}}};V[`CustomDomain${ae}`]={Description:`Custom domain ${re}`,Value:re},V[`CustomDomainTarget${ae}`]={Description:`Point ${re} (CNAME/alias) at this APIGW regional domain`,Value:e.getAtt(se,"RegionalDomainName")}})}if(b)P.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${c}-${i}-dlq`,MessageRetentionPeriod:1209600}},f.forEach((z,re)=>{let ae=`AppQueue${re}`,se=n.queueTimeout??120;P[ae]={Type:"AWS::SQS::Queue",Properties:{QueueName:z.name,VisibilityTimeout:Math.min(43200,se*6),RedrivePolicy:{deadLetterTargetArn:e.getAtt("AppQueueDlq","Arn"),maxReceiveCount:n.queueTries??3}}};let ye=z.concurrency??n.queueConcurrency;P[`${ae}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:e.getAtt(ae,"Arn"),FunctionName:he("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...ye?{ScalingConfig:{MaximumConcurrency:Math.max(2,ye)}}:{}}},V[`QueueUrl${re}`]={Description:`Queue URL: ${z.name}`,Value:e.ref(ae)}});if(v)P.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${i}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:Re("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},P.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:he("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt("SchedulerRule","Arn")}};if(n.warm&&n.warm>0){let z={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},re=(n.warmFunctions??["http"]).filter((ae)=>ae!=="queue"||b);for(let ae of re){let se=ae.charAt(0).toUpperCase()+ae.slice(1),ye=Math.ceil(n.warm/5),tt=0;for(let Te=0;Te<ye;Te++){let at=Math.min(5,n.warm-tt);P[`Warmer${se}Rule${Te}`]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${i}-warmer-${ae}-${Te}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:at},(Tt,vt)=>({Id:`warm-${ae}-${Te}-${vt}`,Arn:e.getAtt(z[ae],"Arn"),Input:JSON.stringify({warmer:!0})}))}},tt+=at}P[`Warmer${se}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:e.ref(z[ae]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${c}-${i}-warmer-${ae}-*`)}}}}if(w)P.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-${i}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},V.CacheTableName={Description:"DynamoDB cache table",Value:e.ref("CacheTable")};if(R){if(P.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:k,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},P.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${c}-${i}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},P.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:e.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:e.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...n.assetDomain?{Aliases:[n.assetDomain],ViewerCertificate:{AcmCertificateArn:n.assetCertificateArn??e.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},n.assetDomain){if(!n.assetCertificateArn){if(!n.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(h!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${h}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);P.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:n.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:n.assetDomain,HostedZoneId:n.hostedZoneId}]}}}if(n.hostedZoneId)P.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:n.assetDomain,Type:"A",AliasTarget:{DNSName:e.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};V.AssetDomain={Description:"Custom asset CDN host",Value:n.assetDomain}}P.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:e.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:e.sub(`arn:aws:s3:::${k}/*`),Condition:{StringEquals:{"AWS:SourceArn":e.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},V.AssetsBucketName={Description:"Assets bucket",Value:e.ref("AssetsBucket")},V.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:e.getAtt("AssetsDistribution","DomainName")}}if(n.firewall?.enabled){let z=[],re=0;if(n.firewall.rateLimit)z.push({Name:"rate-limit",Priority:re++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:n.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${i}-rate`}});let ae={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let se of n.firewall.rules??[]){let ye=ae[se];if(!ye)continue;z.push({Name:`managed-${se}`,Priority:re++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:ye}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${i}-${se}`}})}P.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${c}-${i}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:z,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${i}-waf`}}},V.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:e.getAtt("WebAcl","Arn")}}if(ue&&ie){if(!n.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");P.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:n.vpc.id,GroupDescription:`${c}-${i} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(ne)P.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${c}-${i}-efs`}]}},oe.forEach((z,re)=>{P[`EfsMountTarget${re}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:e.ref("EfsFileSystem"),SubnetId:z,SecurityGroups:[e.getAtt("DataSecurityGroup","GroupId")]}}}),P.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:e.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},V.EfsFileSystemId={Description:"EFS file system id",Value:e.ref("EfsFileSystem")};if(n.cache?.driver==="elasticache")P.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${c}-${i} cache subnets`,SubnetIds:oe}},P.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${c}-${i}-cache`,ReplicationGroupDescription:`${c}-${i} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},V.CacheEndpoint={Description:"Redis primary endpoint",Value:e.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(n.database?.connection==="aurora-serverless")P.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${c}-${i} db subnets`,SubnetIds:oe}},P.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${c}/${i}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},P.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${c}-${i}-db`,DatabaseName:"app",MasterUsername:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:n.database?.minCapacity??0.5,MaxCapacity:n.database?.maxCapacity??4},DBSubnetGroupName:e.ref("DbSubnetGroup"),VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")]}},P.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:e.ref("DbCluster")}},V.DbEndpoint={Description:"Aurora cluster endpoint",Value:e.getAtt("DbCluster","Endpoint.Address")};if(n.rdsProxy&&n.database?.connection==="aurora-serverless")P.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:e.ref("DbSecret")}]}}]}},P.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof n.rdsProxy==="object"&&n.rdsProxy.name?n.rdsProxy.name:`${c}-${i}-proxy`,EngineFamily:"MYSQL",RoleArn:e.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:e.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:oe,VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},P.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:e.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[e.ref("DbCluster")]}},V.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:e.getAtt("DbProxy","Endpoint")};if(V.HttpFunctionName={Description:"HTTP function name",Value:e.ref("HttpFunction")},V.CliFunctionName={Description:"CLI function name",Value:e.ref("CliFunction")},b)V.QueueFunctionName={Description:"Queue function name",Value:e.ref("QueueFunction")};let $e={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${a.config.project.name} (${c}-${i})`,Parameters:T?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:P,Outputs:V},We={};for(let z of Object.values(P))We[z.Type]=(We[z.Type]??0)+1;return{template:$e,functionNames:y,queueNames:S,resourceSummary:We}}var Jf=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function Xf(a){let n=`php${a.replace(".","")}`;return Jf.map((i)=>`${n}-php-${i}`)}function Og(a,n){let i=`php${a.replace(".","")}`,s=Xf(a).join(" \\\n "),c=`/opt/remi/${i}/root`,l=`/etc/opt/remi/${i}`;return`${n?`FROM almalinux:9 AS ${n}`:"FROM almalinux:9"}
7277
7277
 
7278
7278
  # Build PHP on AlmaLinux 9 (where Remi's version-isolated SCL packages install
7279
7279
  # cleanly — Remi's release RPM rejects Amazon Linux 2023). AlmaLinux 9 shares
@@ -7334,7 +7334,7 @@ COPY app/ \${LAMBDA_TASK_ROOT}/
7334
7334
 
7335
7335
  # Per-function CMD (e.g. index.http) is supplied via ImageConfig.Command.
7336
7336
  CMD [ "index.http" ]
7337
- `}function Ba(){return ai(ri(import.meta.url))}function Lg(){return At(Pe(Ba(),"runtime.mjs"),"utf-8")}function _a(a){return At(Pe(Ba(),`${a}-bootstrap`),"utf-8")}function $C(a){let n=a.architecture??"x86_64",i=n==="arm64"?"arm64":"x64",s=a.version.replace(/^v/,""),c=a.onStep??(()=>{}),l=Ma(Pe(Oa(),"tscloud-node-layer-"));try{let u=s.includes(".")?s:ni(s),h=`node-v${u}-linux-${i}`,y=`https://nodejs.org/dist/v${u}/${h}.tar.xz`;c(`downloading Node ${u} (${n})`);let f=Pe(l,"node.tar.xz");Wa(y,f),c("extracting node binary"),bt("tar",["-xf",f,"-C",l,`${h}/bin/node`],{stdio:"inherit"});let S=At(Pe(l,h,"bin","node"));c("packaging layer");let b=[{name:"bootstrap",data:_a("node"),mode:493},{name:"runtime.mjs",data:Lg(),mode:420},{name:"bin/node",data:S,mode:493}];return{zip:hi(b),architecture:n,version:u,fileCount:b.length}}finally{xa(l,{recursive:!0,force:!0})}}function MC(a){let n=a.architecture??"x86_64",i=n==="arm64"?"bun-linux-aarch64":"bun-linux-x64",s=a.version==="latest"?"":a.version.replace(/^v/,""),c=a.onStep??(()=>{}),l=Ma(Pe(Oa(),"tscloud-bun-layer-"));try{let u=s?`https://github.com/oven-sh/bun/releases/download/bun-v${s}/${i}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${i}.zip`;c(`downloading Bun ${s||"latest"} (${n})`);let h=Pe(l,"bun.zip");Wa(u,h),c("extracting bun binary"),bt("unzip",["-o","-q",h,"-d",l],{stdio:"inherit"});let y=At(Pe(l,i,"bun"));c("packaging layer");let f=[{name:"bootstrap",data:_a("bun"),mode:493},{name:"runtime.mjs",data:Lg(),mode:420},{name:"bin/bun",data:y,mode:493}];return{zip:hi(f),architecture:n,version:s||"latest",fileCount:f.length}}finally{xa(l,{recursive:!0,force:!0})}}function Wa(a,n){bt("curl",["-fsSL","-o",n,a],{stdio:["ignore","ignore","inherit"]})}function ni(a){let n=bt("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),i=JSON.parse(n).find((s)=>s.version.startsWith(`v${a}.`));if(!i)throw Error(`No Node release found for major version ${a}`);return i.version.replace(/^v/,"")}var Xs="x-ts-cloud-invoke-depth",Ys="x-ts-cloud-invoke-chain",Zs="x-ts-cloud-trace-id";function gd(a){return si("sha256").update(a).digest("hex").slice(0,8)}var fi={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function Dt(a,n){if(typeof a.get==="function")return a.get(n)??void 0;let i=a;return i[n]??i[n.toLowerCase()]??i[n.toUpperCase()]}function md(a,n=64){if(!a)return[];return a.split(".").map((i)=>i.trim()).filter((i)=>/^[0-9a-f]{8}$/.test(i)).slice(-n)}function hd(a,n=fi){let i=gd(a.functionId),s=md(Dt(a.headers,Ys)),c=a.traceId??Dt(a.headers,Zs)??crypto.randomUUID(),l=[...s,i],u=s.filter((b)=>b===i).length,h=s[s.length-1]===i,y=Number.parseInt(Dt(a.headers,Xs)??"",10),f=Math.max(l.length,Number.isFinite(y)?y+1:0),S="ok";if(f>n.maxDepth)S="depth_exceeded";else if(u>=n.maxRepeats)S="cycle_detected";else if(h&&n.maxRepeats<=1)S="self_invocation";return{reason:S,depth:f,chain:l,traceId:c,selfInvocation:h,repeats:u,propagate:{[Xs]:String(f),[Ys]:l.join("."),[Zs]:c}}}var Ga={ok:"",depth_exceeded:"Invocation chain is deeper than the configured limit; the call was refused to stop a runaway loop.",cycle_detected:"This function already appears in the invocation chain; the call was refused as a recursion loop.",self_invocation:"This function invoked itself directly; the call was refused.",trace_budget_exceeded:"This request has already made more invocations than its budget allows.",breaker_open:"Recursion protection is open for this function after repeated loop detections."};class eo{limits;clock;traces=new Map;breakers=new Map;constructor(a=fi,n=()=>Date.now()){this.limits=a,this.clock=n}check(a){let n=this.clock();this.expireTraces(n);let i=hd(a,this.limits),s=this.breakers.get(a.functionId);if(s?.openUntil!=null&&s.openUntil>n)return this.deny(a.functionId,i,"breaker_open",n,!1);if(i.reason!=="ok")return this.deny(a.functionId,i,i.reason,n,!0);let c=this.traces.get(i.traceId)??{count:0,firstAt:n};if(c.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(i.traceId,c),this.deny(a.functionId,i,"trace_budget_exceeded",n,!0);if(this.traces.set(i.traceId,{count:c.count+1,firstAt:c.firstAt}),s)this.breakers.set(a.functionId,{consecutiveBlocks:0});return{...i,allowed:!0,reason:"ok",propagate:i.propagate}}deny(a,n,i,s,c){if(c){let l=this.breakers.get(a)??{consecutiveBlocks:0},u=l.consecutiveBlocks+1;this.breakers.set(a,{consecutiveBlocks:u,openUntil:u>=this.limits.breakerThreshold?s+this.limits.breakerCooldownMs:l.openUntil})}return{...n,allowed:!1,reason:i,message:Ga[i]}}breakerOpen(a){let n=this.breakers.get(a);return n?.openUntil!=null&&n.openUntil>this.clock()}reset(a){if(a){this.breakers.delete(a);return}this.breakers.clear(),this.traces.clear()}expireTraces(a){if(this.traces.size===0)return;for(let[n,i]of this.traces)if(a-i.firstAt>this.limits.traceWindowMs)this.traces.delete(n)}get trackedTraces(){return this.traces.size}}function fd(a){return{...a.propagate}}function Ad(a){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":a.reason},body:{error:"recursion_blocked",reason:a.reason,message:a.message??Ga[a.reason],depth:a.depth,traceId:a.traceId}}}var $g=new ii;function pa(a){let n=globalThis.process?.env?.[a];if(n==null||n==="")return;return n!=="0"&&n.toLowerCase()!=="false"}function oi(){let a=globalThis.process?.env??{};return a.TS_CLOUD_FUNCTION_ID||a.AWS_LAMBDA_FUNCTION_NAME||a.FUNCTION_NAME||"function"}function Zf(a){let n=a===!1?{enabled:!1}:a??{},i=pa("TS_CLOUD_RECURSION_PROTECTION"),s=pa("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:i??n.enabled??!0,detectionOnly:s??n.detectionOnly??!1,limits:{...fi,...n.limits},functionId:n.functionId??oi()}}var De,fe;function eA(){let a=globalThis.fetch;if(!a||De===a)return()=>{};fe=a;let n=async(i,s)=>{let c=$g.getStore();if(!c)return fe(i,s);let l=new Headers(s?.headers??(i instanceof Request?i.headers:void 0));for(let[u,h]of Object.entries(fd(c)))l.set(u,h);if(i instanceof Request)return fe(new Request(i,{headers:l}),s);return fe(i,{...s,headers:l})};return Object.assign(n,a),globalThis.fetch=n,De=n,()=>{if(globalThis.fetch===De&&fe)globalThis.fetch=fe;De=void 0}}var ut,xt;function tA(a){if(!ut||JSON.stringify(xt)!==JSON.stringify(a))ut=new eo(a),xt=a;return ut}function FC(){if(ut=void 0,xt=void 0,De&&fe&&globalThis.fetch===De)globalThis.fetch=fe;De=void 0,fe=void 0}function rA(a,n){let i=Zf(n);if(!i.enabled)return;let s=tA(i.limits),c={functionId:i.functionId,headers:a},l=s.check(c);return{verdict:l,blocked:!l.allowed&&!i.detectionOnly,observed:!l.allowed&&i.detectionOnly}}function nA(a,n){return eA(),$g.run(a,n)}function UC(a){let n=a,i=n?.default??n;if(typeof i==="function")return{fetch:i};return{fetch:i?.fetch??n?.fetch,queue:i?.queue??n?.queue,cli:i?.cli??n?.cli}}var ci=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function li(a){if(!a)return!0;return ci.test(a)}function di(a){if(a?.maintenance)return a.maintenance;let n=globalThis.process?.env??{};return{enabled:n.MAINTENANCE_MODE==="1"||n.MAINTENANCE_MODE==="true",bypassSecret:n.MAINTENANCE_BYPASS_SECRET}}function iA(a){let n=a.requestContext?.domainName??"localhost",i=a.rawQueryString?`?${a.rawQueryString}`:"",s=`https://${n}${a.rawPath||"/"}${i}`,c=new Headers;for(let[h,y]of Object.entries(a.headers??{}))if(y!==void 0)c.set(h,y);if(a.cookies?.length)c.set("cookie",a.cookies.join("; "));let l=a.requestContext.http.method,u;if(a.body!==void 0&&l!=="GET"&&l!=="HEAD")u=a.isBase64Encoded?new Uint8Array(Buffer.from(a.body,"base64")):new TextEncoder().encode(a.body);return new Request(s,{method:l,headers:c,body:u})}async function Mg(a){let n={},i=[],s=typeof a.headers.getSetCookie==="function"?a.headers.getSetCookie():[];for(let u of s)i.push(u);a.headers.forEach((u,h)=>{if(h.toLowerCase()==="set-cookie")return;n[h]=u});let c=Buffer.from(await a.arrayBuffer()),l=li(a.headers.get("content-type"));return{statusCode:a.status,headers:n,...i.length?{cookies:i}:{},body:l?c.toString("utf-8"):c.toString("base64"),isBase64Encoded:!l}}function sA(a,n){return async(i)=>{if(i.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!a)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let s=di(n);if(s.enabled){let u=i.headers?.["x-maintenance-bypass"]??i.cookies?.find((h)=>h.startsWith("tscloud_bypass="))?.split("=")[1];if(!s.bypassSecret||u!==s.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let c=rA(i.headers??{},n?.recursionProtection);if(c?.blocked){let u=Ad(c.verdict);return{statusCode:u.status,headers:{...u.headers,"retry-after":"60"},body:JSON.stringify(u.body),isBase64Encoded:!1}}let l=iA(i);if(!c){let u=await a(l);return Mg(u)}if(c.observed)console.warn(`[ts-cloud] recursion detected (${c.verdict.reason}) at depth ${c.verdict.depth}; detection-only mode let it run`);return nA(c.verdict,async()=>Mg(await a(l)))}}function yi(a){try{return JSON.parse(a)}catch{return a}}function oA(a){return async(n)=>{let i=[];if(n.warmer)return{batchItemFailures:i};if(!a)return{batchItemFailures:i};for(let s of n.Records??[])try{await a(yi(s.body),s)}catch{i.push({itemIdentifier:s.messageId})}return{batchItemFailures:i}}}function aA(a){return async(n)=>{if(n.warmer)return{statusCode:0,output:"warm"};if(!a)return{statusCode:501,output:"No CLI handler configured"};return a(n)}}function QC(a,n){return{http:sA(a.fetch,n),queue:oA(a.queue),cli:aA(a.cli)}}function cA(a={}){let n=a.socketPath??"/tmp/.tscloud-fpm.sock",i=a.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
7337
+ `}function Ba(){return ai(ri(import.meta.url))}function Lg(){return At(Pe(Ba(),"runtime.mjs"),"utf-8")}function _a(a){return At(Pe(Ba(),`${a}-bootstrap`),"utf-8")}function $C(a){let n=a.architecture??"x86_64",i=n==="arm64"?"arm64":"x64",s=a.version.replace(/^v/,""),c=a.onStep??(()=>{}),l=Ma(Pe(Oa(),"tscloud-node-layer-"));try{let u=s.includes(".")?s:ni(s),h=`node-v${u}-linux-${i}`,y=`https://nodejs.org/dist/v${u}/${h}.tar.xz`;c(`downloading Node ${u} (${n})`);let f=Pe(l,"node.tar.xz");Wa(y,f),c("extracting node binary"),bt("tar",["-xf",f,"-C",l,`${h}/bin/node`],{stdio:"inherit"});let S=At(Pe(l,h,"bin","node"));c("packaging layer");let b=[{name:"bootstrap",data:_a("node"),mode:493},{name:"runtime.mjs",data:Lg(),mode:420},{name:"bin/node",data:S,mode:493}];return{zip:hi(b),architecture:n,version:u,fileCount:b.length}}finally{xa(l,{recursive:!0,force:!0})}}function MC(a){let n=a.architecture??"x86_64",i=n==="arm64"?"bun-linux-aarch64":"bun-linux-x64",s=a.version==="latest"?"":a.version.replace(/^v/,""),c=a.onStep??(()=>{}),l=Ma(Pe(Oa(),"tscloud-bun-layer-"));try{let u=s?`https://github.com/oven-sh/bun/releases/download/bun-v${s}/${i}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${i}.zip`;c(`downloading Bun ${s||"latest"} (${n})`);let h=Pe(l,"bun.zip");Wa(u,h),c("extracting bun binary"),bt("unzip",["-o","-q",h,"-d",l],{stdio:"inherit"});let y=At(Pe(l,i,"bun"));c("packaging layer");let f=[{name:"bootstrap",data:_a("bun"),mode:493},{name:"runtime.mjs",data:Lg(),mode:420},{name:"bin/bun",data:y,mode:493}];return{zip:hi(f),architecture:n,version:s||"latest",fileCount:f.length}}finally{xa(l,{recursive:!0,force:!0})}}function Wa(a,n){bt("curl",["-fsSL","-o",n,a],{stdio:["ignore","ignore","inherit"]})}function ni(a){let n=bt("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),i=JSON.parse(n).find((s)=>s.version.startsWith(`v${a}.`));if(!i)throw Error(`No Node release found for major version ${a}`);return i.version.replace(/^v/,"")}var Xs="x-ts-cloud-invoke-depth",Ys="x-ts-cloud-invoke-chain",Zs="x-ts-cloud-trace-id";function gd(a){return si("sha256").update(a).digest("hex").slice(0,8)}var fi={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function Dt(a,n){if(typeof a.get==="function")return a.get(n)??void 0;let i=a;return i[n]??i[n.toLowerCase()]??i[n.toUpperCase()]}function md(a,n=64){if(!a)return[];return a.split(".").map((i)=>i.trim()).filter((i)=>/^[0-9a-f]{8}$/.test(i)).slice(-n)}function hd(a,n=fi){let i=gd(a.functionId),s=md(Dt(a.headers,Ys)),c=a.traceId??Dt(a.headers,Zs)??crypto.randomUUID(),l=[...s,i],u=s.filter((b)=>b===i).length,h=s[s.length-1]===i,y=Number.parseInt(Dt(a.headers,Xs)??"",10),f=Math.max(l.length,Number.isFinite(y)?y+1:0),S="ok";if(f>n.maxDepth)S="depth_exceeded";else if(u>=n.maxRepeats)S="cycle_detected";else if(h&&n.maxRepeats<=1)S="self_invocation";return{reason:S,depth:f,chain:l,traceId:c,selfInvocation:h,repeats:u,propagate:{[Xs]:String(f),[Ys]:l.join("."),[Zs]:c}}}var Ga={ok:"",depth_exceeded:"Invocation chain is deeper than the configured limit; the call was refused to stop a runaway loop.",cycle_detected:"This function already appears in the invocation chain; the call was refused as a recursion loop.",self_invocation:"This function invoked itself directly; the call was refused.",trace_budget_exceeded:"This request has already made more invocations than its budget allows.",breaker_open:"Recursion protection is open for this function after repeated loop detections."};class eo{limits;clock;traces=new Map;breakers=new Map;constructor(a=fi,n=()=>Date.now()){this.limits=a,this.clock=n}check(a){let n=this.clock();this.expireTraces(n);let i=hd(a,this.limits),s=this.breakers.get(a.functionId);if(s?.openUntil!=null&&s.openUntil>n)return this.deny(a.functionId,i,"breaker_open",n,!1);if(i.reason!=="ok")return this.deny(a.functionId,i,i.reason,n,!0);let c=this.traces.get(i.traceId)??{count:0,firstAt:n};if(c.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(i.traceId,c),this.deny(a.functionId,i,"trace_budget_exceeded",n,!0);if(this.traces.set(i.traceId,{count:c.count+1,firstAt:c.firstAt}),s)this.breakers.set(a.functionId,{consecutiveBlocks:0});return{...i,allowed:!0,reason:"ok",propagate:i.propagate}}deny(a,n,i,s,c){if(c){let l=this.breakers.get(a)??{consecutiveBlocks:0},u=l.consecutiveBlocks+1;this.breakers.set(a,{consecutiveBlocks:u,openUntil:u>=this.limits.breakerThreshold?s+this.limits.breakerCooldownMs:l.openUntil})}return{...n,allowed:!1,reason:i,message:Ga[i]}}breakerOpen(a){let n=this.breakers.get(a);return n?.openUntil!=null&&n.openUntil>this.clock()}reset(a){if(a){this.breakers.delete(a);return}this.breakers.clear(),this.traces.clear()}expireTraces(a){if(this.traces.size===0)return;for(let[n,i]of this.traces)if(a-i.firstAt>this.limits.traceWindowMs)this.traces.delete(n)}get trackedTraces(){return this.traces.size}}function fd(a){return{...a.propagate}}function Ad(a){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":a.reason},body:{error:"recursion_blocked",reason:a.reason,message:a.message??Ga[a.reason],depth:a.depth,traceId:a.traceId}}}var $g=new ii;function pa(a){let n=globalThis.process?.env?.[a];if(n==null||n==="")return;return n!=="0"&&n.toLowerCase()!=="false"}function oi(){let a=globalThis.process?.env??{};return a.TS_CLOUD_FUNCTION_ID||a.AWS_LAMBDA_FUNCTION_NAME||a.FUNCTION_NAME||"function"}function Zf(a){let n=a===!1?{enabled:!1}:a??{},i=pa("TS_CLOUD_RECURSION_PROTECTION"),s=pa("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:i??n.enabled??!0,detectionOnly:s??n.detectionOnly??!1,limits:{...fi,...n.limits},functionId:n.functionId??oi()}}var De,fe;function eA(){let a=globalThis.fetch;if(!a||De===a)return()=>{};fe=a;let n=async(i,s)=>{let c=$g.getStore();if(!c)return fe(i,s);let l=new Headers(s?.headers??(i instanceof Request?i.headers:void 0));for(let[u,h]of Object.entries(fd(c)))l.set(u,h);if(i instanceof Request)return fe(new Request(i,{headers:l}),s);return fe(i,{...s,headers:l})};return Object.assign(n,a),globalThis.fetch=n,De=n,()=>{if(globalThis.fetch===De&&fe)globalThis.fetch=fe;De=void 0}}var lt,xt;function tA(a){if(!lt||JSON.stringify(xt)!==JSON.stringify(a))lt=new eo(a),xt=a;return lt}function FC(){if(lt=void 0,xt=void 0,De&&fe&&globalThis.fetch===De)globalThis.fetch=fe;De=void 0,fe=void 0}function rA(a,n){let i=Zf(n);if(!i.enabled)return;let s=tA(i.limits),c={functionId:i.functionId,headers:a},l=s.check(c);return{verdict:l,blocked:!l.allowed&&!i.detectionOnly,observed:!l.allowed&&i.detectionOnly}}function nA(a,n){return eA(),$g.run(a,n)}function UC(a){let n=a,i=n?.default??n;if(typeof i==="function")return{fetch:i};return{fetch:i?.fetch??n?.fetch,queue:i?.queue??n?.queue,cli:i?.cli??n?.cli}}var ci=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function li(a){if(!a)return!0;return ci.test(a)}function di(a){if(a?.maintenance)return a.maintenance;let n=globalThis.process?.env??{};return{enabled:n.MAINTENANCE_MODE==="1"||n.MAINTENANCE_MODE==="true",bypassSecret:n.MAINTENANCE_BYPASS_SECRET}}function iA(a){let n=a.requestContext?.domainName??"localhost",i=a.rawQueryString?`?${a.rawQueryString}`:"",s=`https://${n}${a.rawPath||"/"}${i}`,c=new Headers;for(let[h,y]of Object.entries(a.headers??{}))if(y!==void 0)c.set(h,y);if(a.cookies?.length)c.set("cookie",a.cookies.join("; "));let l=a.requestContext.http.method,u;if(a.body!==void 0&&l!=="GET"&&l!=="HEAD")u=a.isBase64Encoded?new Uint8Array(Buffer.from(a.body,"base64")):new TextEncoder().encode(a.body);return new Request(s,{method:l,headers:c,body:u})}async function Mg(a){let n={},i=[],s=typeof a.headers.getSetCookie==="function"?a.headers.getSetCookie():[];for(let u of s)i.push(u);a.headers.forEach((u,h)=>{if(h.toLowerCase()==="set-cookie")return;n[h]=u});let c=Buffer.from(await a.arrayBuffer()),l=li(a.headers.get("content-type"));return{statusCode:a.status,headers:n,...i.length?{cookies:i}:{},body:l?c.toString("utf-8"):c.toString("base64"),isBase64Encoded:!l}}function sA(a,n){return async(i)=>{if(i.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!a)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let s=di(n);if(s.enabled){let u=i.headers?.["x-maintenance-bypass"]??i.cookies?.find((h)=>h.startsWith("tscloud_bypass="))?.split("=")[1];if(!s.bypassSecret||u!==s.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let c=rA(i.headers??{},n?.recursionProtection);if(c?.blocked){let u=Ad(c.verdict);return{statusCode:u.status,headers:{...u.headers,"retry-after":"60"},body:JSON.stringify(u.body),isBase64Encoded:!1}}let l=iA(i);if(!c){let u=await a(l);return Mg(u)}if(c.observed)console.warn(`[ts-cloud] recursion detected (${c.verdict.reason}) at depth ${c.verdict.depth}; detection-only mode let it run`);return nA(c.verdict,async()=>Mg(await a(l)))}}function yi(a){try{return JSON.parse(a)}catch{return a}}function oA(a){return async(n)=>{let i=[];if(n.warmer)return{batchItemFailures:i};if(!a)return{batchItemFailures:i};for(let s of n.Records??[])try{await a(yi(s.body),s)}catch{i.push({itemIdentifier:s.messageId})}return{batchItemFailures:i}}}function aA(a){return async(n)=>{if(n.warmer)return{statusCode:0,output:"warm"};if(!a)return{statusCode:501,output:"No CLI handler configured"};return a(n)}}function QC(a,n){return{http:sA(a.fetch,n),queue:oA(a.queue),cli:aA(a.cli)}}function cA(a={}){let n=a.socketPath??"/tmp/.tscloud-fpm.sock",i=a.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
7338
7338
  [global]
7339
7339
  daemonize = no
7340
7340
  error_log = ${a.errorLog??"/tmp/storage/logs/php-fpm.log"}
@@ -7351,5 +7351,5 @@ decorate_workers_output = no
7351
7351
  php_admin_value[error_log] = /dev/stderr
7352
7352
  php_admin_flag[log_errors] = on
7353
7353
  clear_env = no
7354
- `}function Ti(){return Ua(bi(Ci(import.meta.url)),"runtime-assets")}function Ai(){let a=Ti(),n=(i)=>Si(Ua(a,i),"utf-8");return[{path:"bootstrap",contents:n("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:n("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:n("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:n("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:n("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:cA(),mode:420}]}function yd(a={}){let n=a.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:n,CACHE_DRIVER:n,SESSION_DRIVER:n,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var dA=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];function*Va(a){for(let n of Pi(a)){let i=xe(a,n);if(Fa(i).isDirectory())yield*Va(i);else yield i}}function HC(a={}){let n=a.architecture??"x86_64",i=a.platform??(n==="arm64"?"linux/arm64":"linux/amd64"),s=a.onStep??(()=>{}),c=Ei(xe(Di(),"tscloud-php-layer-")),l="tscloud-php-layer:build";try{Ni(xe(c,"Dockerfile"),Yf(a)),s("Building PHP runtime image (docker)"),lt("docker",["build","--platform",i,"-t","tscloud-php-layer:build",c],{stdio:"inherit"}),s("Extracting /opt/php from image");let u=lt("docker",["create","--platform",i,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),h=xe(c,"opt");wi(h,{recursive:!0});try{lt("docker",["cp",`${u}:/opt/php`,xe(h,"php")],{stdio:"inherit"})}finally{lt("docker",["rm",u],{stdio:"ignore"})}if(!vi(xe(h,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let y=[];for(let b of Va(h)){let C=ki(h,b).replace(/\\/g,"/"),T=Fa(b).mode&73?493:420;y.push({name:C,data:Ii(b),mode:T})}s("Injecting runtime assets");let f=new Set(Ai().map((b)=>b.path)),S=y.filter((b)=>!f.has(b.name));for(let b of Ai())S.push({name:b.path,data:b.contents,mode:b.mode});return s("Packaging layer ZIP"),{zip:hi(S),architecture:n,fileCount:S.length}}finally{Ri(c,{recursive:!0,force:!0})}}var lA=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function Bi(a,n){return n.some((i)=>a===i||a.startsWith(`${i}/`))}function*Ha(a,n,i){for(let s of Mi(a)){let c=Oi(a,s),l=Ka(n,c).replace(/\\/g,"/");if(Bi(l,i))continue;if(ja(c).isDirectory())yield*Ha(c,n,i);else yield c}}function to(a){if(a.skipBuild)return;let n=na(a.projectRoot??process.cwd()),i=a.app.build??dA;for(let s of i)a.onStep?.(`build: ${s}`),$i(s,{stdio:"inherit",cwd:n})}function ro(a,n=[]){let i=na(a),s=[...lA,Qs(),...n],c=[];for(let l of Ha(i,i,s)){let u=Ka(i,l).replace(/\\/g,"/"),h=(ja(l).mode&73)!==0;c.push({name:u,data:xi(l),mode:h?493:420})}return c}function Id(a){let n=na(a.projectRoot??process.cwd());to(a),a.onStep?.("packaging application tree");let i=ro(n,a.exclude);if(!i.length)throw Error(`No files to package under ${n}`);let s=hi(i),c=a.app.handlers?.http??"public/index.php";return{zip:s,sha256:Li("sha256").update(s).digest("hex"),handlers:{http:c,queue:a.app.handlers?.queue??c,cli:a.app.handlers?.cli??c},fileCount:i.length}}class Fg{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(a){let n=`asset-opt-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.optimizations.set(n,i),i}createImageOptimization(a){let n=`image-opt-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.imageConfigs.set(n,i),i}createSSGConfig(a){let n=`ssg-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.ssgConfigs.set(n,i),i}createPrerenderConfig(a){let n=`prerender-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.prerenderConfigs.set(n,i),i}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var GC=new Fg;class Ug{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(a,n){let i=`lifecycle-${Date.now()}-${this.counter++}`,s={id:i,transitions:a,expiration:n};return this.policies.set(i,s),s}enableVersioning(a=!1){let n=`versioning-${Date.now()}-${this.counter++}`,i={id:n,enabled:!0,mfaDelete:a};return this.versioningConfigs.set(n,i),i}createReplicationRule(a,n,i){let s=`replication-${Date.now()}-${this.counter++}`,c={id:s,sourceRegion:a,destRegion:n,destBucket:i};return this.replicationRules.set(s,c),c}createIntelligentTiering(a,n){let i=`tiering-${Date.now()}-${this.counter++}`,s={id:i,archiveDays:a,deepArchiveDays:n};return this.tieringConfigs.set(i,s),s}enableObjectLock(a){let n=`object-lock-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,mode:a.mode||"COMPLIANCE",retentionDays:a.retentionDays,retentionYears:a.retentionYears,legalHoldEnabled:a.legalHoldEnabled||!1};return this.objectLocks.set(n,i),i}enableTransferAcceleration(a){let n=`transfer-accel-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a,enabled:!0,endpoint:`${a}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(n,i),i}createAccessPoint(a){let n=`access-point-${Date.now()}-${this.counter++}`,i={id:n,name:a.name,bucketName:a.bucketName,vpcId:a.vpcId,publicAccessBlock:a.publicAccessBlock!==!1,policy:a.policy};return this.accessPoints.set(n,i),i}createGlacierArchive(a){let n=`glacier-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,archiveType:a.archiveType,transitionDays:a.transitionDays,restoreConfig:a.restoreTier?{tier:a.restoreTier,days:a.restoreDays||7}:void 0};return this.glacierConfigs.set(n,i),i}createInventory(a){let n=`inventory-${Date.now()}-${this.counter++}`,i={id:n,sourceBucket:a.sourceBucket,destinationBucket:a.destinationBucket,schedule:a.schedule||"Daily",format:a.format||"CSV",includedFields:a.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:a.prefix};return this.inventories.set(n,i),i}createBatchOperation(a){let n=`batch-op-${Date.now()}-${this.counter++}`,i={id:n,operation:a.operation,manifestBucket:a.manifestBucket,manifestKey:a.manifestKey,priority:a.priority||10,status:"pending"};return this.batchOps.set(n,i),i}executeBatchOperation(a){let n=this.batchOps.get(a);if(!n)throw Error(`Batch operation not found: ${a}`);return n.status="in_progress",n.totalObjects=1000,n.processedObjects=0,n}getBatchOperationStatus(a){return this.batchOps.get(a)}createLambdaNotification(a){let n=`event-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,events:a.events,destination:{type:"Lambda",arn:a.lambdaArn},filter:a.prefix||a.suffix?{prefix:a.prefix,suffix:a.suffix}:void 0};return this.eventNotifications.set(n,i),i}createSQSNotification(a){let n=`event-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,events:a.events,destination:{type:"SQS",arn:a.queueArn},filter:a.prefix||a.suffix?{prefix:a.prefix,suffix:a.suffix}:void 0};return this.eventNotifications.set(n,i),i}createSNSNotification(a){let n=`event-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,events:a.events,destination:{type:"SNS",arn:a.topicArn},filter:a.prefix||a.suffix?{prefix:a.prefix,suffix:a.suffix}:void 0};return this.eventNotifications.set(n,i),i}generateObjectLockCF(a){let n={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:a.mode}}}};if(a.retentionDays)n.ObjectLockConfiguration.Rule.DefaultRetention.Days=a.retentionDays;if(a.retentionYears)n.ObjectLockConfiguration.Rule.DefaultRetention.Years=a.retentionYears;return n}generateTransferAccelerationCF(a){return{AccelerateConfiguration:{AccelerationStatus:a.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(a){return{Type:"AWS::S3::AccessPoint",Properties:{Name:a.name,Bucket:a.bucketName,...a.vpcId&&{VpcConfiguration:{VpcId:a.vpcId}},PublicAccessBlockConfiguration:a.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...a.policy&&{Policy:a.policy}}}}generateInventoryCF(a){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:a.id,Destination:{BucketArn:`arn:aws:s3:::${a.destinationBucket}`,Format:a.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:a.includedFields,ScheduleFrequency:a.schedule,...a.prefix&&{Prefix:a.prefix}}]}}}generateEventNotificationCF(a){let n=a.destination.type==="Lambda"?"LambdaConfigurations":a.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",i=a.destination.type==="Lambda"?"Function":a.destination.type==="SQS"?"Queue":"Topic",s={Event:a.events[0],[i]:a.destination.arn};if(a.filter)s.Filter={S3Key:{Rules:[...a.filter.prefix?[{Name:"prefix",Value:a.filter.prefix}]:[],...a.filter.suffix?[{Name:"suffix",Value:a.filter.suffix}]:[]]}};return{NotificationConfiguration:{[n]:[s]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var qC=new Ug;class Qg{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(a,n=30,i=10){let s=`health-${Date.now()}-${this.counter++}`,c={id:s,url:a,interval:n,timeout:i,status:"healthy"};return this.checks.set(s,c),c}createSyntheticMonitor(a,n,i,s){let c=`synthetic-${Date.now()}-${this.counter++}`,l={id:c,name:a,script:n,frequency:i,locations:s};return this.synthetics.set(c,l),l}trackUptime(a,n,i){let s=`uptime-${Date.now()}-${this.counter++}`,c=n/(n+i)*100,l={id:s,resource:a,uptime:n,downtime:i,availability:c};return this.uptimeTrackers.set(s,l),l}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var VC=new Qg;class Hg{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(a,n,i,s){let c=`waf-${Date.now()}-${this.counter++}`,l={id:c,name:a,priority:n,action:i,conditions:s};return this.wafRules.set(c,l),l}enableShield(a,n="standard"){let i=`shield-${Date.now()}-${this.counter++}`,s={id:i,resourceArn:a,protectionType:n};return this.shieldProtections.set(i,s),s}createSecurityGroup(a,n,i){let s=`sg-${Date.now()}-${this.counter++}`,c={id:s,name:a,vpcId:n,rules:i};return this.securityGroups.set(s,c),c}createNACL(a,n){let i=`nacl-${Date.now()}-${this.counter++}`,s={id:i,vpcId:a,rules:n};return this.nacls.set(i,s),s}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var jC=new Hg;class Gg{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(a,n){let i=`tagging-${Date.now()}-${this.counter++}`,s={id:i,tags:a,resources:n};return this.strategies.set(i,s),s}createCostAllocation(a,n){let i=`cost-${Date.now()}-${this.counter++}`,s={id:i,tagKey:a,allocations:n};return this.allocations.set(i,s),s}createResourceGroup(a,n,i){let s=`group-${Date.now()}-${this.counter++}`,c={id:s,name:a,query:{resourceTypeFilters:n,tagFilters:i}};return this.groups.set(s,c),c}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var zC=new Gg;
7355
- export{Sp,x,Cp,rf,uy,nf,py,gy,my,hy,fy,Ay,yy,Iy,Sy,Cy,bp,Ep,Wc,Jc,Qs,_,d,Xc,vp,O,Yc,p,sf,ui,Zc,ed,ae,td,by,r,t,Ey,vy,g,Ty,wy,Ry,Dy,Py,Mt,rd,Hs,of,Ny,ky,Se,Me,Ce,L,I,o,A,Fe,m,af,Ue,M,at,By,cf,F,nd,be,Ft,Gs,J,id,X,df,qs,U,Q,D,pi,E,Ut,ct,H,e,Vs,xy,Tp,sd,_y,Oy,Ly,$y,od,My,Fy,Uy,Qy,Hy,Gy,qy,Vy,jy,zy,Ky,Wy,lf,uf,pf,gf,mf,hf,ff,Qt,wp,Rp,Nr,gi,Jy,Dp,Xy,Yy,kr,Zy,eI,tI,rI,nI,iI,Af,yf,If,Sf,Cf,js,sI,bf,Ef,vf,G,oI,Qe,zs,Ht,Tf,Pp,wf,Rf,Df,Np,Y,aI,cI,dI,lI,Pf,uI,q,pI,gI,mI,kp,Bp,hI,xp,_p,fI,yI,II,SI,CI,Nf,ad,bI,EI,vI,TI,wI,kf,Bf,RI,DI,PI,NI,kI,BI,xI,_I,OI,Op,cd,LI,$I,MI,FI,Lp,$p,Mp,UI,Fp,QI,HI,GI,qI,Up,VI,jI,zI,KI,WI,JI,XI,YI,xf,_f,Of,Lf,Qp,ZI,eS,tS,rS,nS,iS,sS,oS,aS,$f,Mf,Ff,Uf,cS,dS,Hp,lS,Gp,qp,Vp,jp,uS,pS,gS,mS,Ee,mi,hS,fS,AS,yS,IS,SS,CS,bS,Qf,ES,vS,zp,Kp,TS,wS,Hf,RS,DS,PS,NS,kS,BS,xS,_S,OS,LS,$S,MS,FS,US,QS,HS,GS,qS,VS,jS,zS,Wp,KS,Jp,WS,Xp,JS,Yp,XS,Zp,YS,Br,ZS,eg,eC,Ks,tC,tg,rC,rg,nC,ng,iC,ig,sC,sg,oC,xr,aC,og,cC,ag,dC,cg,lC,dg,uC,lg,pC,ug,gC,pg,mC,gg,hC,mg,fC,hg,AC,fg,yC,Ag,IC,yg,SC,Ig,CC,Sg,bC,Cg,EC,bg,vC,Eg,TC,vg,wC,Tg,RC,wg,DC,Rg,PC,Dg,NC,Pg,kC,Ng,BC,Gf,qf,Vf,jf,kg,xC,Bg,_C,xg,OC,_g,LC,hi,zf,Kf,Ws,dd,_r,Wf,Js,Gt,ld,ud,Jf,Xf,Og,Yf,pd,Lg,$C,MC,Xs,Ys,Zs,gd,fi,md,hd,eo,fd,Ad,$g,Zf,eA,tA,FC,rA,nA,UC,iA,Mg,sA,oA,aA,QC,cA,Ai,yd,dA,HC,lA,to,ro,Id,Fg,GC,Ug,qC,Qg,VC,Hg,jC,Gg,zC};
7354
+ `}function Ti(){return Ua(bi(Ci(import.meta.url)),"runtime-assets")}function Ai(){let a=Ti(),n=(i)=>Si(Ua(a,i),"utf-8");return[{path:"bootstrap",contents:n("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:n("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:n("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:n("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:n("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:cA(),mode:420}]}function yd(a={}){let n=a.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:n,CACHE_DRIVER:n,SESSION_DRIVER:n,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var dA=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];function*Va(a){for(let n of Pi(a)){let i=Me(a,n);if(Fa(i).isDirectory())yield*Va(i);else yield i}}function HC(a={}){let n=a.architecture??"x86_64",i=a.platform??(n==="arm64"?"linux/arm64":"linux/amd64"),s=a.onStep??(()=>{}),c=Ei(Me(Di(),"tscloud-php-layer-")),l="tscloud-php-layer:build";try{Ni(Me(c,"Dockerfile"),Yf(a)),s("Building PHP runtime image (docker)"),ot("docker",["build","--platform",i,"-t","tscloud-php-layer:build",c],{stdio:"inherit"}),s("Extracting /opt/php from image");let u=ot("docker",["create","--platform",i,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),h=Me(c,"opt");wi(h,{recursive:!0});try{ot("docker",["cp",`${u}:/opt/php`,Me(h,"php")],{stdio:"inherit"})}finally{ot("docker",["rm",u],{stdio:"ignore"})}if(!vi(Me(h,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let y=[];for(let b of Va(h)){let C=ki(h,b).replace(/\\/g,"/"),T=Fa(b).mode&73?493:420;y.push({name:C,data:Ii(b),mode:T})}s("Injecting runtime assets");let f=new Set(Ai().map((b)=>b.path)),S=y.filter((b)=>!f.has(b.name));for(let b of Ai())S.push({name:b.path,data:b.contents,mode:b.mode});return s("Packaging layer ZIP"),{zip:hi(S),architecture:n,fileCount:S.length}}finally{Ri(c,{recursive:!0,force:!0})}}var lA=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function Bi(a,n){return n.some((i)=>a===i||a.startsWith(`${i}/`))}function*Ha(a,n,i){for(let s of Mi(a)){let c=Oi(a,s),l=Ka(n,c).replace(/\\/g,"/");if(Bi(l,i))continue;if(ja(c).isDirectory())yield*Ha(c,n,i);else yield c}}function to(a){if(a.skipBuild)return;let n=na(a.projectRoot??process.cwd()),i=a.app.build??dA;for(let s of i)a.onStep?.(`build: ${s}`),$i(s,{stdio:"inherit",cwd:n})}function ro(a,n=[]){let i=na(a),s=[...lA,Qs(),...n],c=[];for(let l of Ha(i,i,s)){let u=Ka(i,l).replace(/\\/g,"/"),h=(ja(l).mode&73)!==0;c.push({name:u,data:xi(l),mode:h?493:420})}return c}function Id(a){let n=na(a.projectRoot??process.cwd());to(a),a.onStep?.("packaging application tree");let i=ro(n,a.exclude);if(!i.length)throw Error(`No files to package under ${n}`);let s=hi(i),c=a.app.handlers?.http??"public/index.php";return{zip:s,sha256:Li("sha256").update(s).digest("hex"),handlers:{http:c,queue:a.app.handlers?.queue??c,cli:a.app.handlers?.cli??c},fileCount:i.length}}class Fg{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(a){let n=`asset-opt-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.optimizations.set(n,i),i}createImageOptimization(a){let n=`image-opt-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.imageConfigs.set(n,i),i}createSSGConfig(a){let n=`ssg-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.ssgConfigs.set(n,i),i}createPrerenderConfig(a){let n=`prerender-${Date.now()}-${this.counter++}`,i={id:n,...a};return this.prerenderConfigs.set(n,i),i}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var GC=new Fg;class Ug{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(a,n){let i=`lifecycle-${Date.now()}-${this.counter++}`,s={id:i,transitions:a,expiration:n};return this.policies.set(i,s),s}enableVersioning(a=!1){let n=`versioning-${Date.now()}-${this.counter++}`,i={id:n,enabled:!0,mfaDelete:a};return this.versioningConfigs.set(n,i),i}createReplicationRule(a,n,i){let s=`replication-${Date.now()}-${this.counter++}`,c={id:s,sourceRegion:a,destRegion:n,destBucket:i};return this.replicationRules.set(s,c),c}createIntelligentTiering(a,n){let i=`tiering-${Date.now()}-${this.counter++}`,s={id:i,archiveDays:a,deepArchiveDays:n};return this.tieringConfigs.set(i,s),s}enableObjectLock(a){let n=`object-lock-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,mode:a.mode||"COMPLIANCE",retentionDays:a.retentionDays,retentionYears:a.retentionYears,legalHoldEnabled:a.legalHoldEnabled||!1};return this.objectLocks.set(n,i),i}enableTransferAcceleration(a){let n=`transfer-accel-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a,enabled:!0,endpoint:`${a}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(n,i),i}createAccessPoint(a){let n=`access-point-${Date.now()}-${this.counter++}`,i={id:n,name:a.name,bucketName:a.bucketName,vpcId:a.vpcId,publicAccessBlock:a.publicAccessBlock!==!1,policy:a.policy};return this.accessPoints.set(n,i),i}createGlacierArchive(a){let n=`glacier-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,archiveType:a.archiveType,transitionDays:a.transitionDays,restoreConfig:a.restoreTier?{tier:a.restoreTier,days:a.restoreDays||7}:void 0};return this.glacierConfigs.set(n,i),i}createInventory(a){let n=`inventory-${Date.now()}-${this.counter++}`,i={id:n,sourceBucket:a.sourceBucket,destinationBucket:a.destinationBucket,schedule:a.schedule||"Daily",format:a.format||"CSV",includedFields:a.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:a.prefix};return this.inventories.set(n,i),i}createBatchOperation(a){let n=`batch-op-${Date.now()}-${this.counter++}`,i={id:n,operation:a.operation,manifestBucket:a.manifestBucket,manifestKey:a.manifestKey,priority:a.priority||10,status:"pending"};return this.batchOps.set(n,i),i}executeBatchOperation(a){let n=this.batchOps.get(a);if(!n)throw Error(`Batch operation not found: ${a}`);return n.status="in_progress",n.totalObjects=1000,n.processedObjects=0,n}getBatchOperationStatus(a){return this.batchOps.get(a)}createLambdaNotification(a){let n=`event-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,events:a.events,destination:{type:"Lambda",arn:a.lambdaArn},filter:a.prefix||a.suffix?{prefix:a.prefix,suffix:a.suffix}:void 0};return this.eventNotifications.set(n,i),i}createSQSNotification(a){let n=`event-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,events:a.events,destination:{type:"SQS",arn:a.queueArn},filter:a.prefix||a.suffix?{prefix:a.prefix,suffix:a.suffix}:void 0};return this.eventNotifications.set(n,i),i}createSNSNotification(a){let n=`event-${Date.now()}-${this.counter++}`,i={id:n,bucketName:a.bucketName,events:a.events,destination:{type:"SNS",arn:a.topicArn},filter:a.prefix||a.suffix?{prefix:a.prefix,suffix:a.suffix}:void 0};return this.eventNotifications.set(n,i),i}generateObjectLockCF(a){let n={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:a.mode}}}};if(a.retentionDays)n.ObjectLockConfiguration.Rule.DefaultRetention.Days=a.retentionDays;if(a.retentionYears)n.ObjectLockConfiguration.Rule.DefaultRetention.Years=a.retentionYears;return n}generateTransferAccelerationCF(a){return{AccelerateConfiguration:{AccelerationStatus:a.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(a){return{Type:"AWS::S3::AccessPoint",Properties:{Name:a.name,Bucket:a.bucketName,...a.vpcId&&{VpcConfiguration:{VpcId:a.vpcId}},PublicAccessBlockConfiguration:a.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...a.policy&&{Policy:a.policy}}}}generateInventoryCF(a){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:a.id,Destination:{BucketArn:`arn:aws:s3:::${a.destinationBucket}`,Format:a.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:a.includedFields,ScheduleFrequency:a.schedule,...a.prefix&&{Prefix:a.prefix}}]}}}generateEventNotificationCF(a){let n=a.destination.type==="Lambda"?"LambdaConfigurations":a.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",i=a.destination.type==="Lambda"?"Function":a.destination.type==="SQS"?"Queue":"Topic",s={Event:a.events[0],[i]:a.destination.arn};if(a.filter)s.Filter={S3Key:{Rules:[...a.filter.prefix?[{Name:"prefix",Value:a.filter.prefix}]:[],...a.filter.suffix?[{Name:"suffix",Value:a.filter.suffix}]:[]]}};return{NotificationConfiguration:{[n]:[s]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var qC=new Ug;class Qg{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(a,n=30,i=10){let s=`health-${Date.now()}-${this.counter++}`,c={id:s,url:a,interval:n,timeout:i,status:"healthy"};return this.checks.set(s,c),c}createSyntheticMonitor(a,n,i,s){let c=`synthetic-${Date.now()}-${this.counter++}`,l={id:c,name:a,script:n,frequency:i,locations:s};return this.synthetics.set(c,l),l}trackUptime(a,n,i){let s=`uptime-${Date.now()}-${this.counter++}`,c=n/(n+i)*100,l={id:s,resource:a,uptime:n,downtime:i,availability:c};return this.uptimeTrackers.set(s,l),l}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var VC=new Qg;class Hg{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(a,n,i,s){let c=`waf-${Date.now()}-${this.counter++}`,l={id:c,name:a,priority:n,action:i,conditions:s};return this.wafRules.set(c,l),l}enableShield(a,n="standard"){let i=`shield-${Date.now()}-${this.counter++}`,s={id:i,resourceArn:a,protectionType:n};return this.shieldProtections.set(i,s),s}createSecurityGroup(a,n,i){let s=`sg-${Date.now()}-${this.counter++}`,c={id:s,name:a,vpcId:n,rules:i};return this.securityGroups.set(s,c),c}createNACL(a,n){let i=`nacl-${Date.now()}-${this.counter++}`,s={id:i,vpcId:a,rules:n};return this.nacls.set(i,s),s}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var jC=new Hg;class Gg{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(a,n){let i=`tagging-${Date.now()}-${this.counter++}`,s={id:i,tags:a,resources:n};return this.strategies.set(i,s),s}createCostAllocation(a,n){let i=`cost-${Date.now()}-${this.counter++}`,s={id:i,tagKey:a,allocations:n};return this.allocations.set(i,s),s}createResourceGroup(a,n,i){let s=`group-${Date.now()}-${this.counter++}`,c={id:s,name:a,query:{resourceTypeFilters:n,tagFilters:i}};return this.groups.set(s,c),c}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var zC=new Gg;
7355
+ export{Sp,x,Cp,rf,uy,nf,py,gy,my,hy,fy,Ay,yy,Iy,Sy,Cy,bp,Ep,Wc,Jc,Qs,_,d,Xc,vp,O,Yc,p,sf,ui,Zc,ed,ce,td,by,r,t,Ey,vy,g,Ty,wy,Ry,Dy,Py,Mt,rd,Hs,of,Ny,ky,Se,Fe,Ce,L,I,o,A,Ue,m,af,Qe,M,ct,By,cf,F,nd,be,Ft,Gs,X,id,Y,df,qs,U,Q,D,pi,E,Ut,dt,H,e,Vs,xy,Tp,sd,_y,Oy,Ly,$y,od,My,Fy,Uy,Qy,Hy,Gy,qy,Vy,jy,zy,Ky,Wy,lf,uf,pf,gf,mf,hf,ff,Qt,wp,Rp,Nr,gi,Jy,Dp,Xy,Yy,kr,Zy,eI,tI,rI,nI,iI,Af,yf,If,Sf,Cf,js,sI,bf,Ef,vf,G,oI,He,zs,Ht,Tf,Pp,wf,Rf,Df,Np,Z,aI,cI,dI,lI,Pf,uI,q,pI,gI,mI,kp,Bp,hI,xp,_p,fI,yI,II,SI,CI,Nf,ad,bI,EI,vI,TI,wI,kf,Bf,RI,DI,PI,NI,kI,BI,xI,_I,OI,Op,cd,LI,$I,MI,FI,Lp,$p,Mp,UI,Fp,QI,HI,GI,qI,Up,VI,jI,zI,KI,WI,JI,XI,YI,xf,_f,Of,Lf,Qp,ZI,eS,tS,rS,nS,iS,sS,oS,aS,$f,Mf,Ff,Uf,cS,dS,Hp,lS,Gp,qp,Vp,jp,uS,pS,gS,mS,Ee,mi,hS,fS,AS,yS,IS,SS,CS,bS,Qf,ES,vS,zp,Kp,TS,wS,Hf,RS,DS,PS,NS,kS,BS,xS,_S,OS,LS,$S,MS,FS,US,QS,HS,GS,qS,VS,jS,zS,Wp,KS,Jp,WS,Xp,JS,Yp,XS,Zp,YS,Br,ZS,eg,eC,Ks,tC,tg,rC,rg,nC,ng,iC,ig,sC,sg,oC,xr,aC,og,cC,ag,dC,cg,lC,dg,uC,lg,pC,ug,gC,pg,mC,gg,hC,mg,fC,hg,AC,fg,yC,Ag,IC,yg,SC,Ig,CC,Sg,bC,Cg,EC,bg,vC,Eg,TC,vg,wC,Tg,RC,wg,DC,Rg,PC,Dg,NC,Pg,kC,Ng,BC,Gf,qf,Vf,jf,kg,xC,Bg,_C,xg,OC,_g,LC,hi,zf,Kf,Ws,dd,_r,Wf,Js,Gt,ld,ud,Jf,Xf,Og,Yf,pd,Lg,$C,MC,Xs,Ys,Zs,gd,fi,md,hd,eo,fd,Ad,$g,Zf,eA,tA,FC,rA,nA,UC,iA,Mg,sA,oA,aA,QC,cA,Ai,yd,dA,HC,lA,to,ro,Id,Fg,GC,Ug,qC,Qg,VC,Hg,jC,Gg,zC};