@stacksjs/ts-cloud 0.16.23 → 0.16.24

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 (184) hide show
  1. package/dist/aws/client.d.ts +9 -0
  2. package/dist/aws/index.js +1 -1
  3. package/dist/bin/chunk-0cwbg3pf.js +1 -0
  4. package/dist/bin/{chunk-6cfpdb35.js → chunk-0md2h0an.js} +4 -4
  5. package/dist/bin/chunk-0ytk5g2t.js +1 -0
  6. package/dist/bin/chunk-19tmmwmt.js +1 -0
  7. package/dist/bin/chunk-1fde3e2c.js +1 -0
  8. package/dist/bin/{chunk-2tk8egg8.js → chunk-1j9vy88a.js} +1 -1
  9. package/dist/bin/{chunk-wyanqf91.js → chunk-257sygzm.js} +2 -2
  10. package/dist/bin/{chunk-j0zg3mbm.js → chunk-2q27v6vz.js} +1 -1
  11. package/dist/bin/chunk-3b8a3knq.js +1 -0
  12. package/dist/bin/{chunk-9h7yjtz2.js → chunk-3jjggqfj.js} +3 -3
  13. package/dist/bin/{chunk-zcabmq4p.js → chunk-4sq6cvz5.js} +3 -3
  14. package/dist/bin/chunk-4y20ry45.js +1 -0
  15. package/dist/bin/{chunk-8vm7tpyv.js → chunk-5kc8s9gp.js} +1 -1
  16. package/dist/bin/{chunk-gzpwf3n4.js → chunk-5x59x4qw.js} +2 -2
  17. package/dist/bin/chunk-6aj3h8yk.js +1 -0
  18. package/dist/bin/{chunk-f3sd1hpa.js → chunk-6eesa8d1.js} +5 -5
  19. package/dist/bin/{chunk-jtnv8nwz.js → chunk-6nm91cfw.js} +1 -1
  20. package/dist/bin/{chunk-ht6tpmqw.js → chunk-7412q5cz.js} +2 -2
  21. package/dist/bin/chunk-78w3bn85.js +1 -0
  22. package/dist/bin/{chunk-cpwk0pbg.js → chunk-8e7n357e.js} +30 -30
  23. package/dist/bin/{chunk-ht318ydv.js → chunk-8knkt6sd.js} +1 -1
  24. package/dist/bin/{chunk-34kwhmbt.js → chunk-9464wvf2.js} +5 -5
  25. package/dist/bin/{chunk-jbpkwxht.js → chunk-988qv730.js} +4 -4
  26. package/dist/bin/chunk-9b6af1sj.js +1 -0
  27. package/dist/bin/{chunk-0r45d0s3.js → chunk-9e7pqhj1.js} +1 -1
  28. package/dist/bin/chunk-a07jfqvs.js +1 -0
  29. package/dist/bin/{chunk-cas0bp91.js → chunk-a3rq51az.js} +2 -2
  30. package/dist/bin/{chunk-gfwkmttt.js → chunk-apw5bbjg.js} +1 -1
  31. package/dist/bin/{chunk-33e0t7e5.js → chunk-ax41jhq7.js} +1 -1
  32. package/dist/bin/{chunk-k052rtd5.js → chunk-c35qm7as.js} +4 -4
  33. package/dist/bin/{chunk-f2yhthd1.js → chunk-d1psxeqj.js} +2 -2
  34. package/dist/bin/{chunk-0d98bem8.js → chunk-f0fpp4mk.js} +1 -1
  35. package/dist/bin/chunk-fpy7nv5g.js +1 -0
  36. package/dist/bin/chunk-fq4nxfec.js +1 -0
  37. package/dist/bin/chunk-ghe1nawv.js +1 -0
  38. package/dist/bin/{chunk-h90azajz.js → chunk-hez48c69.js} +1 -1
  39. package/dist/bin/{chunk-90kpnjdm.js → chunk-hjv1k8s9.js} +11 -11
  40. package/dist/bin/chunk-hwqvx1zb.js +1 -0
  41. package/dist/bin/{chunk-tyqxz92e.js → chunk-jdfbahjb.js} +101 -101
  42. package/dist/bin/chunk-jwdcx0mm.js +1 -0
  43. package/dist/bin/chunk-k9mzq7z9.js +1 -0
  44. package/dist/bin/chunk-kf1p7s61.js +1 -0
  45. package/dist/bin/{chunk-en7sf83z.js → chunk-m2gwzksz.js} +1 -1
  46. package/dist/bin/chunk-mh172wt8.js +1 -0
  47. package/dist/bin/{chunk-k1eezsj1.js → chunk-prj5b597.js} +2 -2
  48. package/dist/bin/{chunk-t1jpqn4x.js → chunk-q3xwh0r8.js} +6 -6
  49. package/dist/bin/chunk-q8crt80d.js +1 -0
  50. package/dist/bin/chunk-r3hkc2s3.js +1 -0
  51. package/dist/bin/{chunk-n298azax.js → chunk-rpfvv7hw.js} +1 -1
  52. package/dist/bin/{chunk-xs6afjat.js → chunk-wfa8j3wg.js} +3 -3
  53. package/dist/bin/{chunk-65rndjtr.js → chunk-wffaqgcc.js} +31 -31
  54. package/dist/bin/{chunk-hdsgfgnz.js → chunk-wg20x65t.js} +3 -3
  55. package/dist/bin/{chunk-21zhm1mk.js → chunk-wsedynyb.js} +6 -6
  56. package/dist/bin/chunk-xb82bmgf.js +1 -0
  57. package/dist/bin/{chunk-btr6zq53.js → chunk-xh5jcv64.js} +3 -3
  58. package/dist/bin/{chunk-v002yxaf.js → chunk-xss6yj73.js} +2 -2
  59. package/dist/bin/chunk-xxgybh3b.js +1 -0
  60. package/dist/bin/{chunk-hqmkfh4a.js → chunk-y6rgvb7r.js} +1 -1
  61. package/dist/bin/{chunk-yxyvhqhr.js → chunk-z5ycwy38.js} +2 -2
  62. package/dist/bin/chunk-zq02x716.js +1 -0
  63. package/dist/bin/cli.js +71 -71
  64. package/dist/bin/dashboard-server.js +1 -1
  65. package/dist/chunk-1ba6keyk.js +1 -0
  66. package/dist/{chunk-4rb7stp5.js → chunk-3x9g48ey.js} +3 -3
  67. package/dist/{chunk-gm0qysea.js → chunk-4rkjhvgw.js} +6 -6
  68. package/dist/{chunk-nfkdgsgh.js → chunk-65yh2h1e.js} +1 -1
  69. package/dist/{chunk-60fn008g.js → chunk-6e5j40n9.js} +2 -2
  70. package/dist/{chunk-xkqx98bx.js → chunk-97trx8p9.js} +2 -2
  71. package/dist/{chunk-14zcywnp.js → chunk-9ca1yafd.js} +2 -2
  72. package/dist/{chunk-hpq0rrve.js → chunk-bzbryxfm.js} +1 -1
  73. package/dist/{chunk-c836kdrx.js → chunk-d8w90gsb.js} +17 -17
  74. package/dist/{chunk-j2w0cvnr.js → chunk-dm6kyz6e.js} +1 -1
  75. package/dist/chunk-e3axmek0.js +1 -0
  76. package/dist/chunk-e4z4tfh6.js +1 -0
  77. package/dist/{chunk-01rbgche.js → chunk-e7m70ex1.js} +1 -1
  78. package/dist/{chunk-bz1hp7es.js → chunk-gvybjt7y.js} +1 -1
  79. package/dist/{chunk-xassxhvq.js → chunk-h85wqdvr.js} +7 -7
  80. package/dist/{chunk-92gn9ght.js → chunk-hzbyj0xd.js} +19 -19
  81. package/dist/{chunk-b5xjjz3y.js → chunk-jrrw3ezm.js} +5 -5
  82. package/dist/{chunk-t7q4awss.js → chunk-mv7hne2c.js} +1 -1
  83. package/dist/chunk-qa6jjv3m.js +1 -0
  84. package/dist/{chunk-ckwdjb5q.js → chunk-qfqh21rq.js} +5 -5
  85. package/dist/{chunk-2hy7ny4k.js → chunk-qrchr75r.js} +4 -4
  86. package/dist/{chunk-4apkvhsc.js → chunk-rgq7m90a.js} +48 -48
  87. package/dist/chunk-rnjgde95.js +1 -0
  88. package/dist/{chunk-g6aev693.js → chunk-rr1qjxyj.js} +1 -1
  89. package/dist/{chunk-cwgy9pvc.js → chunk-t4ynyk8k.js} +3 -3
  90. package/dist/{chunk-ds2v2xpb.js → chunk-v7y50hhf.js} +82 -82
  91. package/dist/{chunk-cpyrhh52.js → chunk-vtm83crj.js} +79 -79
  92. package/dist/{chunk-5vxpgw8q.js → chunk-wrpnnrdf.js} +5 -5
  93. package/dist/{chunk-pdmfmsm9.js → chunk-x9bpm5s1.js} +1 -1
  94. package/dist/{chunk-rq0wrpz6.js → chunk-zv85cpt2.js} +4 -4
  95. package/dist/deploy/index.js +1 -1
  96. package/dist/dns/index.js +1 -1
  97. package/dist/drivers/index.js +1 -1
  98. package/dist/index.js +18 -18
  99. package/dist/operations/index.js +1 -1
  100. package/dist/protection/index.js +1 -1
  101. package/dist/spend/index.js +1 -1
  102. package/dist/ui/404.html +1 -1
  103. package/dist/ui/accept-invitation.html +1 -1
  104. package/dist/ui/access-denied.html +1 -1
  105. package/dist/ui/account/automation.html +6 -6
  106. package/dist/ui/account/security.html +2 -2
  107. package/dist/ui/applications/compose.html +6 -6
  108. package/dist/ui/applications/new.html +2 -2
  109. package/dist/ui/data/backups.html +6 -6
  110. package/dist/ui/data/services.html +6 -6
  111. package/dist/ui/data/volumes.html +6 -6
  112. package/dist/ui/index.html +6 -6
  113. package/dist/ui/infrastructure/topology.html +6 -6
  114. package/dist/ui/integrations.html +2 -2
  115. package/dist/ui/operations/alerts.html +5 -5
  116. package/dist/ui/operations/configuration.html +5 -5
  117. package/dist/ui/operations/jobs.html +6 -6
  118. package/dist/ui/operations/maintenance.html +6 -6
  119. package/dist/ui/operations/observability.html +6 -6
  120. package/dist/ui/operations/previews.html +6 -6
  121. package/dist/ui/operations/queue.html +6 -6
  122. package/dist/ui/operations/regions.html +6 -6
  123. package/dist/ui/operations/releases.html +6 -6
  124. package/dist/ui/operations/spend.html +6 -6
  125. package/dist/ui/operations/workloads.html +6 -6
  126. package/dist/ui/security.html +1 -1
  127. package/dist/ui/server/actions.html +6 -6
  128. package/dist/ui/server/activity.html +1 -1
  129. package/dist/ui/server/capacity.html +6 -6
  130. package/dist/ui/server/database.html +6 -6
  131. package/dist/ui/server/deployments.html +6 -6
  132. package/dist/ui/server/diagnostics.html +2 -2
  133. package/dist/ui/server/firewall.html +6 -6
  134. package/dist/ui/server/fleet.html +6 -6
  135. package/dist/ui/server/logs.html +6 -6
  136. package/dist/ui/server/metrics.html +6 -6
  137. package/dist/ui/server/security.html +1 -1
  138. package/dist/ui/server/services.html +2 -2
  139. package/dist/ui/server/sites.html +6 -6
  140. package/dist/ui/server/ssh-keys.html +6 -6
  141. package/dist/ui/server/team.html +6 -6
  142. package/dist/ui/server/terminal.html +1 -1
  143. package/dist/ui/serverless/alarms.html +5 -5
  144. package/dist/ui/serverless/assets.html +2 -2
  145. package/dist/ui/serverless/cost.html +2 -2
  146. package/dist/ui/serverless/data.html +6 -6
  147. package/dist/ui/serverless/deployments.html +2 -2
  148. package/dist/ui/serverless/firewall.html +2 -2
  149. package/dist/ui/serverless/functions.html +6 -6
  150. package/dist/ui/serverless/logs.html +6 -6
  151. package/dist/ui/serverless/metrics.html +2 -2
  152. package/dist/ui/serverless/queues.html +6 -6
  153. package/dist/ui/serverless/secrets.html +6 -6
  154. package/dist/ui/serverless/traces.html +6 -6
  155. package/dist/ui/serverless.html +6 -6
  156. package/package.json +3 -3
  157. package/dist/bin/chunk-2g1j00yc.js +0 -1
  158. package/dist/bin/chunk-4xmhrvfa.js +0 -1
  159. package/dist/bin/chunk-6crapvp1.js +0 -1
  160. package/dist/bin/chunk-7b4gf64x.js +0 -1
  161. package/dist/bin/chunk-818tj49e.js +0 -1
  162. package/dist/bin/chunk-92qsww97.js +0 -1
  163. package/dist/bin/chunk-9947rscj.js +0 -1
  164. package/dist/bin/chunk-cyap08qg.js +0 -1
  165. package/dist/bin/chunk-dk92s260.js +0 -1
  166. package/dist/bin/chunk-ejxp74ks.js +0 -1
  167. package/dist/bin/chunk-gx98tkpf.js +0 -1
  168. package/dist/bin/chunk-hcdbw9j1.js +0 -1
  169. package/dist/bin/chunk-kay11qc7.js +0 -1
  170. package/dist/bin/chunk-n28a9a9c.js +0 -1
  171. package/dist/bin/chunk-q8w7fa56.js +0 -1
  172. package/dist/bin/chunk-qdnx952p.js +0 -1
  173. package/dist/bin/chunk-tr0pkm4p.js +0 -1
  174. package/dist/bin/chunk-tytvrehe.js +0 -1
  175. package/dist/bin/chunk-wpp0fa94.js +0 -1
  176. package/dist/bin/chunk-xzgxwnb7.js +0 -1
  177. package/dist/bin/chunk-y21yk6zv.js +0 -1
  178. package/dist/bin/chunk-yt1t5ct8.js +0 -1
  179. package/dist/bin/chunk-zs8ddeaz.js +0 -1
  180. package/dist/chunk-e4qh4c2n.js +0 -1
  181. package/dist/chunk-pj9z4fjv.js +0 -1
  182. package/dist/chunk-twhbns31.js +0 -1
  183. package/dist/chunk-wkg22nj5.js +0 -1
  184. package/dist/chunk-xtd0s5ep.js +0 -1
@@ -1 +1 @@
1
- import{Yi}from"./chunk-21zhm1mk.js";var Ou="\x00";function Xl(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function g(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function wa(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!Xl(t.path,i.path))return!1;if(t.host&&!g(t.host,i.host??""))return!1;return!0}function Ca(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class Ql{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>wa(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=Ca(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!wa(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=Ca(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Lu(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function Mu(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var m="protection.controls",Gt=24,un=4,R={ipRules:{allow:[],block:[]}};function p(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function h(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Gt,Math.max(0.25,e))}var f=500;class Kt{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(m);if(!t||typeof t!=="object"||Array.isArray(t))return{...R,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(m,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:p(i.attackMode,t),mitigationPause:p(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+h(t.hours,un)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+h(t.hours,Gt)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!Yi(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>f)throw Error(`At most ${f} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Ii(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function Uu(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function pn(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function jo(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:pn(o,i)}}}}export{Ou,Xl,wa,Ca,Ql,Lu,Mu,Gt,un,Kt,Ii,Uu,pn,jo};
1
+ import{Yi}from"./chunk-wsedynyb.js";var Lu="\x00";function Ql(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function g(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function Ca(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!Ql(t.path,i.path))return!1;if(t.host&&!g(t.host,i.host??""))return!1;return!0}function Aa(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class Yl{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>Ca(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=Aa(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!Ca(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=Aa(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Mu(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function Uu(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var m="protection.controls",Gt=24,un=4,R={ipRules:{allow:[],block:[]}};function p(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function h(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Gt,Math.max(0.25,e))}var f=500;class Kt{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(m);if(!t||typeof t!=="object"||Array.isArray(t))return{...R,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(m,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:p(i.attackMode,t),mitigationPause:p(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+h(t.hours,un)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+h(t.hours,Gt)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!Yi(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>f)throw Error(`At most ${f} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Ii(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function Bu(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function pn(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function Vo(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:pn(o,i)}}}}export{Lu,Ql,Ca,Aa,Yl,Mu,Uu,Gt,un,Kt,Ii,Bu,pn,Vo};
@@ -1,8 +1,8 @@
1
- var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function Xe(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function hs(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?ic(n.path):".*";if(!hs(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${Xe(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Xe(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Xe(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${Xe(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${Xe(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function ic(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function oi(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
1
+ var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function Xe(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function ys(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?oc(n.path):".*";if(!ys(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${Xe(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Xe(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Xe(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${Xe(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${Xe(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function oc(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function oi(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
2
2
  `)}
3
- `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${Xe(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=ic(a);if(!hs(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${Xe(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${Xe(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${Xe(a.reason)}`),a.pathPattern){if(!hs(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${Xe(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
3
+ `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${Xe(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=oc(a);if(!ys(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${Xe(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${Xe(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${Xe(a.reason)}`),a.pathPattern){if(!ys(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${Xe(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
4
4
  `)}
5
- `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function ys(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=oi(e,r);return`#!/usr/bin/env bash
5
+ `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function Ss(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=oi(e,r);return`#!/usr/bin/env bash
6
6
  # Managed by ts-cloud. Installs the zig-waf ruleset.
7
7
  set -euo pipefail
8
8
 
@@ -33,5 +33,5 @@ fi
33
33
 
34
34
  mv "${s}.new" "${s}"
35
35
  echo "ts-cloud: WAF config installed (mode: ${n.mode})"
36
- `}function sp(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
- export{Xe,hs,ic,oi,ys,sp};
36
+ `}function ap(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
+ export{Xe,ys,oc,oi,Ss,ap};
@@ -1,4 +1,4 @@
1
- import{Yr,W,so,Lt,L}from"./chunk-k1eezsj1.js";import{v}from"./chunk-0r45d0s3.js";import{w}from"./chunk-en7sf83z.js";import{g}from"./chunk-j0zg3mbm.js";import{U}from"./chunk-8vm7tpyv.js";function _(t){let{bucketName:s,domain:l,aliases:e,certificateArn:p,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:A=!1,computeOriginDomain:D,computeOriginPort:O=3008,computeOriginId:F="app-compute",retainOnStackDelete:B=!1}=t,C=B?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},h=A&&!!D,V=h?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],E=h?["GET","HEAD"]:["GET","HEAD"],R={},x={};R.S3Bucket={Type:"AWS::S3::Bucket",...C,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},x.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},x.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},R.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...C,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let y;if(a&&h)y="InstallRootRedirectFunction",R[y]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
1
+ import{Yr,W,so,Lt,L}from"./chunk-prj5b597.js";import{v}from"./chunk-9e7pqhj1.js";import{w}from"./chunk-m2gwzksz.js";import{g}from"./chunk-2q27v6vz.js";import{U}from"./chunk-5kc8s9gp.js";function _(t){let{bucketName:s,domain:l,aliases:e,certificateArn:p,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:A=!1,computeOriginDomain:D,computeOriginPort:O=3008,computeOriginId:F="app-compute",retainOnStackDelete:B=!1}=t,C=B?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},h=A&&!!D,V=h?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],E=h?["GET","HEAD"]:["GET","HEAD"],R={},x={};R.S3Bucket={Type:"AWS::S3::Bucket",...C,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},x.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},x.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},R.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...C,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let y;if(a&&h)y="InstallRootRedirectFunction",R[y]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
2
2
  var request = event.request;
3
3
  if (request.uri === '/' || request.uri === '') {
4
4
  return {
@@ -42,7 +42,7 @@ import{Yr,W,so,Lt,L}from"./chunk-k1eezsj1.js";import{v}from"./chunk-0r45d0s3.js"
42
42
  │ │
43
43
  │ Verification typically takes 1-2 business days. │
44
44
  │ After verification, re-run: bunx bunpress deploy │
45
- └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:x,stackName:i,bucket:h,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:x,stackName:i,bucket:h,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],S=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,b=S("DistributionDomain");if(b&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,b);else if(b&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:x,stackName:i,bucket:S("BucketName")||h,distributionId:S("DistributionId"),distributionDomain:b,domain:e,certificateArn:A,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Yr){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let A of d.records){let D=A.name.replace(/\.$/,"");if(D===s||D==="")console.log(`Removing existing root A record (${A.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:A.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function Ri(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(p);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new g(p.region||"us-east-1").emptyBucket(i.bucket)}catch(A){console.log(`Note: Could not clean bucket: ${A.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-dk92s260.js"),a=await r({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(A,D,O)=>{e?.("upload",`${A}/${D}: ${O}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:A}=await import("./chunk-dk92s260.js");await A(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Yl(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:p,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
45
+ └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:x,stackName:i,bucket:h,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:x,stackName:i,bucket:h,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],S=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,b=S("DistributionDomain");if(b&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,b);else if(b&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:x,stackName:i,bucket:S("BucketName")||h,distributionId:S("DistributionId"),distributionDomain:b,domain:e,certificateArn:A,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Yr){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let A of d.records){let D=A.name.replace(/\.$/,"");if(D===s||D==="")console.log(`Removing existing root A record (${A.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:A.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function Ri(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(p);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new g(p.region||"us-east-1").emptyBucket(i.bucket)}catch(A){console.log(`Note: Could not clean bucket: ${A.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-78w3bn85.js"),a=await r({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(A,D,O)=>{e?.("upload",`${A}/${D}: ${O}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:A}=await import("./chunk-78w3bn85.js");await A(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Zl(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:p,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
46
46
  const request = event.request;
47
47
  var uri = request.uri;
48
48
 
@@ -56,5 +56,5 @@ import{Yr,W,so,Lt,L}from"./chunk-k1eezsj1.js";import{v}from"./chunk-0r45d0s3.js"
56
56
  }
57
57
 
58
58
  return request;
59
- }`}};let A={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(l&&e)A.Aliases=[l],A.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else A.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(a.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:A}},d.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},d.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},a.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},l&&p)a.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:l,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},a.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:l,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},d.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${l||s}`,Resources:a,Outputs:d}}async function Zl(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let u=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!u)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return G({siteName:t.siteName,region:t.region,domain:u,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",l="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let p=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new v(l),a=new U,d=new W("us-east-1"),A=new so("us-east-1"),{hostedZoneId:D,certificateArn:O}=t;if(e&&!D){let u=await a.findHostedZoneForDomain(e);if(u)D=u.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:p,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!O&&D){let u=await d.findCertificateByDomain(e);if(u&&u.Status==="ISSUED")O=u.CertificateArn;else O=(await A.requestAndValidate({domainName:e,hostedZoneId:D,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let F=!1,B;try{let u=await r.describeStacks({stackName:i});if(u.Stacks.length>0){let S=u.Stacks[0],b=S.StackStatus;if(b==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),F=!1;else if(b==="DELETE_COMPLETE")F=!1;else F=!0,B=(S.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(u){if(u.message?.includes("does not exist")||u.code==="ValidationError")F=!1;else throw u}let C=B||p;if(!F){let u=new g(s),S=new w,b=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await S.listDistributions();for(let n of o){let m=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))m=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let f=n.Aliases.Items.CNAME;if(typeof f==="string")m=[f];else if(Array.isArray(f))m=f}}if(m.includes(e)){b=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let c=(await S.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,k;if(c){let P=[];if(Array.isArray(c))P=c;else if(c.Origin)P=Array.isArray(c.Origin)?c.Origin:[c.Origin];else P=[c];for(let I of P){let T=(I.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(T){k=T[1];break}}}if(k){let P=e.replace(/\./g,"-");if(!k.startsWith(P)&&!k.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${k}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${k}`),D&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"A",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"AAAA",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(I){console.log(`Note: Could not update Route53 records: ${I.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:k,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:O,message:"Using existing CloudFront distribution"}}}}}catch{}if(D)try{let n=(await a.listResourceRecordSets({HostedZoneId:D})).ResourceRecordSets||[];for(let m of n)if(m.Name===`${e}.`&&(m.Type==="A"||m.Type==="AAAA")){if(m.AliasTarget){console.log(`Found orphaned Route53 ${m.Type} record for ${e}, cleaning up...`);try{await a.deleteRecord({HostedZoneId:D,RecordSet:m}),console.log(`Deleted orphaned Route53 ${m.Type} record for ${e}`)}catch(f){console.log(`Note: Could not delete Route53 record: ${f.message}`)}}}}catch{}}if(!b)try{if((await u.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let n=u.emptyBucket(p).then(()=>u.deleteBucket(p)),m=new Promise((f,c)=>setTimeout(()=>c(Error("Bucket cleanup timeout")),30000));await Promise.race([n,m]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let m=Date.now().toString(36);C=`${p}-${m}`,console.log(`Using alternative bucket name: ${C}`)}}}catch{}}let h=Yl({bucketName:C,domain:e,certificateArn:O,hostedZoneId:D,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),V=Object.entries(t.tags||{}).map(([u,S])=>({Key:u,Value:S}));V.push({Key:"ManagedBy",Value:"ts-cloud"}),V.push({Key:"Application",Value:t.siteName});let E,R=!1;if(F){R=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${C}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${O||"not specified"}`);try{E=(await r.updateStack({stackName:i,templateBody:JSON.stringify(h),capabilities:["CAPABILITY_IAM"],tags:V})).StackId,console.log(`Update initiated, stack ID: ${E}`)}catch(u){if(u.message?.includes("No updates are to be performed")){let S=await r.describeStacks({stackName:i});E=S.Stacks[0].StackId;let b=S.Stacks[0]?.Outputs||[],o=(n)=>b.find((m)=>m.OutputKey===n)?.OutputValue;return{success:!0,stackId:E,stackName:i,bucket:o("BucketName")||C,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:O,message:"Static site infrastructure is already up to date"}}else throw u}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${C}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${O||"not specified"}`),console.log("Stack does not exist, creating..."),E=(await r.createStack({stackName:i,templateBody:JSON.stringify(h),capabilities:["CAPABILITY_IAM"],tags:V,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${E}`);console.log(`Waiting for stack to reach ${R?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,R?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(u){if(u.message?.includes("must be verified")||u.message?.includes("Access denied for operation")||u.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let S=new w;if(e)try{let b=await S.listDistributions();for(let o of b){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let m=o.Aliases.Items.CNAME;if(typeof m==="string")n=[m];else if(Array.isArray(m))n=m}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let f=(await S.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,c;if(f){let k=[];if(Array.isArray(f))k=f;else if(f.Origin)k=Array.isArray(f.Origin)?f.Origin:[f.Origin];else k=[f];for(let P of k){let M=(P.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(M){c=M[1];break}}}if(c)return console.log(`Using existing S3 bucket: ${c}`),{success:!0,stackName:`existing-${o.Id}`,bucket:c,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:O,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let b=new g(s);if((await b.headBucket(C)).exists)console.log(`Using existing S3 bucket: ${C}`);else console.log(`Creating S3 bucket: ${C}...`),await b.createBucket(C);await b.putBucketWebsite(C,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await b.putPublicAccessBlock(C,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${C} configured`);let n=`OAC-${C}`;console.log(`Creating Origin Access Control: ${n}...`);let m=await S.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${m.Id} ready`),console.log("Creating CloudFront distribution...");let f=await S.createDistributionForS3({bucketName:C,bucketRegion:s,originAccessControlId:m.Id,aliases:e?[e]:[],certificateArn:O,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||C}`});console.log(`CloudFront distribution ${f.Id} created`),console.log("Updating S3 bucket policy...");let c=w.getS3BucketPolicyForCloudFront(C,f.ARN);if(await b.putBucketPolicy(C,c),console.log("S3 bucket policy updated"),e&&D){console.log(`Creating Route53 records for ${e}...`);try{await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"A",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"AAAA",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(k){console.log(`Note: Could not create Route53 records: ${k.message}`)}}return{success:!0,stackName:`direct-${f.Id}`,bucket:C,distributionId:f.Id,distributionDomain:f.DomainName,domain:e,certificateArn:O,message:"Static site infrastructure created via direct API calls"}}catch(b){return console.log(`Direct API creation failed: ${b.message}`),{success:!1,stackId:E,stackName:i,bucket:C,message:`Deployment failed: ${b.message}`}}}return{success:!1,stackId:E,stackName:i,bucket:C,message:`Stack deployment failed: ${u.message}`}}let y=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],N=(u)=>y.find((S)=>S.OutputKey===u)?.OutputValue;return{success:!0,stackId:E,stackName:i,bucket:N("BucketName")||C,distributionId:N("DistributionId"),distributionDomain:N("DistributionDomain"),domain:e,certificateArn:O,message:"Static site infrastructure deployed successfully"}}async function ed(t){let{sourceDir:s,bucket:l,region:e,cacheControl:p="max-age=31536000, public",onProgress:i}=t,r=new g(e),{readdir:a}=await import("node:fs/promises"),{join:d,relative:A}=await import("node:path"),{createHash:D}=await import("node:crypto");async function O(y){let N=[],u=await a(y,{withFileTypes:!0});for(let S of u){let b=d(y,S.name);if(S.isDirectory())N.push(...await O(b));else N.push(b)}return N}function F(y){let N=y.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[N||""]||"application/octet-stream"}function B(y){return D("md5").update(y).digest("hex")}async function C(){let y=new Map,N;do{let u=await r.listObjects({bucket:l,maxKeys:1000,continuationToken:N});for(let S of u.objects){let b=S.ETag?.replace(/"/g,"")||"";y.set(S.Key,b)}N=u.nextContinuationToken}while(N);return y}let h=await O(s),V=[],E=0,R=0,x=await C();for(let y of h){let N=A(s,y),u=F(y),S=y.endsWith(".html")?"max-age=3600, public":p;try{let b=Buffer.from(await Bun.file(y).arrayBuffer()),o=B(b),n=x.get(N);if(n&&n===o){R++,i?.(E+R,h.length,N);continue}await r.putObject({bucket:l,key:N,body:b,contentType:u,cacheControl:S}),E++,i?.(E+R,h.length,N)}catch(b){V.push(`Failed to upload ${N}: ${b.message}`)}}return{uploaded:E,skipped:R,errors:V}}async function td(t){return{invalidationId:(await new w().invalidateAll(t)).Id}}async function Fu(t,s="us-east-1"){let l=new v(s);try{let r=((await l.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((a)=>a.OutputKey==="BucketName")?.OutputValue;if(r)await new g(s).emptyBucket(r)}catch{}await l.deleteStack(t);let e=await l.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function ju(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await Zl(p);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new g(p.region||"us-east-1").emptyBucket(i.bucket)}catch(d){console.log(`Note: Could not clean bucket: ${d.message}`)}}e?.("upload","Uploading files to S3...");let r=await ed({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(d,A,D)=>{e?.("upload",`${d}/${A}: ${D}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await td(i.distributionId);e?.("complete","Deployment complete!");let a=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:a}}
60
- export{Yl,Zl,ed,td,Fu,ju,Ri};
59
+ }`}};let A={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(l&&e)A.Aliases=[l],A.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else A.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(a.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:A}},d.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},d.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},a.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},l&&p)a.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:l,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},a.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:l,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},d.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${l||s}`,Resources:a,Outputs:d}}async function ed(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let u=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!u)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return G({siteName:t.siteName,region:t.region,domain:u,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",l="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let p=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new v(l),a=new U,d=new W("us-east-1"),A=new so("us-east-1"),{hostedZoneId:D,certificateArn:O}=t;if(e&&!D){let u=await a.findHostedZoneForDomain(e);if(u)D=u.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:p,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!O&&D){let u=await d.findCertificateByDomain(e);if(u&&u.Status==="ISSUED")O=u.CertificateArn;else O=(await A.requestAndValidate({domainName:e,hostedZoneId:D,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let F=!1,B;try{let u=await r.describeStacks({stackName:i});if(u.Stacks.length>0){let S=u.Stacks[0],b=S.StackStatus;if(b==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),F=!1;else if(b==="DELETE_COMPLETE")F=!1;else F=!0,B=(S.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(u){if(u.message?.includes("does not exist")||u.code==="ValidationError")F=!1;else throw u}let C=B||p;if(!F){let u=new g(s),S=new w,b=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await S.listDistributions();for(let n of o){let m=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))m=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let f=n.Aliases.Items.CNAME;if(typeof f==="string")m=[f];else if(Array.isArray(f))m=f}}if(m.includes(e)){b=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let c=(await S.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,k;if(c){let P=[];if(Array.isArray(c))P=c;else if(c.Origin)P=Array.isArray(c.Origin)?c.Origin:[c.Origin];else P=[c];for(let I of P){let T=(I.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(T){k=T[1];break}}}if(k){let P=e.replace(/\./g,"-");if(!k.startsWith(P)&&!k.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${k}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${k}`),D&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"A",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"AAAA",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(I){console.log(`Note: Could not update Route53 records: ${I.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:k,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:O,message:"Using existing CloudFront distribution"}}}}}catch{}if(D)try{let n=(await a.listResourceRecordSets({HostedZoneId:D})).ResourceRecordSets||[];for(let m of n)if(m.Name===`${e}.`&&(m.Type==="A"||m.Type==="AAAA")){if(m.AliasTarget){console.log(`Found orphaned Route53 ${m.Type} record for ${e}, cleaning up...`);try{await a.deleteRecord({HostedZoneId:D,RecordSet:m}),console.log(`Deleted orphaned Route53 ${m.Type} record for ${e}`)}catch(f){console.log(`Note: Could not delete Route53 record: ${f.message}`)}}}}catch{}}if(!b)try{if((await u.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let n=u.emptyBucket(p).then(()=>u.deleteBucket(p)),m=new Promise((f,c)=>setTimeout(()=>c(Error("Bucket cleanup timeout")),30000));await Promise.race([n,m]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let m=Date.now().toString(36);C=`${p}-${m}`,console.log(`Using alternative bucket name: ${C}`)}}}catch{}}let h=Zl({bucketName:C,domain:e,certificateArn:O,hostedZoneId:D,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),V=Object.entries(t.tags||{}).map(([u,S])=>({Key:u,Value:S}));V.push({Key:"ManagedBy",Value:"ts-cloud"}),V.push({Key:"Application",Value:t.siteName});let E,R=!1;if(F){R=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${C}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${O||"not specified"}`);try{E=(await r.updateStack({stackName:i,templateBody:JSON.stringify(h),capabilities:["CAPABILITY_IAM"],tags:V})).StackId,console.log(`Update initiated, stack ID: ${E}`)}catch(u){if(u.message?.includes("No updates are to be performed")){let S=await r.describeStacks({stackName:i});E=S.Stacks[0].StackId;let b=S.Stacks[0]?.Outputs||[],o=(n)=>b.find((m)=>m.OutputKey===n)?.OutputValue;return{success:!0,stackId:E,stackName:i,bucket:o("BucketName")||C,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:O,message:"Static site infrastructure is already up to date"}}else throw u}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${C}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${O||"not specified"}`),console.log("Stack does not exist, creating..."),E=(await r.createStack({stackName:i,templateBody:JSON.stringify(h),capabilities:["CAPABILITY_IAM"],tags:V,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${E}`);console.log(`Waiting for stack to reach ${R?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,R?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(u){if(u.message?.includes("must be verified")||u.message?.includes("Access denied for operation")||u.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let S=new w;if(e)try{let b=await S.listDistributions();for(let o of b){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let m=o.Aliases.Items.CNAME;if(typeof m==="string")n=[m];else if(Array.isArray(m))n=m}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let f=(await S.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,c;if(f){let k=[];if(Array.isArray(f))k=f;else if(f.Origin)k=Array.isArray(f.Origin)?f.Origin:[f.Origin];else k=[f];for(let P of k){let M=(P.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(M){c=M[1];break}}}if(c)return console.log(`Using existing S3 bucket: ${c}`),{success:!0,stackName:`existing-${o.Id}`,bucket:c,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:O,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let b=new g(s);if((await b.headBucket(C)).exists)console.log(`Using existing S3 bucket: ${C}`);else console.log(`Creating S3 bucket: ${C}...`),await b.createBucket(C);await b.putBucketWebsite(C,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await b.putPublicAccessBlock(C,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${C} configured`);let n=`OAC-${C}`;console.log(`Creating Origin Access Control: ${n}...`);let m=await S.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${m.Id} ready`),console.log("Creating CloudFront distribution...");let f=await S.createDistributionForS3({bucketName:C,bucketRegion:s,originAccessControlId:m.Id,aliases:e?[e]:[],certificateArn:O,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||C}`});console.log(`CloudFront distribution ${f.Id} created`),console.log("Updating S3 bucket policy...");let c=w.getS3BucketPolicyForCloudFront(C,f.ARN);if(await b.putBucketPolicy(C,c),console.log("S3 bucket policy updated"),e&&D){console.log(`Creating Route53 records for ${e}...`);try{await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"A",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:D,Name:e,Type:"AAAA",TargetHostedZoneId:U.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(k){console.log(`Note: Could not create Route53 records: ${k.message}`)}}return{success:!0,stackName:`direct-${f.Id}`,bucket:C,distributionId:f.Id,distributionDomain:f.DomainName,domain:e,certificateArn:O,message:"Static site infrastructure created via direct API calls"}}catch(b){return console.log(`Direct API creation failed: ${b.message}`),{success:!1,stackId:E,stackName:i,bucket:C,message:`Deployment failed: ${b.message}`}}}return{success:!1,stackId:E,stackName:i,bucket:C,message:`Stack deployment failed: ${u.message}`}}let y=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],N=(u)=>y.find((S)=>S.OutputKey===u)?.OutputValue;return{success:!0,stackId:E,stackName:i,bucket:N("BucketName")||C,distributionId:N("DistributionId"),distributionDomain:N("DistributionDomain"),domain:e,certificateArn:O,message:"Static site infrastructure deployed successfully"}}async function td(t){let{sourceDir:s,bucket:l,region:e,cacheControl:p="max-age=31536000, public",onProgress:i}=t,r=new g(e),{readdir:a}=await import("node:fs/promises"),{join:d,relative:A}=await import("node:path"),{createHash:D}=await import("node:crypto");async function O(y){let N=[],u=await a(y,{withFileTypes:!0});for(let S of u){let b=d(y,S.name);if(S.isDirectory())N.push(...await O(b));else N.push(b)}return N}function F(y){let N=y.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[N||""]||"application/octet-stream"}function B(y){return D("md5").update(y).digest("hex")}async function C(){let y=new Map,N;do{let u=await r.listObjects({bucket:l,maxKeys:1000,continuationToken:N});for(let S of u.objects){let b=S.ETag?.replace(/"/g,"")||"";y.set(S.Key,b)}N=u.nextContinuationToken}while(N);return y}let h=await O(s),V=[],E=0,R=0,x=await C();for(let y of h){let N=A(s,y),u=F(y),S=y.endsWith(".html")?"max-age=3600, public":p;try{let b=Buffer.from(await Bun.file(y).arrayBuffer()),o=B(b),n=x.get(N);if(n&&n===o){R++,i?.(E+R,h.length,N);continue}await r.putObject({bucket:l,key:N,body:b,contentType:u,cacheControl:S}),E++,i?.(E+R,h.length,N)}catch(b){V.push(`Failed to upload ${N}: ${b.message}`)}}return{uploaded:E,skipped:R,errors:V}}async function rd(t){return{invalidationId:(await new w().invalidateAll(t)).Id}}async function ju(t,s="us-east-1"){let l=new v(s);try{let r=((await l.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((a)=>a.OutputKey==="BucketName")?.OutputValue;if(r)await new g(s).emptyBucket(r)}catch{}await l.deleteStack(t);let e=await l.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function Vu(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await ed(p);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new g(p.region||"us-east-1").emptyBucket(i.bucket)}catch(d){console.log(`Note: Could not clean bucket: ${d.message}`)}}e?.("upload","Uploading files to S3...");let r=await td({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(d,A,D)=>{e?.("upload",`${d}/${A}: ${D}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await rd(i.distributionId);e?.("complete","Deployment complete!");let a=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:a}}
60
+ export{Zl,ed,td,rd,ju,Vu,Ri};
@@ -0,0 +1 @@
1
+ import{w}from"./chunk-m2gwzksz.js";import"./chunk-q3xwh0r8.js";export{w as CloudFrontClient};
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-t1jpqn4x.js";import{_}from"./chunk-cas0bp91.js";class v{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!o)o=k.ResourceStatusReason}}catch{}let l=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((r,m)=>{t[`Parameters.member.${m+1}.ParameterKey`]=r.ParameterKey,t[`Parameters.member.${m+1}.ParameterValue`]=r.ParameterValue});if(e.capabilities)e.capabilities.forEach((r,m)=>{t[`Capabilities.member.${m+1}`]=r});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=_(s,"CreateChangeSet");return{Id:a?.Id,StackId:a?.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!n.has(g))n.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=o.Stacks[0];if(m.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
1
+ import{u}from"./chunk-q3xwh0r8.js";import{_}from"./chunk-a3rq51az.js";class v{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!o)o=k.ResourceStatusReason}}catch{}let l=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((r,m)=>{t[`Parameters.member.${m+1}.ParameterKey`]=r.ParameterKey,t[`Parameters.member.${m+1}.ParameterValue`]=r.ParameterValue});if(e.capabilities)e.capabilities.forEach((r,m)=>{t[`Capabilities.member.${m+1}`]=r});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=_(s,"CreateChangeSet");return{Id:a?.Id,StackId:a?.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!n.has(g))n.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=o.Stacks[0];if(m.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
2
  export{v};
@@ -0,0 +1 @@
1
+ import{Jn}from"./chunk-wffaqgcc.js";import"./chunk-ax41jhq7.js";import"./chunk-c35qm7as.js";import"./chunk-9e7pqhj1.js";import"./chunk-0md2h0an.js";import"./chunk-2q27v6vz.js";import"./chunk-q3xwh0r8.js";import"./chunk-jdfbahjb.js";export{Jn as resolveServerDashboardData};
@@ -1,2 +1,2 @@
1
- function _(n,r){return(n?.[`${r}Response`]??n)?.[`${r}Result`]}function ee(n){if(n===void 0||n===null||n==="")return[];return Array.isArray(n)?n:[n]}function js(n){return n===!0||n==="true"}
2
- export{_,ee,js};
1
+ function _(n,r){return(n?.[`${r}Response`]??n)?.[`${r}Result`]}function ee(n){if(n===void 0||n===null||n==="")return[];return Array.isArray(n)?n:[n]}function Vs(n){return n===!0||n==="true"}
2
+ export{_,ee,Vs};
@@ -1 +1 @@
1
- import{Tr,pc,mc,Tt,Er,wr,Cr,Ar,nn}from"./chunk-f3sd1hpa.js";import"./chunk-wyanqf91.js";import"./chunk-tyqxz92e.js";export{Er as AwsSecretsManagerConfigurationBackend,wr as AwsSsmConfigurationBackend,Ar as ConfigurationService,Tr as ConfigurationStore,Cr as ExternalConfigurationBackend,Tt as LocalEncryptedConfigurationBackend,pc as parseDotenv,mc as serializeDotenv,nn as synchronizeConfiguredConfiguration};
1
+ import{Tr,mc,gc,Tt,Er,wr,Cr,Ar,nn}from"./chunk-6eesa8d1.js";import"./chunk-257sygzm.js";import"./chunk-jdfbahjb.js";export{Er as AwsSecretsManagerConfigurationBackend,wr as AwsSsmConfigurationBackend,Ar as ConfigurationService,Tr as ConfigurationStore,Cr as ExternalConfigurationBackend,Tt as LocalEncryptedConfigurationBackend,mc as parseDotenv,gc as serializeDotenv,nn as synchronizeConfiguredConfiguration};
@@ -1,4 +1,4 @@
1
- import{u}from"./chunk-t1jpqn4x.js";class X{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,a)=>{t[`InstanceId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeInstancesResponse||s;return{Reservations:this.parseReservations(n.reservationSet?.item),NextToken:n.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let s={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)s.Latest="true";let n=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()}),r=n.GetConsoleOutputResponse||n;return{InstanceId:r.instanceId,Output:r.output,Timestamp:r.timestamp}}async getConsoleOutputDecoded(e,t){let s=await this.getConsoleOutput(e,t?.latest);if(!s.Output)return"No console output available yet";let n=Buffer.from(s.Output,"base64").toString("utf-8");if(t?.tailLines)return n.split(`
1
+ import{u}from"./chunk-q3xwh0r8.js";class X{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,a)=>{t[`InstanceId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeInstancesResponse||s;return{Reservations:this.parseReservations(n.reservationSet?.item),NextToken:n.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let s={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)s.Latest="true";let n=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()}),r=n.GetConsoleOutputResponse||n;return{InstanceId:r.instanceId,Output:r.output,Timestamp:r.timestamp}}async getConsoleOutputDecoded(e,t){let s=await this.getConsoleOutput(e,t?.latest);if(!s.Output)return"No console output available yet";let n=Buffer.from(s.Output,"base64").toString("utf-8");if(t?.tailLines)return n.split(`
2
2
  `).slice(-t.tailLines).join(`
3
3
  `);return n}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(s.instanceStatusSet?.item).map((n)=>({InstanceId:n.instanceId,InstanceState:n.instanceState?{Code:Number.parseInt(n.instanceState.code),Name:n.instanceState.name}:void 0,InstanceStatus:n.instanceStatus?{Status:n.instanceStatus.status,Details:this.parseArray(n.instanceStatus.details?.item).map((r)=>({Name:r.name,Status:r.status}))}:void 0,SystemStatus:n.systemStatus?{Status:n.systemStatus.status,Details:this.parseArray(n.systemStatus.details?.item).map((r)=>({Name:r.name,Status:r.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(s.instancesSet?.item).map((n)=>({InstanceId:n.instanceId,CurrentState:n.currentState?{Name:n.currentState.name}:void 0,PreviousState:n.previousState?{Name:n.previousState.name}:void 0}))}}async stopInstances(e,t){let s={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((r,a)=>{s[`InstanceId.${a+1}`]=r}),t)s.Force="true";let n=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()});return{StoppingInstances:this.parseArray(n.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((s,n)=>{t[`InstanceId.${n+1}`]=s}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(s.instancesSet?.item).map((n)=>({InstanceId:n.instanceId,CurrentState:n.currentState?{Name:n.currentState.name}:void 0,PreviousState:n.previousState?{Name:n.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(s.CreateImageResponse||s).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((n,r)=>{t[`VpcId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(s.vpcSet?.item).map((n)=>({VpcId:n.vpcId,CidrBlock:n.cidrBlock,State:n.state,DhcpOptionsId:n.dhcpOptionsId,InstanceTenancy:n.instanceTenancy,IsDefault:n.isDefault==="true",Tags:this.parseTags(n.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((n,r)=>{t[`SubnetId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(s.subnetSet?.item).map((n)=>({SubnetId:n.subnetId,VpcId:n.vpcId,CidrBlock:n.cidrBlock,AvailabilityZone:n.availabilityZone,AvailableIpAddressCount:Number.parseInt(n.availableIpAddressCount),State:n.state,MapPublicIpOnLaunch:n.mapPublicIpOnLaunch==="true",Tags:this.parseTags(n.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((n,r)=>{t[`GroupId.${r+1}`]=n});if(e?.GroupNames)e.GroupNames.forEach((n,r)=>{t[`GroupName.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(s.securityGroupInfo?.item).map((n)=>({GroupId:n.groupId,GroupName:n.groupName,Description:n.groupDescription,VpcId:n.vpcId,IpPermissions:this.parseIpPermissions(n.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(n.ipPermissionsEgress?.item),Tags:this.parseTags(n.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((n,r)=>{t[`InternetGatewayId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(s.internetGatewaySet?.item).map((n)=>({InternetGatewayId:n.internetGatewayId,Attachments:this.parseArray(n.attachmentSet?.item).map((r)=>({VpcId:r.vpcId,State:r.state})),Tags:this.parseTags(n.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((n,r)=>{t[`AllocationId.${r+1}`]=n});if(e?.PublicIps)e.PublicIps.forEach((n,r)=>{t[`PublicIp.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(s.addressesSet?.item).map((n)=>({PublicIp:n.publicIp,AllocationId:n.allocationId,AssociationId:n.associationId,InstanceId:n.instanceId,NetworkInterfaceId:n.networkInterfaceId,PrivateIpAddress:n.privateIpAddress,Domain:n.domain,Tags:this.parseTags(n.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((n,r)=>{t[`TagSpecification.${r+1}.ResourceType`]=n.ResourceType,n.Tags.forEach((a,i)=>{t[`TagSpecification.${r+1}.Tag.${i+1}.Key`]=a.Key,t[`TagSpecification.${r+1}.Tag.${i+1}.Value`]=a.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:s.allocationId,PublicIp:s.publicIp,Domain:s.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((s,n)=>{t[`ResourceId.${n+1}`]=s}),e.Tags.forEach((s,n)=>{t[`Tag.${n+1}.Key`]=s.Key,t[`Tag.${n+1}.Value`]=s.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,s){let n=s?.maxWaitMs||300000,r=s?.pollIntervalMs||5000,a=Date.now();while(Date.now()-a<n){let i;try{i=await this.getInstance(e)}catch{i=void 0}if(i?.State?.Name===t)return i;await new Promise((c)=>setTimeout(c,r))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((a,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=a.ResourceType,a.Tags.forEach((c,o)=>{t[`TagSpecification.${i+1}.Tag.${o+1}.Key`]=c.Key,t[`TagSpecification.${i+1}.Tag.${o+1}.Value`]=c.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=(s.CreateVpcResponse||s).vpc;return{Vpc:r?{VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((a,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=a.ResourceType,a.Tags.forEach((c,o)=>{t[`TagSpecification.${i+1}.Tag.${o+1}.Key`]=c.Key,t[`TagSpecification.${i+1}.Tag.${o+1}.Value`]=c.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=(s.CreateSubnetResponse||s).subnet;return{Subnet:r?{SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:r.availableIpAddressCount?Number.parseInt(r.availableIpAddressCount):void 0,State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(s.CreateSecurityGroupResponse||s).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((r,a)=>{t[`RouteTableId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeRouteTablesResponse||s;return{RouteTables:this.parseArray(n.routeTableSet?.item).map((r)=>({RouteTableId:r.routeTableId,VpcId:r.vpcId,Routes:this.parseArray(r.routeSet?.item).map((a)=>({DestinationCidrBlock:a.destinationCidrBlock,GatewayId:a.gatewayId,NatGatewayId:a.natGatewayId,State:a.state})),Associations:this.parseArray(r.associationSet?.item).map((a)=>({RouteTableAssociationId:a.routeTableAssociationId,SubnetId:a.subnetId,Main:a.main==="true"||a.main===!0})),Tags:this.parseTags(r.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((r,a)=>{t[`NetworkInterfaceId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeNetworkInterfacesResponse||s;return{NetworkInterfaces:this.parseArray(n.networkInterfaceSet?.item).map((r)=>({NetworkInterfaceId:r.networkInterfaceId,SubnetId:r.subnetId,VpcId:r.vpcId,Status:r.status,Attachment:r.attachment?{AttachmentId:r.attachment.attachmentId,InstanceId:r.attachment.instanceId,Status:r.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let s={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)s.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),s=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(s.regionInfo?.item).map((n)=>({RegionName:n.regionName,Endpoint:n.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((r,a)=>{t[`SecurityGroupId.${a+1}`]=r});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.RunInstancesResponse||s;return{Instances:this.parseInstances(n.instancesSet?.item||n.instancesSet)}}encodeIpPermissions(e,t){t.forEach((s,n)=>{let r=`IpPermissions.${n+1}`;if(s.IpProtocol!==void 0)e[`${r}.IpProtocol`]=s.IpProtocol;if(s.FromPort!==void 0)e[`${r}.FromPort`]=String(s.FromPort);if(s.ToPort!==void 0)e[`${r}.ToPort`]=String(s.ToPort);if(s.IpRanges)s.IpRanges.forEach((a,i)=>{if(a.CidrIp)e[`${r}.IpRanges.${i+1}.CidrIp`]=a.CidrIp;if(a.Description)e[`${r}.IpRanges.${i+1}.Description`]=a.Description});if(s.Ipv6Ranges)s.Ipv6Ranges.forEach((a,i)=>{if(a.CidrIpv6)e[`${r}.Ipv6Ranges.${i+1}.CidrIpv6`]=a.CidrIpv6;if(a.Description)e[`${r}.Ipv6Ranges.${i+1}.Description`]=a.Description});if(s.UserIdGroupPairs)s.UserIdGroupPairs.forEach((a,i)=>{if(a.GroupId)e[`${r}.Groups.${i+1}.GroupId`]=a.GroupId;if(a.UserId)e[`${r}.Groups.${i+1}.UserId`]=a.UserId;if(a.Description)e[`${r}.Groups.${i+1}.Description`]=a.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let s of this.parseArray(t?.ipv6AddressesSet?.item))if(s?.ipv6Address)return s.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((s)=>({GroupId:s.groupId,GroupName:s.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((s)=>({DeviceName:s.deviceName,Ebs:s.ebs?{VolumeId:s.ebs.volumeId,Status:s.ebs.status,AttachTime:s.ebs.attachTime,DeleteOnTermination:s.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((s)=>({CidrIp:s.cidrIp,Description:s.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((s)=>({CidrIpv6:s.cidrIpv6,Description:s.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((s)=>({GroupId:s.groupId,UserId:s.userId,Description:s.description}))}))}}
4
4
  export{X};
@@ -1,6 +1,6 @@
1
- import{et,A,qt,Pr,Ei}from"./chunk-tyqxz92e.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
2
- `)}var Td="dashboard";function oc(){return et("dashboard-credentials.json")}function F(){return R(24).toString("base64url")}function Ed(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(b(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=oc(),i=A(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(U(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=F();try{w(v(i),{recursive:!0}),m(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
1
+ import{et,A,qt,Pr,Ei}from"./chunk-jdfbahjb.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
2
+ `)}var Ed="dashboard";function sc(){return et("dashboard-credentials.json")}function F(){return R(24).toString("base64url")}function wd(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(b(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=sc(),i=A(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(U(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=F();try{w(v(i),{recursive:!0}),m(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
3
3
  `),j(i,384),t.info(`Management dashboard: generated a password for '${r}' and saved it to ${n} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(o){t.warn(`Management dashboard: could not persist the generated password (${o?.message??o}). Using it for this deploy only — pass: ${d}
4
4
  This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${n} is writable.`)}return{password:d,source:"generated"}}var I={info:()=>{},warn:()=>{}};function b(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function J(){return et("dashboard-release")}function L(){let e=v(C(import.meta.url));for(let r of[a(e,"..","..","package.json"),a(e,"..","package.json")])try{let t=JSON.parse(U(r,"utf8"));if(t.name==="@stacksjs/ts-cloud"&&t.version)return`^${t.version}`}catch{}return"latest"}function z(){return process.env.TS_CLOUD_UI_VERSION?.trim()||L()}function V(e,r,t){if(!e?.project?.slug)return t.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let s=A(r,"dashboard-release");try{w(s,{recursive:!0}),m(a(s,"cloud.config.ts"),y(e));let n=z();if(n.startsWith("file:")){let d=n.slice(5),o=O(d)?d:B(r,d);if(!u(o)||!N(o).isFile())n=L(),t.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${o}); using the deploying ts-cloud version ${n} instead.`);else{let c=P(o),l=a(s,c);if(o!==l)x(o,l);n=`file:./${c}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":n}};return m(a(s,"package.json"),`${JSON.stringify(i,null,2)}
5
- `),J()}catch(n){return t.warn(`Management dashboard: could not stage the live release (${n?.message??n}) — skipping.`),null}}function ao(e){if(u(a(e,"packages","ui","pages"))||u(a(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let r=v(C(import.meta.url)),t=[a(r,"ui"),a(r,"..","ui"),a(r,"..","..","ui"),a(r,"..","dist","ui")];for(let s of t)if(u(a(s,"index.html"))||u(a(s,"serverless.html")))return{uiRoot:s,build:!1};return null}function co(e,r={}){let t=r.logger??I,s=r.cwd??process.cwd();if(b(process.env.TS_CLOUD_UI_DISABLE))return t.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return t.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(qt(e))return e;let n=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,d=Number(process.env.TS_CLOUD_UI_PORT)||void 0,o={...e.sites??{}};if(!b(process.env.TS_CLOUD_UI_STATIC)){let g=V(e,s,t);if(!g)return e;let p=Ei(e,n??"production",{uiRoot:g,build:!1,domain:i,port:d,live:!0});if(p.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:k,site:_}of p)o[k]=_,t.info(`Management dashboard → https://${_.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=o,e}let c=ao(s);if(!c)return t.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let l=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",f=Ed(s,l,t),S=Ei(e,n??"production",{uiRoot:c.uiRoot,build:c.build,domain:i,username:l,password:f.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:d});if(S.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let T=f.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":f.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${oc()})`;t.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:g,site:p}of S)o[g]=p,t.info(`Management dashboard → https://${p.domain} (${T})`);return e.sites=o,e}function lo(e){return Object.keys(e.sites??{}).filter(Pr)}function vs(e,r){if(!e?.root)return null;let t=r.cwd??process.cwd(),s=r.logger??I;try{if(typeof e.build==="string"&&e.build.trim())s.info(`Management dashboard: building UI (${e.build})`),D(e.build,{cwd:t,stdio:"inherit"});let n=O(e.root)?e.root:a(t,e.root);if(!u(n))return s.warn(`Management dashboard: build output not found at ${n} — skipping dashboard artifact.`),null;let i=a(E(),`${r.slug}-${r.siteName??Td}-${r.sha}.tar.gz`);return D(`tar czf "${i}" -C "${n}" .`,{stdio:"inherit"}),i}catch(n){return s.warn(`Management dashboard: failed to build artifact — ${n?.message??n}. Skipping dashboard deploy.`),null}}
6
- export{Td,oc,Ed,ao,co,lo,vs};
5
+ `),J()}catch(n){return t.warn(`Management dashboard: could not stage the live release (${n?.message??n}) — skipping.`),null}}function ao(e){if(u(a(e,"packages","ui","pages"))||u(a(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let r=v(C(import.meta.url)),t=[a(r,"ui"),a(r,"..","ui"),a(r,"..","..","ui"),a(r,"..","dist","ui")];for(let s of t)if(u(a(s,"index.html"))||u(a(s,"serverless.html")))return{uiRoot:s,build:!1};return null}function co(e,r={}){let t=r.logger??I,s=r.cwd??process.cwd();if(b(process.env.TS_CLOUD_UI_DISABLE))return t.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return t.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(qt(e))return e;let n=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,d=Number(process.env.TS_CLOUD_UI_PORT)||void 0,o={...e.sites??{}};if(!b(process.env.TS_CLOUD_UI_STATIC)){let g=V(e,s,t);if(!g)return e;let p=Ei(e,n??"production",{uiRoot:g,build:!1,domain:i,port:d,live:!0});if(p.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:k,site:_}of p)o[k]=_,t.info(`Management dashboard → https://${_.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=o,e}let c=ao(s);if(!c)return t.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let l=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",f=wd(s,l,t),S=Ei(e,n??"production",{uiRoot:c.uiRoot,build:c.build,domain:i,username:l,password:f.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:d});if(S.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let T=f.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":f.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${sc()})`;t.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:g,site:p}of S)o[g]=p,t.info(`Management dashboard → https://${p.domain} (${T})`);return e.sites=o,e}function lo(e){return Object.keys(e.sites??{}).filter(Pr)}function Ts(e,r){if(!e?.root)return null;let t=r.cwd??process.cwd(),s=r.logger??I;try{if(typeof e.build==="string"&&e.build.trim())s.info(`Management dashboard: building UI (${e.build})`),D(e.build,{cwd:t,stdio:"inherit"});let n=O(e.root)?e.root:a(t,e.root);if(!u(n))return s.warn(`Management dashboard: build output not found at ${n} — skipping dashboard artifact.`),null;let i=a(E(),`${r.slug}-${r.siteName??Ed}-${r.sha}.tar.gz`);return D(`tar czf "${i}" -C "${n}" .`,{stdio:"inherit"}),i}catch(n){return s.warn(`Management dashboard: failed to build artifact — ${n?.message??n}. Skipping dashboard deploy.`),null}}
6
+ export{Ed,sc,wd,ao,co,lo,Ts};
@@ -1,2 +1,2 @@
1
- import{Lo,dn,ha,Ai,Bo,Fo}from"./chunk-tyqxz92e.js";import{e}from"./chunk-9h7yjtz2.js";import{ht}from"./chunk-hqmkfh4a.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Bu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Bo({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=Fo(r);E(h,i),E(o(a,"runtime"),Ai().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Lo(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await dn({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),ha({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new ht(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
2
- export{Bu};
1
+ import{Mo,dn,ya,Ai,Fo,jo}from"./chunk-jdfbahjb.js";import{e}from"./chunk-3jjggqfj.js";import{ht}from"./chunk-y6rgvb7r.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Fu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Fo({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=jo(r);E(h,i),E(o(a,"runtime"),Ai().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Mo(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await dn({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),ya({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new ht(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
2
+ export{Fu};
@@ -1,2 +1,2 @@
1
- import{u,N}from"./chunk-t1jpqn4x.js";class me{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeDBInstances(e){let r={Action:"DescribeDBInstances",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((a,o)=>{r[`Filters.Filter.${o+1}.Name`]=a.Name,a.Values.forEach((c,d)=>{r[`Filters.Filter.${o+1}.Values.Value.${d+1}`]=c})});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBInstancesResult||n,s=i.DBInstances?.DBInstance||[];if(!Array.isArray(s))s=s?[s]:[];return{DBInstances:s,Marker:i.Marker}}async describeDBInstance(e){return(await this.describeDBInstances({DBInstanceIdentifier:e})).DBInstances?.[0]}async describeDBClusters(e){let r={Action:"DescribeDBClusters",Version:"2014-10-31"};if(e?.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((a,o)=>{r[`Filters.Filter.${o+1}.Name`]=a.Name,a.Values.forEach((c,d)=>{r[`Filters.Filter.${o+1}.Values.Value.${d+1}`]=c})});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBClustersResult||n,s=i.DBClusters?.DBCluster||[];if(!Array.isArray(s))s=s?[s]:[];return{DBClusters:s,Marker:i.Marker}}async describeDBSnapshots(e){let r={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;if(e?.SnapshotType)r.SnapshotType=e.SnapshotType;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBSnapshotsResult||n,s=i.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(s))s=s?[s]:[];return{DBSnapshots:s,Marker:i.Marker}}async describeDBSubnetGroups(e){let r={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if(e?.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBSubnetGroupsResult||n,s=i.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(s))s=s?[s]:[];return{DBSubnetGroups:s,Marker:i.Marker}}async createDBInstance(e){let r={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBInstanceClass:e.DBInstanceClass,Engine:e.Engine};if(e.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DBName)r.DBName=e.DBName;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.LicenseModel)r.LicenseModel=e.LicenseModel;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.StorageType)r.StorageType=e.StorageType;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.CreateDBInstanceResult||n).DBInstance}}async createDBCluster(e){let r={Action:"CreateDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DatabaseName)r.DatabaseName=e.DatabaseName;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;e.VpcSecurityGroupIds?.forEach((i,s)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${s+1}`]=i});let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.CreateDBClusterResult||t).DBCluster}}async deleteDBInstance(e){let r={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.SkipFinalSnapshot!==void 0)r.SkipFinalSnapshot=e.SkipFinalSnapshot;if(e.FinalDBSnapshotIdentifier)r.FinalDBSnapshotIdentifier=e.FinalDBSnapshotIdentifier;if(e.DeleteAutomatedBackups!==void 0)r.DeleteAutomatedBackups=e.DeleteAutomatedBackups;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.DeleteDBInstanceResult||n).DBInstance}}async modifyDBInstance(e){let r={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.ModifyDBInstanceResult||n).DBInstance}}async modifyDBCluster(e){let r={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier};if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBCluster:(n.ModifyDBClusterResult||n).DBCluster}}async rebootDBCluster(e){let r={Action:"FailoverDBCluster",Version:"2014-10-31",DBClusterIdentifier:e},t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.FailoverDBClusterResult||t).DBCluster}}async createDBClusterSnapshot(e,r){let t={Action:"CreateDBClusterSnapshot",Version:"2014-10-31",DBClusterIdentifier:e,DBClusterSnapshotIdentifier:r};return this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(t)).toString()})}async describeDBClusterSnapshots(e={}){let r={Action:"DescribeDBClusterSnapshots",Version:"2014-10-31",...e},t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()}),n=t.DescribeDBClusterSnapshotsResult||t,i=n.DBClusterSnapshots?.DBClusterSnapshot??n.DBClusterSnapshots??[];return{DBClusterSnapshots:Array.isArray(i)?i:[i]}}async deleteDBClusterSnapshot(e){await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N({Action:"DeleteDBClusterSnapshot",Version:"2014-10-31",DBClusterSnapshotIdentifier:e})).toString()})}async deleteDBCluster(e,r){let t={Action:"DeleteDBCluster",Version:"2014-10-31",DBClusterIdentifier:e,SkipFinalSnapshot:!r};if(r)t.FinalDBSnapshotIdentifier=r;let n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(t)).toString()});return{DBCluster:(n.DeleteDBClusterResult||n).DBCluster}}async restoreDBClusterToPointInTime(e){let r={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SourceDBClusterIdentifier:e.SourceDBClusterIdentifier};if(e.RestoreToTime)r.RestoreToTime=e.RestoreToTime.toISOString();if(e.UseLatestRestorableTime)r.UseLatestRestorableTime=!0;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBCluster:(n.RestoreDBClusterToPointInTimeResult||n).DBCluster}}async restoreDBClusterFromSnapshot(e){let r={Action:"RestoreDBClusterFromSnapshot",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SnapshotIdentifier:e.SnapshotIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds?.forEach((i,s)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${s+1}`]=i}),e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.RestoreDBClusterFromSnapshotResult||t).DBCluster}}async startDBInstance(e){let t=new URLSearchParams(N({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e})).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.StartDBInstanceResult||n).DBInstance}}async stopDBInstance(e){let r={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.StopDBInstanceResult||n).DBInstance}}async rebootDBInstance(e){let r={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.ForceFailover!==void 0)r.ForceFailover=e.ForceFailover;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.RebootDBInstanceResult||n).DBInstance}}async createDBSnapshot(e){let r={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBSnapshot:(n.CreateDBSnapshotResult||n).DBSnapshot}}async deleteDBSnapshot(e){let t=new URLSearchParams(N({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:e})).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBSnapshot:(n.DeleteDBSnapshotResult||n).DBSnapshot}}async restoreDBInstanceFromDBSnapshot(e){let r={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.Port)r.Port=e.Port;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.RestoreDBInstanceFromDBSnapshotResult||n).DBInstance}}async waitForDBInstanceAvailable(e,r=60,t=30000){for(let n=0;n<r;n++){let i=await this.describeDBInstance(e);if(i?.DBInstanceStatus==="available")return i;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(i?.DBInstanceStatus||""))throw Error(`DB instance ${e} is in terminal state: ${i?.DBInstanceStatus}`);await new Promise((s)=>setTimeout(s,t))}throw Error(`Timeout waiting for DB instance ${e} to become available`)}async waitForDBInstanceDeleted(e,r=60,t=30000){for(let n=0;n<r;n++)try{let i=await this.describeDBInstance(e);if(i?.DBInstanceStatus==="deleting"){await new Promise((s)=>setTimeout(s,t));continue}throw Error(`DB instance ${e} is in state: ${i?.DBInstanceStatus}`)}catch(i){if(i.code==="DBInstanceNotFound"||i.code==="DBInstanceNotFoundFault")return;throw i}throw Error(`Timeout waiting for DB instance ${e} to be deleted`)}}
1
+ import{u,N}from"./chunk-q3xwh0r8.js";class me{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeDBInstances(e){let r={Action:"DescribeDBInstances",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((a,o)=>{r[`Filters.Filter.${o+1}.Name`]=a.Name,a.Values.forEach((c,d)=>{r[`Filters.Filter.${o+1}.Values.Value.${d+1}`]=c})});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBInstancesResult||n,s=i.DBInstances?.DBInstance||[];if(!Array.isArray(s))s=s?[s]:[];return{DBInstances:s,Marker:i.Marker}}async describeDBInstance(e){return(await this.describeDBInstances({DBInstanceIdentifier:e})).DBInstances?.[0]}async describeDBClusters(e){let r={Action:"DescribeDBClusters",Version:"2014-10-31"};if(e?.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((a,o)=>{r[`Filters.Filter.${o+1}.Name`]=a.Name,a.Values.forEach((c,d)=>{r[`Filters.Filter.${o+1}.Values.Value.${d+1}`]=c})});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBClustersResult||n,s=i.DBClusters?.DBCluster||[];if(!Array.isArray(s))s=s?[s]:[];return{DBClusters:s,Marker:i.Marker}}async describeDBSnapshots(e){let r={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;if(e?.SnapshotType)r.SnapshotType=e.SnapshotType;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBSnapshotsResult||n,s=i.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(s))s=s?[s]:[];return{DBSnapshots:s,Marker:i.Marker}}async describeDBSubnetGroups(e){let r={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if(e?.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBSubnetGroupsResult||n,s=i.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(s))s=s?[s]:[];return{DBSubnetGroups:s,Marker:i.Marker}}async createDBInstance(e){let r={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBInstanceClass:e.DBInstanceClass,Engine:e.Engine};if(e.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DBName)r.DBName=e.DBName;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.LicenseModel)r.LicenseModel=e.LicenseModel;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.StorageType)r.StorageType=e.StorageType;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.CreateDBInstanceResult||n).DBInstance}}async createDBCluster(e){let r={Action:"CreateDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DatabaseName)r.DatabaseName=e.DatabaseName;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;e.VpcSecurityGroupIds?.forEach((i,s)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${s+1}`]=i});let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.CreateDBClusterResult||t).DBCluster}}async deleteDBInstance(e){let r={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.SkipFinalSnapshot!==void 0)r.SkipFinalSnapshot=e.SkipFinalSnapshot;if(e.FinalDBSnapshotIdentifier)r.FinalDBSnapshotIdentifier=e.FinalDBSnapshotIdentifier;if(e.DeleteAutomatedBackups!==void 0)r.DeleteAutomatedBackups=e.DeleteAutomatedBackups;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.DeleteDBInstanceResult||n).DBInstance}}async modifyDBInstance(e){let r={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.ModifyDBInstanceResult||n).DBInstance}}async modifyDBCluster(e){let r={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier};if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBCluster:(n.ModifyDBClusterResult||n).DBCluster}}async rebootDBCluster(e){let r={Action:"FailoverDBCluster",Version:"2014-10-31",DBClusterIdentifier:e},t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.FailoverDBClusterResult||t).DBCluster}}async createDBClusterSnapshot(e,r){let t={Action:"CreateDBClusterSnapshot",Version:"2014-10-31",DBClusterIdentifier:e,DBClusterSnapshotIdentifier:r};return this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(t)).toString()})}async describeDBClusterSnapshots(e={}){let r={Action:"DescribeDBClusterSnapshots",Version:"2014-10-31",...e},t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()}),n=t.DescribeDBClusterSnapshotsResult||t,i=n.DBClusterSnapshots?.DBClusterSnapshot??n.DBClusterSnapshots??[];return{DBClusterSnapshots:Array.isArray(i)?i:[i]}}async deleteDBClusterSnapshot(e){await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N({Action:"DeleteDBClusterSnapshot",Version:"2014-10-31",DBClusterSnapshotIdentifier:e})).toString()})}async deleteDBCluster(e,r){let t={Action:"DeleteDBCluster",Version:"2014-10-31",DBClusterIdentifier:e,SkipFinalSnapshot:!r};if(r)t.FinalDBSnapshotIdentifier=r;let n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(t)).toString()});return{DBCluster:(n.DeleteDBClusterResult||n).DBCluster}}async restoreDBClusterToPointInTime(e){let r={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SourceDBClusterIdentifier:e.SourceDBClusterIdentifier};if(e.RestoreToTime)r.RestoreToTime=e.RestoreToTime.toISOString();if(e.UseLatestRestorableTime)r.UseLatestRestorableTime=!0;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBCluster:(n.RestoreDBClusterToPointInTimeResult||n).DBCluster}}async restoreDBClusterFromSnapshot(e){let r={Action:"RestoreDBClusterFromSnapshot",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SnapshotIdentifier:e.SnapshotIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds?.forEach((i,s)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${s+1}`]=i}),e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.RestoreDBClusterFromSnapshotResult||t).DBCluster}}async startDBInstance(e){let t=new URLSearchParams(N({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e})).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.StartDBInstanceResult||n).DBInstance}}async stopDBInstance(e){let r={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.StopDBInstanceResult||n).DBInstance}}async rebootDBInstance(e){let r={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.ForceFailover!==void 0)r.ForceFailover=e.ForceFailover;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.RebootDBInstanceResult||n).DBInstance}}async createDBSnapshot(e){let r={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBSnapshot:(n.CreateDBSnapshotResult||n).DBSnapshot}}async deleteDBSnapshot(e){let t=new URLSearchParams(N({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:e})).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBSnapshot:(n.DeleteDBSnapshotResult||n).DBSnapshot}}async restoreDBInstanceFromDBSnapshot(e){let r={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.Port)r.Port=e.Port;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.RestoreDBInstanceFromDBSnapshotResult||n).DBInstance}}async waitForDBInstanceAvailable(e,r=60,t=30000){for(let n=0;n<r;n++){let i=await this.describeDBInstance(e);if(i?.DBInstanceStatus==="available")return i;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(i?.DBInstanceStatus||""))throw Error(`DB instance ${e} is in terminal state: ${i?.DBInstanceStatus}`);await new Promise((s)=>setTimeout(s,t))}throw Error(`Timeout waiting for DB instance ${e} to become available`)}async waitForDBInstanceDeleted(e,r=60,t=30000){for(let n=0;n<r;n++)try{let i=await this.describeDBInstance(e);if(i?.DBInstanceStatus==="deleting"){await new Promise((s)=>setTimeout(s,t));continue}throw Error(`DB instance ${e} is in state: ${i?.DBInstanceStatus}`)}catch(i){if(i.code==="DBInstanceNotFound"||i.code==="DBInstanceNotFoundFault")return;throw i}throw Error(`Timeout waiting for DB instance ${e} to be deleted`)}}
2
2
  export{me};
@@ -0,0 +1 @@
1
+ import{Ds,gp,fp,ks}from"./chunk-wfa8j3wg.js";import"./chunk-0md2h0an.js";import"./chunk-jdfbahjb.js";export{gp as getComputeDeployHistory,ks as restoreDatabaseBackup,Ds as rollbackComputeSite,fp as runComputeRecipe};
@@ -0,0 +1 @@
1
+ import{v}from"./chunk-9e7pqhj1.js";import"./chunk-q3xwh0r8.js";export{v as CloudFormationClient};
@@ -0,0 +1 @@
1
+ import{qn}from"./chunk-4sq6cvz5.js";import"./chunk-rpfvv7hw.js";import"./chunk-xh5jcv64.js";import"./chunk-1j9vy88a.js";import"./chunk-3jjggqfj.js";import"./chunk-9e7pqhj1.js";import"./chunk-2q27v6vz.js";import"./chunk-q3xwh0r8.js";import"./chunk-jdfbahjb.js";export{qn as resolveDashboardData};
@@ -1,4 +1,4 @@
1
- import{B}from"./chunk-tyqxz92e.js";function g(t){let e=t.sites||{};for(let r of Object.values(e))if(r?.repository?.url)return{provider:r.repository.provider,branch:r.repository.branch};return}function m(t){let e=t.trim().toLowerCase();if(e.includes("github.com"))return"github";if(e.includes("gitlab.com"))return"gitlab";if(e.includes("bitbucket.org"))return"bitbucket";return}function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function E(t){return t.replace(/'/g,"''")}function _(t,e){let r=["bunx --bun @stacksjs/ts-cloud deploy","--env",a(t)];if(e.site)r.push("--site",a(e.site));if(e.skipDnsVerification)r.push("--skip-dns-verification");return r.push("--yes"),r.join(" ")}function v(t,e="production",r={}){let l=g(t),n=r.provider||l?.provider;if(n!=="github"&&n!=="gitlab"&&n!=="bitbucket")return null;let i=t.environments?.[e],s=i?.deployBranch||l?.branch||"main",u=_(e,r),c=JSON.stringify(s),d=JSON.stringify(e),p=i?.domain?i.domain.startsWith("http")?i.domain:`https://${i.domain}`:void 0,f=p?`
1
+ import{B}from"./chunk-jdfbahjb.js";function g(t){let e=t.sites||{};for(let r of Object.values(e))if(r?.repository?.url)return{provider:r.repository.provider,branch:r.repository.branch};return}function m(t){let e=t.trim().toLowerCase();if(e.includes("github.com"))return"github";if(e.includes("gitlab.com"))return"gitlab";if(e.includes("bitbucket.org"))return"bitbucket";return}function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function E(t){return t.replace(/'/g,"''")}function _(t,e){let r=["bunx --bun @stacksjs/ts-cloud deploy","--env",a(t)];if(e.site)r.push("--site",a(e.site));if(e.skipDnsVerification)r.push("--skip-dns-verification");return r.push("--yes"),r.join(" ")}function v(t,e="production",r={}){let l=g(t),n=r.provider||l?.provider;if(n!=="github"&&n!=="gitlab"&&n!=="bitbucket")return null;let i=t.environments?.[e],s=i?.deployBranch||l?.branch||"main",u=_(e,r),c=JSON.stringify(s),d=JSON.stringify(e),p=i?.domain?i.domain.startsWith("http")?i.domain:`https://${i.domain}`:void 0,f=p?`
2
2
  url: ${JSON.stringify(p)}`:"",h=r.setup==="pantry"?` - name: Setup Pantry
3
3
  uses: home-lang/pantry/packages/action@main`:` - uses: oven-sh/setup-bun@v2
4
4
  - run: bun install --frozen-lockfile`,y=B(t)==="hetzner"&&!!t.infrastructure?.compute,o=r.sshPrivateKeySecret||"SSH_PRIVATE_KEY";if(!/^[A-Z_][A-Z0-9_]*$/i.test(o))throw Error(`Invalid SSH private key secret name '${o}'`);let b=y?`