@stacksjs/ts-cloud 0.16.59 → 0.16.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-x8gqdr3m.js → chunk-0ejp168p.js} +1 -1
  3. package/dist/bin/chunk-0v5tsfx5.js +1 -0
  4. package/dist/bin/{chunk-qt6rjw6v.js → chunk-2avtspqd.js} +5 -5
  5. package/dist/bin/{chunk-hs2r1nsg.js → chunk-38qy0dj2.js} +3 -3
  6. package/dist/bin/chunk-3x52axr2.js +1 -0
  7. package/dist/bin/{chunk-bss9yv52.js → chunk-5ad4b744.js} +2 -2
  8. package/dist/bin/chunk-67mww6gq.js +1 -0
  9. package/dist/bin/{chunk-0dmf1a2q.js → chunk-6da5c33e.js} +2 -2
  10. package/dist/bin/chunk-6r04kx46.js +2 -0
  11. package/dist/bin/{chunk-p6qa21fr.js → chunk-71b4t3d8.js} +2 -2
  12. package/dist/bin/chunk-7khzyn7k.js +1 -0
  13. package/dist/bin/{chunk-rq0wxfyp.js → chunk-8bgfn8ek.js} +3 -3
  14. package/dist/bin/{chunk-9t78j764.js → chunk-90ds3vw7.js} +1 -1
  15. package/dist/bin/chunk-97494wnx.js +1 -0
  16. package/dist/bin/{chunk-jvbe549p.js → chunk-9pj5r0x0.js} +1 -1
  17. package/dist/bin/{chunk-sy4zws71.js → chunk-aekwpste.js} +1 -1
  18. package/dist/bin/chunk-agmznzms.js +1 -0
  19. package/dist/bin/chunk-ambf5hpg.js +1 -0
  20. package/dist/bin/chunk-b39h9as6.js +1 -0
  21. package/dist/bin/{chunk-27rh6te6.js → chunk-cf2eyje1.js} +7 -7
  22. package/dist/bin/{chunk-z6xnegpe.js → chunk-d0q93ecd.js} +5 -5
  23. package/dist/bin/{chunk-yydj05nb.js → chunk-d38cyam8.js} +5 -5
  24. package/dist/bin/chunk-dfgzav9j.js +1 -0
  25. package/dist/bin/{chunk-3mhzd931.js → chunk-e51cd46z.js} +2 -2
  26. package/dist/bin/chunk-ekwfpppj.js +1 -0
  27. package/dist/bin/{chunk-acn2c3ep.js → chunk-favx96qj.js} +5 -5
  28. package/dist/bin/chunk-g0w0jec3.js +1 -0
  29. package/dist/bin/{chunk-nn1w8fvd.js → chunk-g2kjjb1a.js} +95 -95
  30. package/dist/bin/chunk-g514nb80.js +1 -0
  31. package/dist/bin/chunk-hknz7fsr.js +1 -0
  32. package/dist/bin/chunk-j9yq3b4d.js +2 -0
  33. package/dist/bin/chunk-k8qrjnyg.js +1 -0
  34. package/dist/bin/{chunk-dwq5vgdc.js → chunk-kmxkwznm.js} +5 -5
  35. package/dist/bin/chunk-kqstefmv.js +1 -0
  36. package/dist/bin/chunk-mk2h37pm.js +1 -0
  37. package/dist/bin/{chunk-8z2436dv.js → chunk-mver6psb.js} +2 -2
  38. package/dist/bin/{chunk-0rvg0ma7.js → chunk-n667tnf3.js} +3 -3
  39. package/dist/bin/{chunk-p23wfy3r.js → chunk-nn8k84cd.js} +1 -1
  40. package/dist/bin/chunk-nrtjmzzn.js +1 -0
  41. package/dist/bin/{chunk-1mb679gj.js → chunk-pe18g092.js} +3 -3
  42. package/dist/bin/chunk-q3rch5hc.js +1 -0
  43. package/dist/bin/{chunk-0xfy78nc.js → chunk-qpvydcfm.js} +5 -5
  44. package/dist/bin/chunk-qqb6h33k.js +1 -0
  45. package/dist/bin/chunk-r1p3k2tn.js +1 -0
  46. package/dist/bin/{chunk-c1dwwtkq.js → chunk-rgddxcrr.js} +112 -97
  47. package/dist/bin/{chunk-cvps1wjq.js → chunk-sbjzewvk.js} +6 -6
  48. package/dist/bin/chunk-t8xq3v3j.js +1 -0
  49. package/dist/bin/{chunk-mdcv2vw1.js → chunk-tcn6qcc4.js} +2 -2
  50. package/dist/bin/{chunk-gr1ra9nj.js → chunk-tg3vzzc4.js} +2 -2
  51. package/dist/bin/{chunk-551brgyd.js → chunk-tpttr74v.js} +5 -5
  52. package/dist/bin/{chunk-0f8jky3x.js → chunk-tw6z2mvh.js} +15 -15
  53. package/dist/bin/{chunk-hc9tnwqs.js → chunk-v3j9wgmn.js} +200 -200
  54. package/dist/bin/{chunk-r99jcm9t.js → chunk-v5x06h8w.js} +5 -5
  55. package/dist/bin/{chunk-9hb2wkkt.js → chunk-v6jm8dsa.js} +1 -1
  56. package/dist/bin/{chunk-06rjt80a.js → chunk-vbq4ten8.js} +3 -3
  57. package/dist/bin/chunk-xb48vxmk.js +1 -0
  58. package/dist/bin/{chunk-e19dabas.js → chunk-ya1413jw.js} +2 -2
  59. package/dist/bin/chunk-yehb738r.js +1 -0
  60. package/dist/bin/chunk-ythfx8pv.js +1 -0
  61. package/dist/bin/{chunk-95djv2ja.js → chunk-zesb85ra.js} +1 -1
  62. package/dist/bin/{chunk-rbyrd9we.js → chunk-zs0q8sh5.js} +1 -1
  63. package/dist/bin/chunk-zynfzzjk.js +1 -0
  64. package/dist/bin/cli.js +292 -292
  65. package/dist/bin/dashboard-server.js +1 -1
  66. package/dist/{chunk-b1v1301e.js → chunk-2phe49y7.js} +25 -25
  67. package/dist/chunk-3b08b1zx.js +1 -0
  68. package/dist/{chunk-pqyv47m4.js → chunk-7mw4x3ay.js} +1 -1
  69. package/dist/{chunk-j2bpd2v9.js → chunk-7s7w8kzc.js} +5 -5
  70. package/dist/{chunk-c87bg8wk.js → chunk-8jqv6wh7.js} +2 -2
  71. package/dist/{chunk-2pqjw8pq.js → chunk-8z3jfyk8.js} +7 -7
  72. package/dist/chunk-9sdkhmav.js +1 -0
  73. package/dist/{chunk-y9q6sv2q.js → chunk-b0s2605f.js} +6 -6
  74. package/dist/{chunk-tj3egckk.js → chunk-betvtvy7.js} +3 -3
  75. package/dist/{chunk-qb8cf1ss.js → chunk-bn3jfrg5.js} +2 -2
  76. package/dist/{chunk-mkvqcd3x.js → chunk-bydj8p3h.js} +2 -2
  77. package/dist/{chunk-95qrgpjk.js → chunk-e97qhzfe.js} +8 -8
  78. package/dist/{chunk-1a7ms51t.js → chunk-et77ydjb.js} +4 -4
  79. package/dist/{chunk-yece1kc4.js → chunk-f512g4fq.js} +5 -5
  80. package/dist/chunk-fc9n4dpq.js +1 -0
  81. package/dist/{chunk-x8fg8zg8.js → chunk-g0bh9atv.js} +2 -2
  82. package/dist/{chunk-6ky22rmg.js → chunk-gj4hj95p.js} +1 -1
  83. package/dist/{chunk-7bzyjfb1.js → chunk-h5j27a4h.js} +106 -101
  84. package/dist/{chunk-rxh9dkpd.js → chunk-k2bb62em.js} +4 -4
  85. package/dist/chunk-kfcct0jz.js +1 -0
  86. package/dist/{chunk-nq6cqjfv.js → chunk-mqbsnpsv.js} +1 -1
  87. package/dist/{chunk-dp0hvmd0.js → chunk-n0xw26th.js} +1 -1
  88. package/dist/{chunk-w174jbbm.js → chunk-n3sydv3m.js} +1 -1
  89. package/dist/{chunk-za23j2mq.js → chunk-p921pam0.js} +118 -118
  90. package/dist/{chunk-jg2m713e.js → chunk-pjdp30dn.js} +2 -2
  91. package/dist/{chunk-qdaj5yyh.js → chunk-r41cawtf.js} +5 -5
  92. package/dist/{chunk-z5as1fa7.js → chunk-r9ydamw0.js} +102 -102
  93. package/dist/{chunk-ryce2n62.js → chunk-rs8v7c67.js} +3 -3
  94. package/dist/{chunk-cwqqv7dx.js → chunk-sqtzajrx.js} +4 -4
  95. package/dist/{chunk-7md90ny0.js → chunk-t3ssg8p0.js} +2 -2
  96. package/dist/{chunk-3h5vgz4z.js → chunk-tt3pn05f.js} +1 -1
  97. package/dist/chunk-v34tdcwv.js +1 -0
  98. package/dist/{chunk-x6a2e5sx.js → chunk-v90w8kbz.js} +3 -3
  99. package/dist/chunk-xq7xs8bh.js +1 -0
  100. package/dist/deploy/index.js +1 -1
  101. package/dist/dns/index.js +1 -1
  102. package/dist/drivers/index.js +1 -1
  103. package/dist/drivers/shared/box-converge.d.ts +46 -1
  104. package/dist/index.js +45 -45
  105. package/dist/mail/index.js +2 -2
  106. package/dist/operations/index.js +1 -1
  107. package/dist/protection/index.js +1 -1
  108. package/dist/spend/index.js +1 -1
  109. package/dist/ui/404.html +1 -1
  110. package/dist/ui/accept-invitation.html +1 -1
  111. package/dist/ui/access-denied.html +1 -1
  112. package/dist/ui/account/automation.html +6 -6
  113. package/dist/ui/account/security.html +2 -2
  114. package/dist/ui/applications/compose.html +6 -6
  115. package/dist/ui/applications/new.html +2 -2
  116. package/dist/ui/data/backups.html +5 -5
  117. package/dist/ui/data/services.html +6 -6
  118. package/dist/ui/data/volumes.html +6 -6
  119. package/dist/ui/index.html +6 -6
  120. package/dist/ui/infrastructure/topology.html +5 -5
  121. package/dist/ui/integrations.html +1 -1
  122. package/dist/ui/operations/alerts.html +6 -6
  123. package/dist/ui/operations/configuration.html +6 -6
  124. package/dist/ui/operations/jobs.html +5 -5
  125. package/dist/ui/operations/maintenance.html +6 -6
  126. package/dist/ui/operations/observability.html +5 -5
  127. package/dist/ui/operations/previews.html +5 -5
  128. package/dist/ui/operations/queue.html +5 -5
  129. package/dist/ui/operations/regions.html +6 -6
  130. package/dist/ui/operations/releases.html +5 -5
  131. package/dist/ui/operations/spend.html +5 -5
  132. package/dist/ui/operations/workloads.html +5 -5
  133. package/dist/ui/security.html +1 -1
  134. package/dist/ui/server/actions.html +5 -5
  135. package/dist/ui/server/activity.html +1 -1
  136. package/dist/ui/server/capacity.html +5 -5
  137. package/dist/ui/server/database.html +5 -5
  138. package/dist/ui/server/deployments.html +5 -5
  139. package/dist/ui/server/diagnostics.html +1 -1
  140. package/dist/ui/server/firewall.html +5 -5
  141. package/dist/ui/server/fleet.html +5 -5
  142. package/dist/ui/server/logs.html +5 -5
  143. package/dist/ui/server/metrics.html +5 -5
  144. package/dist/ui/server/security.html +1 -1
  145. package/dist/ui/server/services.html +2 -2
  146. package/dist/ui/server/sites.html +6 -6
  147. package/dist/ui/server/ssh-keys.html +6 -6
  148. package/dist/ui/server/team.html +6 -6
  149. package/dist/ui/server/terminal.html +2 -2
  150. package/dist/ui/serverless/alarms.html +6 -6
  151. package/dist/ui/serverless/assets.html +1 -1
  152. package/dist/ui/serverless/cost.html +2 -2
  153. package/dist/ui/serverless/data.html +6 -6
  154. package/dist/ui/serverless/deployments.html +2 -2
  155. package/dist/ui/serverless/firewall.html +1 -1
  156. package/dist/ui/serverless/functions.html +6 -6
  157. package/dist/ui/serverless/logs.html +6 -6
  158. package/dist/ui/serverless/metrics.html +2 -2
  159. package/dist/ui/serverless/queues.html +6 -6
  160. package/dist/ui/serverless/secrets.html +6 -6
  161. package/dist/ui/serverless/traces.html +6 -6
  162. package/dist/ui/serverless.html +5 -5
  163. package/package.json +3 -3
  164. package/dist/bin/chunk-1z4hxpwe.js +0 -2
  165. package/dist/bin/chunk-37gemrn2.js +0 -1
  166. package/dist/bin/chunk-40963a0r.js +0 -1
  167. package/dist/bin/chunk-4zsp269q.js +0 -1
  168. package/dist/bin/chunk-57sers7y.js +0 -1
  169. package/dist/bin/chunk-5cmj2m13.js +0 -1
  170. package/dist/bin/chunk-8vmy8yhf.js +0 -1
  171. package/dist/bin/chunk-apqyj6gr.js +0 -1
  172. package/dist/bin/chunk-at4x6wf2.js +0 -1
  173. package/dist/bin/chunk-bd4ppf6w.js +0 -1
  174. package/dist/bin/chunk-bzbah8jm.js +0 -1
  175. package/dist/bin/chunk-bzpeqh5z.js +0 -1
  176. package/dist/bin/chunk-cmkvxf6c.js +0 -1
  177. package/dist/bin/chunk-d2fq60kd.js +0 -1
  178. package/dist/bin/chunk-e0d34gcp.js +0 -1
  179. package/dist/bin/chunk-ed4vh6b4.js +0 -1
  180. package/dist/bin/chunk-fqvqqtg6.js +0 -1
  181. package/dist/bin/chunk-hrg9ygbz.js +0 -1
  182. package/dist/bin/chunk-hzc049ns.js +0 -1
  183. package/dist/bin/chunk-kj0eewaq.js +0 -1
  184. package/dist/bin/chunk-kqd186ky.js +0 -2
  185. package/dist/bin/chunk-mt70pxs8.js +0 -1
  186. package/dist/bin/chunk-n6hngvvb.js +0 -1
  187. package/dist/bin/chunk-n9aeark7.js +0 -1
  188. package/dist/bin/chunk-pntcdh4x.js +0 -1
  189. package/dist/bin/chunk-sfwm3wzx.js +0 -1
  190. package/dist/bin/chunk-zgasmfgt.js +0 -1
  191. package/dist/chunk-3855mx54.js +0 -1
  192. package/dist/chunk-92yhw6da.js +0 -1
  193. package/dist/chunk-9tbx7g94.js +0 -1
  194. package/dist/chunk-qkycmppw.js +0 -1
  195. package/dist/chunk-wtp36fj6.js +0 -1
  196. package/dist/chunk-zwckda2e.js +0 -1
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-1a7ms51t.js";import{b}from"./chunk-w174jbbm.js";var pt=new Set(["A","AAAA","CNAME"]);function V(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function E(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,i=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,i))}class he{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let i,o=new AbortController,a=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{i=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(d){if(r=d,s===8)throw d;await E(s);continue}finally{clearTimeout(a)}if(!i.ok){let d=await i.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${i.status} ${i.statusText}${d?`: ${d}`:""}`),!V(i.status)||s===8)throw r;await E(s,i);continue}let c=await i.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!V(0,c.message)||s===8)throw r;await E(s,i);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!he.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${i.message??"unknown provider error"}`];let o=[];for(let a of i.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)o.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return!0;return i.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===s&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)i.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,i);if(he.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(i.success){let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(o?.id&&o.content===t.content&&(t.ttl===void 0||o.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||o.priority===t.priority))return{success:!0,id:o.id,message:"Record already up to date"};if(o?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,a),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return{success:!1,message:"Failed to list records"};let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class Ge{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,i={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let a=await fetch(s,o);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),i={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)i.priority=e.priority;return i}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),o=i.filter((a)=>a.data!==t.content);if(o.length===i.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var Dg=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],U=[{name:"x-stx-router",value:"true"}];function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Z(e){return`{${e.map(C).join(" ")}}`}function j(e){let t=`http.request.headers[${C(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${C(e.value)})`}function Vt(e){if(e.length===1)return`http.host eq ${C(e[0])}`;return`http.host in ${Z(e)}`}function Dc(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=Vt(e),s=[],o=(t.bypassPaths??[]).map((v)=>`starts_with(http.request.uri.path, ${C(v)})`),c=(t.negotiatedRequestHeaders??U).map(j),d=[...o,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let g=u?`${r} and not ${u}`:r,m=t.assetExtensions??Dg,p=m.length>0?`lower(http.request.uri.path.extension) in ${Z([...m])}`:void 0;if(p)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${p})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let y=p?`(${g} and not ${p})`:`(${g})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:y,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function Pc(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${Vt(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var F="https://api.cloudflare.com/client/v4",qt="[ts-cloud]";class H{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${F}${t}`,i={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let c=await(await fetch(s,o)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let i=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!i.result||i.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=i.result[0].id;return this.zoneCache.set(r,o),{id:o,name:i.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},i=r??e.proxied;if(i!==void 0&&pt.has(e.type)){if(s.proxied=i,i)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let o=W(e);if(o)s.data=o,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??o?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let a=o.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let i=[],o=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${o}`);if(i.push(...c.result||[]),c.result_info)a=o<c.result_info.total_pages,o++;else a=!1}return{success:!0,records:i.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let i=await this.getZoneDetails(r);if(i)return{...i,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(o){let a=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(a))throw o;let c=await this.getZoneDetails(r);if(!c)throw o;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let i of r.result||[]){if(i.status!=="active")continue;for(let o of i.hosts||[])s.add(o.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(o.result&&o.result.length>0)return o.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),i=s.id,o=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${i}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${i}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let i of r.result||[])s[i.id]=i.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),i=[],o=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&_(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),i.push({id:a,from:d,to:c})}catch(u){o.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:i,failed:o}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let i of r.result?.managed_request_headers||[])s[i.id]=i.enabled===!0;return s}async applyTieredCache(e,t){let r=[],s=[],i=await this.getZoneId(e),o=[["tiered_caching",`/zones/${i}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${i}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")o.reverse();for(let[a,c,d]of o)try{let g=(await this.request("GET",c)).result?.value;if(g===d)continue;await this.request("PATCH",c,{value:d}),r.push({id:a,from:g,to:d})}catch(u){s.push({id:a,error:u instanceof Error?u.message:String(u)})}return{changed:r,failed:s}}async applyManagedRequestHeaders(e,t){let r=[],s=[],i=Object.entries(t).filter(([,d])=>d!==void 0);if(i.length===0)return{changed:r,failed:s};let o=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of i)s.push({id:g,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of i){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${o}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of c)s.push({id:g,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),i=await this.getPhaseRules(e,t),o=r.map((d)=>({...d,description:d.description?.startsWith(qt)?d.description:`${qt} ${d.description||t}`})),c=K(i,o).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var x=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function jn(e){return x.test(e)?e.replace(x,"\x00hosts\x00"):null}function O(e,t){return e.replace(x,Vt(t))}function P(e){if(Array.isArray(e))return`[${e.map(P).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${P(s)}`).join(",")}}`;return JSON.stringify(e)}function G(e,t){let r=jn(e.expression);return r!==null&&r===jn(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&P(e.action_parameters)===P(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((o)=>jt(o.expression))),s=(o)=>(o.description||"").startsWith(qt),i=[];for(let o of e){if(!s(o)){i.push(o);continue}let a=jt(o.expression);if(a.length===0){if(r.size>0)i.push(o);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)i.push(o);else if(c.length>0)i.push({...o,expression:O(o.expression,c)})}for(let o of t){let a=jt(o.expression),c=a.length>0?i.findIndex((g)=>s(g)&&G(g,o)):-1;if(c===-1){i.push(o);continue}let d=i[c],u=[...new Set([...jt(d.expression),...a])];i[c]={...d,expression:O(d.expression,u)}}return i}function jt(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function _(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((i,o)=>_(i,t[o]))}let r=e,s=t;return Object.keys(s).every((i)=>_(r[i],s[i]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:M(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,i,o]=r.slice(0,3).map(Number);if(![s,i,o].every(Number.isFinite))return null;return{priority:s,weight:i,port:o,target:M(r.slice(3).join(" "))}}function M(e){return e.replace(/\.$/,"")}var B=new Set(["A","AAAA","CNAME","ALIAS"]);function zt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function zn(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let i=w(s);if(i===r||i.endsWith(`.${r}`))return i;return`${i}.${r}`}function Ms(e,t){return e.map((r)=>({...r,name:zn(r.name,t),proxied:r.proxied??!1}))}function X(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(B.has(t.type))return!0;if(t.type==="TXT"){let r=zt(t.content);if(r)return zt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Y(e,t){if(R(e.content)!==R(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Fs(e){let{provider:t,zone:r,records:s}=e,i={outcomes:[],warnings:[]};if(s.length===0)return i;let o=await t.listRecords(r);if(!o.success)return i.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),i;let a=o.records;for(let c of s){let d=a.filter((p)=>X(p,c));if(d.length>0&&d.every((p)=>Y(p,c))){i.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},g=c.type==="TXT"&&zt(c.content)!==void 0;if(g)for(let p of d){let y=await t.deleteRecord(r,{name:p.name,type:p.type,content:p.content});if(!y.success)i.warnings.push(`could not remove superseded ${p.type} at ${p.name}: ${y.message||"unknown error"}`)}let m=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)i.outcomes.push({record:c,action:d.length>0?"updated":"created"});else i.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let g=new Set(s.filter((p)=>p.type===c&&w(p.name)===u).map((p)=>R(p.content).toLowerCase())),m=a.filter((p)=>p.type===c&&w(p.name)===u&&!g.has(R(p.content).toLowerCase()));for(let p of m)i.warnings.push(`${u} has an undeclared ${c} record (${p.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return i}function Dr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function Pr(e){return Boolean(e&&typeof e.createZone==="function")}var J=new Set(["NS"]);function D(e){return e.replace(/\.$/,"").toLowerCase()}function Kn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(D)),s=new Set(t.map(D));if(r.size!==s.size)return!1;for(let i of r)if(!s.has(i))return!1;return!0}function Q(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:D(r)}var ee=new Set(["MX","SRV"]),te=new Set(["A","AAAA","CNAME"]);function S(e){let t=ee.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${D(e.name)}|${Q(e)}|${t}`}function re(e,t){return S(e)===S(t)}async function kr(e){let{domain:t,registrar:r,host:s,dryRun:i=!1}=e,o=new Set([...e.proxiedHosts??[]].map(D)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(Kn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let g=await r.listRecords(t);if(!g.success)return a.push(`Could not read ${t} from ${r.name}: ${g.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of g.records){if(J.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=pt.has(l.type)&&o.has(D(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...pt.has(l.type)?{proxied:f}:{}})}if(i){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let p=new Map;for(let l of m){let f=`${l.type}|${D(l.name)}`;p.set(f,(p.get(f)??0)+1)}let y=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])y.add(S(f))}catch{}for(let l of m){let f=te.has(l.type)&&p.get(`${l.type}|${D(l.name)}`)===1;if(!f&&y.has(S(l))){u.records.push({record:l,status:"present"});continue}let A;try{A=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(I){A={success:!1,message:I instanceof Error?I.message:String(I)}}if(A.success)y.add(S(l));u.records.push(A.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:A.message})}let v=await s.listRecords(t);if(!v.success)return a.push(`Could not read back ${t} from ${s.name}: ${v.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!v.records.some((f)=>re(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ne={add_visitor_location_headers:"visitorLocationHeaders"};function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function se(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new he(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new Ge(t.godaddyApiKey,t.godaddyApiSecret);if(!Dr(r))return"the GoDaddy provider cannot change nameservers";return r}async function Us(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=se(r.provider,s);if(typeof i==="string")return{status:"skipped",reason:i};let o=new H(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!Pr(o))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return kr({domain:e.domain,registrar:i,host:o,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function Qs(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function oe(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function ae(e){let t={};for(let[r,s]of Object.entries(ne)){let i=e[s];if(typeof i==="boolean")t[r]=i}return t}async function Hs(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=oe(e.zone),s=ae(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0&&!e.zone.tieredCache)return{status:"skipped",reason:"dns.zone declares no settings"};let i=t.credentials??z(t.env??process.env);if(!i.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=new H(i.cloudflareApiToken,{accountId:i.cloudflareAccountId}),a=await o.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await o.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=e.zone.tieredCache?await o.applyTieredCache(e.domain,e.zone.tieredCache):{changed:[],failed:[]},u=[...a.changed,...c.changed,...d.changed],g=[...a.failed,...c.failed,...d.failed];return{status:u.length>0?"applied":"unchanged",domain:e.domain,changed:u,failed:g}}function Gs(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class ie{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new b(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let i=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,i),i}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ce(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?k(t)===k(r):t===r}async currentSet(e,t,r){let i=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!i||i.Name.toLowerCase()!==t.toLowerCase()||i.Type!==r||i.AliasTarget||i.SetIdentifier)return null;return{ttl:i.TTL??300,values:(i.ResourceRecords??[]).map((o)=>o.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(o?.values.some((d)=>this.sameValue(t.type,d,i)))return{success:!0,message:"Record already present"};let a=[...o?.values??[],i];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:o?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:i}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(!o||!o.values.some((c)=>this.sameValue(t.type,c,i)))return{success:!0,message:"Record already absent"};let a=o.values.filter((c)=>!this.sameValue(t.type,c,i));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o.ttl,ResourceRecords:(a.length>0?a:o.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),i=[];for(let o of s.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let a of o.ResourceRecords||[]){let c=a.Value,d;if(o.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(o.Type==="TXT"&&c.startsWith('"'))c=k(c);i.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:c,ttl:o.TTL,priority:d})}}return{success:!0,records:i}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:b.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=b.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var q=255;function ce(e){let t=[];for(let r=0;r<e.length;r+=q)t.push(e.slice(r,r+q));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function k(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(!r){if(i==='"')r=!0;continue}if(i==="\\"&&s+1<e.length){t+=e[++s];continue}if(i==='"'){r=!1;continue}t+=i}return t}async function Vs(e,t){let r=[],s,i;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:i,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(s=o.NextRecordName,i=o.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function T(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function de(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function qs(e,t){let r=h(t),s=[],i=[],o=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){i.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){i.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let g=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)o.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of c.ResourceRecords||[]){let m=ue(d,u,g.Value,c.TTL);if("reason"in m){i.push({name:d,type:u,reason:m.reason}),o.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:i,warnings:o}}function ue(e,t,r,s){let i={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...i,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...i,type:"TXT",content:de(r)};case"MX":{let[o,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...i,type:"MX",content:h(a.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=o.slice(0,3).map(Number);return{...i,type:"SRV",content:h(o.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...i,type:"NS",content:h(r)};case"CAA":return{...i,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var le=new Set(["TXT","MX","SRV","NS","CAA"]);async function js(e,t){let r=[],s=[],i=new Set;try{let o=await e.listRecords(t.zone);for(let a of o.records||[])i.add(`${h(a.name)}|${a.type}|${T(a)}`)}catch{}for(let o of t.records){let a={...o,proxied:!1},c=`${h(o.name)}|${o.type}|${T(o)}`;if(!le.has(o.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(o);else s.push({record:o,message:u.message||"unknown provider error"});continue}if(i.has(c)){r.push(o);continue}let d=await e.createRecord(t.zone,a);if(d.success)i.add(c),r.push(o);else s.push({record:o,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function zs(e,t){let r=await e.listRecords(t.zone),s=[],i=[],o=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=o.get(c)??[];d.push(T(a)),o.set(c,d)}for(let a of t.records){let c=o.get(`${h(a.name)}|${a.type}`),d=T(a);if(c?.some((u)=>u===d))s.push(a);else i.push({record:a,found:c?.join(", ")})}return{matched:s,missing:i,ok:i.length===0}}class Ae{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ye(t),"provider"in e)this.dnsProvider=N(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:i=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let a=await this.acm.getDnsValidationRecords(o);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(o,i*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,records:i.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!a.success)s.push(`Failed to delete record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:i}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let a=o.SubjectAlternativeNames||[o.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:i})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:i=[],waitForValidation:o=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...i),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function Ks(e,t,r){return new Ae({provider:"porkbun",apiKey:e,secretKey:t},r)}function Ws(e,t,r,s){return new Ae({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function Js(e,t,r){return new Ae({provider:"route53",region:e,hostedZoneId:t},r||e)}function N(e){switch(e.provider){case"route53":return new ie(e.region,e.hostedZoneId);case"porkbun":return new he(e.apiKey,e.secretKey);case"godaddy":return new Ge(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new H(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function kc(e,t){for(let r of t){let s=N(r);if(await s.canManageDomain(e))return s}return null}class Wn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,o)}let i=process.env.CLOUDFLARE_API_TOKEN;if(i)this.addCloudflare(i,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((i)=>i.provider===e);if(!r)return null;let s=N(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=N(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>N(e))}}var Nc=new Wn;class ye{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let i=await this.describeCertificate({CertificateArn:e});if(i.Status==="ISSUED")return i;if(i.Status==="FAILED"||i.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),i=t.split("."),o=s.split(".");if(i.slice(-o.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let i=s.slice(2),o=t.split("."),a=i.split(".");if(o.slice(-a.length).join(".")===i)return!0}}return!1}}class Nr{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ye(e),this.route53=new b,t&&t.provider!=="route53")this.dnsProvider=N(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:i=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(i){if(!await this.acm.waitForCertificateValidation(a,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let a=s||i[0]?.domainName;for(let c of i){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});o.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of i){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});o.push({...a,changeId:c.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,i=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=s||i[0]?.domainName;for(let a of i)try{await this.dnsProvider.deleteRecord(o,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let o of i)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
- export{pt,he,Ge,Dg,Vt,Dc,Pc,qt,H,jn,jt,zt,zn,Ms,Fs,Dr,Pr,Kn,kr,Us,Qs,Hs,Gs,ie,Vs,qs,js,zs,Ae,Ks,Ws,Js,N,kc,Wn,Nc,ye,Nr};
1
+ import{n}from"./chunk-et77ydjb.js";import{b}from"./chunk-n3sydv3m.js";var pt=new Set(["A","AAAA","CNAME"]);function V(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function E(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,i=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,i))}class he{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let i,o=new AbortController,a=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{i=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(d){if(r=d,s===8)throw d;await E(s);continue}finally{clearTimeout(a)}if(!i.ok){let d=await i.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${i.status} ${i.statusText}${d?`: ${d}`:""}`),!V(i.status)||s===8)throw r;await E(s,i);continue}let c=await i.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!V(0,c.message)||s===8)throw r;await E(s,i);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!he.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${i.message??"unknown provider error"}`];let o=[];for(let a of i.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)o.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return!0;return i.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===s&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)i.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,i);if(he.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(i.success){let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(o?.id&&o.content===t.content&&(t.ttl===void 0||o.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||o.priority===t.priority))return{success:!0,id:o.id,message:"Record already up to date"};if(o?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,a),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return{success:!1,message:"Failed to list records"};let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class Ge{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,i={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let a=await fetch(s,o);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),i={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)i.priority=e.priority;return i}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),o=i.filter((a)=>a.data!==t.content);if(o.length===i.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var Pg=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],U=[{name:"x-stx-router",value:"true"}];function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Z(e){return`{${e.map(C).join(" ")}}`}function j(e){let t=`http.request.headers[${C(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${C(e.value)})`}function qt(e){if(e.length===1)return`http.host eq ${C(e[0])}`;return`http.host in ${Z(e)}`}function Pc(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=qt(e),s=[],o=(t.bypassPaths??[]).map((v)=>`starts_with(http.request.uri.path, ${C(v)})`),c=(t.negotiatedRequestHeaders??U).map(j),d=[...o,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let g=u?`${r} and not ${u}`:r,m=t.assetExtensions??Pg,p=m.length>0?`lower(http.request.uri.path.extension) in ${Z([...m])}`:void 0;if(p)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${p})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let y=p?`(${g} and not ${p})`:`(${g})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:y,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function kc(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${qt(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var F="https://api.cloudflare.com/client/v4",jt="[ts-cloud]";class H{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${F}${t}`,i={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let c=await(await fetch(s,o)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let i=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!i.result||i.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=i.result[0].id;return this.zoneCache.set(r,o),{id:o,name:i.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},i=r??e.proxied;if(i!==void 0&&pt.has(e.type)){if(s.proxied=i,i)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let o=W(e);if(o)s.data=o,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??o?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let a=o.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let i=[],o=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${o}`);if(i.push(...c.result||[]),c.result_info)a=o<c.result_info.total_pages,o++;else a=!1}return{success:!0,records:i.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let i=await this.getZoneDetails(r);if(i)return{...i,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(o){let a=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(a))throw o;let c=await this.getZoneDetails(r);if(!c)throw o;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let i of r.result||[]){if(i.status!=="active")continue;for(let o of i.hosts||[])s.add(o.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(o.result&&o.result.length>0)return o.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),i=s.id,o=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${i}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${i}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let i of r.result||[])s[i.id]=i.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),i=[],o=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&_(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),i.push({id:a,from:d,to:c})}catch(u){o.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:i,failed:o}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let i of r.result?.managed_request_headers||[])s[i.id]=i.enabled===!0;return s}async applyTieredCache(e,t){let r=[],s=[],i=await this.getZoneId(e),o=[["tiered_caching",`/zones/${i}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${i}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")o.reverse();for(let[a,c,d]of o)try{let g=(await this.request("GET",c)).result?.value;if(g===d)continue;await this.request("PATCH",c,{value:d}),r.push({id:a,from:g,to:d})}catch(u){s.push({id:a,error:u instanceof Error?u.message:String(u)})}return{changed:r,failed:s}}async applyManagedRequestHeaders(e,t){let r=[],s=[],i=Object.entries(t).filter(([,d])=>d!==void 0);if(i.length===0)return{changed:r,failed:s};let o=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of i)s.push({id:g,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of i){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${o}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of c)s.push({id:g,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),i=await this.getPhaseRules(e,t),o=r.map((d)=>({...d,description:d.description?.startsWith(jt)?d.description:`${jt} ${d.description||t}`})),c=K(i,o).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var x=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function zn(e){return x.test(e)?e.replace(x,"\x00hosts\x00"):null}function O(e,t){return e.replace(x,qt(t))}function P(e){if(Array.isArray(e))return`[${e.map(P).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${P(s)}`).join(",")}}`;return JSON.stringify(e)}function G(e,t){let r=zn(e.expression);return r!==null&&r===zn(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&P(e.action_parameters)===P(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((o)=>zt(o.expression))),s=(o)=>(o.description||"").startsWith(jt),i=[];for(let o of e){if(!s(o)){i.push(o);continue}let a=zt(o.expression);if(a.length===0){if(r.size>0)i.push(o);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)i.push(o);else if(c.length>0)i.push({...o,expression:O(o.expression,c)})}for(let o of t){let a=zt(o.expression),c=a.length>0?i.findIndex((g)=>s(g)&&G(g,o)):-1;if(c===-1){i.push(o);continue}let d=i[c],u=[...new Set([...zt(d.expression),...a])];i[c]={...d,expression:O(d.expression,u)}}return i}function zt(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function _(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((i,o)=>_(i,t[o]))}let r=e,s=t;return Object.keys(s).every((i)=>_(r[i],s[i]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:M(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,i,o]=r.slice(0,3).map(Number);if(![s,i,o].every(Number.isFinite))return null;return{priority:s,weight:i,port:o,target:M(r.slice(3).join(" "))}}function M(e){return e.replace(/\.$/,"")}var B=new Set(["A","AAAA","CNAME","ALIAS"]);function Kt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function Kn(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let i=w(s);if(i===r||i.endsWith(`.${r}`))return i;return`${i}.${r}`}function Us(e,t){return e.map((r)=>({...r,name:Kn(r.name,t),proxied:r.proxied??!1}))}function X(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(B.has(t.type))return!0;if(t.type==="TXT"){let r=Kt(t.content);if(r)return Kt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Y(e,t){if(R(e.content)!==R(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Qs(e){let{provider:t,zone:r,records:s}=e,i={outcomes:[],warnings:[]};if(s.length===0)return i;let o=await t.listRecords(r);if(!o.success)return i.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),i;let a=o.records;for(let c of s){let d=a.filter((p)=>X(p,c));if(d.length>0&&d.every((p)=>Y(p,c))){i.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},g=c.type==="TXT"&&Kt(c.content)!==void 0;if(g)for(let p of d){let y=await t.deleteRecord(r,{name:p.name,type:p.type,content:p.content});if(!y.success)i.warnings.push(`could not remove superseded ${p.type} at ${p.name}: ${y.message||"unknown error"}`)}let m=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)i.outcomes.push({record:c,action:d.length>0?"updated":"created"});else i.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let g=new Set(s.filter((p)=>p.type===c&&w(p.name)===u).map((p)=>R(p.content).toLowerCase())),m=a.filter((p)=>p.type===c&&w(p.name)===u&&!g.has(R(p.content).toLowerCase()));for(let p of m)i.warnings.push(`${u} has an undeclared ${c} record (${p.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return i}function Pr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function kr(e){return Boolean(e&&typeof e.createZone==="function")}var J=new Set(["NS"]);function D(e){return e.replace(/\.$/,"").toLowerCase()}function Wn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(D)),s=new Set(t.map(D));if(r.size!==s.size)return!1;for(let i of r)if(!s.has(i))return!1;return!0}function Q(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:D(r)}var ee=new Set(["MX","SRV"]),te=new Set(["A","AAAA","CNAME"]);function S(e){let t=ee.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${D(e.name)}|${Q(e)}|${t}`}function re(e,t){return S(e)===S(t)}async function Nr(e){let{domain:t,registrar:r,host:s,dryRun:i=!1}=e,o=new Set([...e.proxiedHosts??[]].map(D)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(Wn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let g=await r.listRecords(t);if(!g.success)return a.push(`Could not read ${t} from ${r.name}: ${g.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of g.records){if(J.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=pt.has(l.type)&&o.has(D(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...pt.has(l.type)?{proxied:f}:{}})}if(i){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let p=new Map;for(let l of m){let f=`${l.type}|${D(l.name)}`;p.set(f,(p.get(f)??0)+1)}let y=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])y.add(S(f))}catch{}for(let l of m){let f=te.has(l.type)&&p.get(`${l.type}|${D(l.name)}`)===1;if(!f&&y.has(S(l))){u.records.push({record:l,status:"present"});continue}let A;try{A=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(I){A={success:!1,message:I instanceof Error?I.message:String(I)}}if(A.success)y.add(S(l));u.records.push(A.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:A.message})}let v=await s.listRecords(t);if(!v.success)return a.push(`Could not read back ${t} from ${s.name}: ${v.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!v.records.some((f)=>re(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ne={add_visitor_location_headers:"visitorLocationHeaders"};function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function se(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new he(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new Ge(t.godaddyApiKey,t.godaddyApiSecret);if(!Pr(r))return"the GoDaddy provider cannot change nameservers";return r}async function Hs(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=se(r.provider,s);if(typeof i==="string")return{status:"skipped",reason:i};let o=new H(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!kr(o))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return Nr({domain:e.domain,registrar:i,host:o,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function Gs(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function oe(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function ae(e){let t={};for(let[r,s]of Object.entries(ne)){let i=e[s];if(typeof i==="boolean")t[r]=i}return t}async function Vs(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=oe(e.zone),s=ae(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0&&!e.zone.tieredCache)return{status:"skipped",reason:"dns.zone declares no settings"};let i=t.credentials??z(t.env??process.env);if(!i.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=new H(i.cloudflareApiToken,{accountId:i.cloudflareAccountId}),a=await o.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await o.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=e.zone.tieredCache?await o.applyTieredCache(e.domain,e.zone.tieredCache):{changed:[],failed:[]},u=[...a.changed,...c.changed,...d.changed],g=[...a.failed,...c.failed,...d.failed];return{status:u.length>0?"applied":"unchanged",domain:e.domain,changed:u,failed:g}}function qs(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class ie{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new b(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let i=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,i),i}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ce(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?k(t)===k(r):t===r}async currentSet(e,t,r){let i=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!i||i.Name.toLowerCase()!==t.toLowerCase()||i.Type!==r||i.AliasTarget||i.SetIdentifier)return null;return{ttl:i.TTL??300,values:(i.ResourceRecords??[]).map((o)=>o.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(o?.values.some((d)=>this.sameValue(t.type,d,i)))return{success:!0,message:"Record already present"};let a=[...o?.values??[],i];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:o?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:i}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(!o||!o.values.some((c)=>this.sameValue(t.type,c,i)))return{success:!0,message:"Record already absent"};let a=o.values.filter((c)=>!this.sameValue(t.type,c,i));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o.ttl,ResourceRecords:(a.length>0?a:o.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),i=[];for(let o of s.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let a of o.ResourceRecords||[]){let c=a.Value,d;if(o.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(o.Type==="TXT"&&c.startsWith('"'))c=k(c);i.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:c,ttl:o.TTL,priority:d})}}return{success:!0,records:i}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:b.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=b.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var q=255;function ce(e){let t=[];for(let r=0;r<e.length;r+=q)t.push(e.slice(r,r+q));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function k(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(!r){if(i==='"')r=!0;continue}if(i==="\\"&&s+1<e.length){t+=e[++s];continue}if(i==='"'){r=!1;continue}t+=i}return t}async function js(e,t){let r=[],s,i;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:i,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(s=o.NextRecordName,i=o.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function T(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function de(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function zs(e,t){let r=h(t),s=[],i=[],o=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){i.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){i.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let g=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)o.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of c.ResourceRecords||[]){let m=ue(d,u,g.Value,c.TTL);if("reason"in m){i.push({name:d,type:u,reason:m.reason}),o.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:i,warnings:o}}function ue(e,t,r,s){let i={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...i,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...i,type:"TXT",content:de(r)};case"MX":{let[o,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...i,type:"MX",content:h(a.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=o.slice(0,3).map(Number);return{...i,type:"SRV",content:h(o.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...i,type:"NS",content:h(r)};case"CAA":return{...i,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var le=new Set(["TXT","MX","SRV","NS","CAA"]);async function Ks(e,t){let r=[],s=[],i=new Set;try{let o=await e.listRecords(t.zone);for(let a of o.records||[])i.add(`${h(a.name)}|${a.type}|${T(a)}`)}catch{}for(let o of t.records){let a={...o,proxied:!1},c=`${h(o.name)}|${o.type}|${T(o)}`;if(!le.has(o.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(o);else s.push({record:o,message:u.message||"unknown provider error"});continue}if(i.has(c)){r.push(o);continue}let d=await e.createRecord(t.zone,a);if(d.success)i.add(c),r.push(o);else s.push({record:o,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function Ws(e,t){let r=await e.listRecords(t.zone),s=[],i=[],o=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=o.get(c)??[];d.push(T(a)),o.set(c,d)}for(let a of t.records){let c=o.get(`${h(a.name)}|${a.type}`),d=T(a);if(c?.some((u)=>u===d))s.push(a);else i.push({record:a,found:c?.join(", ")})}return{matched:s,missing:i,ok:i.length===0}}class Ae{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ye(t),"provider"in e)this.dnsProvider=N(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:i=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let a=await this.acm.getDnsValidationRecords(o);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(o,i*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,records:i.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!a.success)s.push(`Failed to delete record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:i}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let a=o.SubjectAlternativeNames||[o.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:i})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:i=[],waitForValidation:o=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...i),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function Js(e,t,r){return new Ae({provider:"porkbun",apiKey:e,secretKey:t},r)}function Xs(e,t,r,s){return new Ae({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function Ys(e,t,r){return new Ae({provider:"route53",region:e,hostedZoneId:t},r||e)}function N(e){switch(e.provider){case"route53":return new ie(e.region,e.hostedZoneId);case"porkbun":return new he(e.apiKey,e.secretKey);case"godaddy":return new Ge(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new H(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Nc(e,t){for(let r of t){let s=N(r);if(await s.canManageDomain(e))return s}return null}class Jn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,o)}let i=process.env.CLOUDFLARE_API_TOKEN;if(i)this.addCloudflare(i,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((i)=>i.provider===e);if(!r)return null;let s=N(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=N(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>N(e))}}var Bc=new Jn;class ye{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let i=await this.describeCertificate({CertificateArn:e});if(i.Status==="ISSUED")return i;if(i.Status==="FAILED"||i.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),i=t.split("."),o=s.split(".");if(i.slice(-o.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let i=s.slice(2),o=t.split("."),a=i.split(".");if(o.slice(-a.length).join(".")===i)return!0}}return!1}}class Br{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ye(e),this.route53=new b,t&&t.provider!=="route53")this.dnsProvider=N(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:i=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(i){if(!await this.acm.waitForCertificateValidation(a,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let a=s||i[0]?.domainName;for(let c of i){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});o.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of i){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});o.push({...a,changeId:c.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,i=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=s||i[0]?.domainName;for(let a of i)try{await this.dnsProvider.deleteRecord(o,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let o of i)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
+ export{pt,he,Ge,Pg,qt,Pc,kc,jt,H,zn,zt,Kt,Kn,Us,Qs,Pr,kr,Wn,Nr,Hs,Gs,Vs,qs,ie,js,zs,Ks,Ws,Ae,Js,Xs,Ys,N,Nc,Jn,Bc,ye,Br};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-1a7ms51t.js";class Hr{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=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=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
1
+ import{n}from"./chunk-et77ydjb.js";class Gr{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=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=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
2
2
  `).slice(-t.tailLines).join(`
3
3
  `);return r}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=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(a.instanceStatusSet?.item).map((r)=>({InstanceId:r.instanceId,InstanceState:r.instanceState?{Code:Number.parseInt(r.instanceState.code),Name:r.instanceState.name}:void 0,InstanceStatus:r.instanceStatus?{Status:r.instanceStatus.status,Details:this.parseArray(r.instanceStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0,SystemStatus:r.systemStatus?{Status:r.systemStatus.status,Details:this.parseArray(r.systemStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=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(a.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 stopInstances(e,t){let a={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((s,i)=>{a[`InstanceId.${i+1}`]=s}),t)a.Force="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()});return{StoppingInstances:this.parseArray(r.instancesSet?.item).map((s)=>({InstanceId:s.instanceId,CurrentState:s.currentState?{Name:s.currentState.name}:void 0,PreviousState:s.previousState?{Name:s.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((a,r)=>{t[`InstanceId.${r+1}`]=a}),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((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=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(a.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 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((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=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:(a.CreateImageResponse||a).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((r,s)=>{t[`VpcId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=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(a.vpcSet?.item).map((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)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((r,s)=>{t[`SubnetId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=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(a.subnetSet?.item).map((r)=>({SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:Number.parseInt(r.availableIpAddressCount),State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((r,s)=>{t[`GroupId.${s+1}`]=r});if(e?.GroupNames)e.GroupNames.forEach((r,s)=>{t[`GroupName.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=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(a.securityGroupInfo?.item).map((r)=>({GroupId:r.groupId,GroupName:r.groupName,Description:r.groupDescription,VpcId:r.vpcId,IpPermissions:this.parseIpPermissions(r.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(r.ipPermissionsEgress?.item),Tags:this.parseTags(r.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((r,s)=>{t[`InternetGatewayId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=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(a.internetGatewaySet?.item).map((r)=>({InternetGatewayId:r.internetGatewayId,Attachments:this.parseArray(r.attachmentSet?.item).map((s)=>({VpcId:s.vpcId,State:s.state})),Tags:this.parseTags(r.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((r,s)=>{t[`AllocationId.${s+1}`]=r});if(e?.PublicIps)e.PublicIps.forEach((r,s)=>{t[`PublicIp.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=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(a.addressesSet?.item).map((r)=>({PublicIp:r.publicIp,AllocationId:r.allocationId,AssociationId:r.associationId,InstanceId:r.instanceId,NetworkInterfaceId:r.networkInterfaceId,PrivateIpAddress:r.privateIpAddress,Domain:r.domain,Tags:this.parseTags(r.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((r,s)=>{t[`TagSpecification.${s+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,o)=>{t[`TagSpecification.${s+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${s+1}.Tag.${o+1}.Value`]=i.Value})});let a=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:a.allocationId,PublicIp:a.publicIp,Domain:a.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((a,r)=>{t[`ResourceId.${r+1}`]=a}),e.Tags.forEach((a,r)=>{t[`Tag.${r+1}.Key`]=a.Key,t[`Tag.${r+1}.Value`]=a.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,a){let r=a?.maxWaitMs||300000,s=a?.pollIntervalMs||5000,i=Date.now();while(Date.now()-i<r){let o;try{o=await this.getInstance(e)}catch{o=void 0}if(o?.State?.Name===t)return o;await new Promise((c)=>setTimeout(c,s))}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((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=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()}),s=(a.CreateVpcResponse||a).vpc;return{Vpc:s?{VpcId:s.vpcId,CidrBlock:s.cidrBlock,State:s.state,DhcpOptionsId:s.dhcpOptionsId,InstanceTenancy:s.instanceTenancy,IsDefault:s.isDefault==="true",Tags:this.parseTags(s.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((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=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()}),s=(a.CreateSubnetResponse||a).subnet;return{Subnet:s?{SubnetId:s.subnetId,VpcId:s.vpcId,CidrBlock:s.cidrBlock,AvailabilityZone:s.availabilityZone,AvailableIpAddressCount:s.availableIpAddressCount?Number.parseInt(s.availableIpAddressCount):void 0,State:s.state,MapPublicIpOnLaunch:s.mapPublicIpOnLaunch==="true",Tags:this.parseTags(s.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 importKeyPair(e){let t={Action:"ImportKeyPair",Version:"2016-11-15",KeyName:e.KeyName,PublicKeyMaterial:Buffer.from(e.PublicKeyMaterial.trim()).toString("base64")};e.TagSpecifications?.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=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=a.ImportKeyPairResponse||a;return{KeyName:r.keyName,KeyPairId:r.keyPairId,KeyFingerprint:r.keyFingerprint}}async deleteKeyPair(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:"DeleteKeyPair",Version:"2016-11-15",KeyName:e}).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((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=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:(a.CreateSecurityGroupResponse||a).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((s,i)=>{t[`RouteTableId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=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=a.DescribeRouteTablesResponse||a;return{RouteTables:this.parseArray(r.routeTableSet?.item).map((s)=>({RouteTableId:s.routeTableId,VpcId:s.vpcId,Routes:this.parseArray(s.routeSet?.item).map((i)=>({DestinationCidrBlock:i.destinationCidrBlock,GatewayId:i.gatewayId,NatGatewayId:i.natGatewayId,State:i.state})),Associations:this.parseArray(s.associationSet?.item).map((i)=>({RouteTableAssociationId:i.routeTableAssociationId,SubnetId:i.subnetId,Main:i.main==="true"||i.main===!0})),Tags:this.parseTags(s.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((s,i)=>{t[`NetworkInterfaceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=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=a.DescribeNetworkInterfacesResponse||a;return{NetworkInterfaces:this.parseArray(r.networkInterfaceSet?.item).map((s)=>({NetworkInterfaceId:s.networkInterfaceId,SubnetId:s.subnetId,VpcId:s.vpcId,Status:s.status,Attachment:s.attachment?{AttachmentId:s.attachment.attachmentId,InstanceId:s.attachment.instanceId,Status:s.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let a={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)a.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(a).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()}),a=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(a.regionInfo?.item).map((r)=>({RegionName:r.regionName,Endpoint:r.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((s,i)=>{t[`SecurityGroupId.${i+1}`]=s});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.KeyName)t.KeyName=e.KeyName;if(e.InstanceInitiatedShutdownBehavior)t.InstanceInitiatedShutdownBehavior=e.InstanceInitiatedShutdownBehavior;if(e.BlockDeviceMappings?.forEach((s,i)=>{let o=`BlockDeviceMapping.${i+1}`;t[`${o}.DeviceName`]=s.DeviceName;let c=s.Ebs;if(!c)return;if(c.VolumeSize!==void 0)t[`${o}.Ebs.VolumeSize`]=String(c.VolumeSize);if(c.VolumeType)t[`${o}.Ebs.VolumeType`]=c.VolumeType;if(c.Iops!==void 0)t[`${o}.Ebs.Iops`]=String(c.Iops);if(c.Throughput!==void 0)t[`${o}.Ebs.Throughput`]=String(c.Throughput);if(c.DeleteOnTermination!==void 0)t[`${o}.Ebs.DeleteOnTermination`]=String(c.DeleteOnTermination);if(c.Encrypted!==void 0)t[`${o}.Ebs.Encrypted`]=String(c.Encrypted)}),e.MetadataOptions?.HttpTokens)t["MetadataOptions.HttpTokens"]=e.MetadataOptions.HttpTokens;if(e.MetadataOptions?.HttpEndpoint)t["MetadataOptions.HttpEndpoint"]=e.MetadataOptions.HttpEndpoint;if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=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=a.RunInstancesResponse||a;return{Instances:this.parseInstances(r.instancesSet?.item||r.instancesSet)}}encodeIpPermissions(e,t){t.forEach((a,r)=>{let s=`IpPermissions.${r+1}`;if(a.IpProtocol!==void 0)e[`${s}.IpProtocol`]=a.IpProtocol;if(a.FromPort!==void 0)e[`${s}.FromPort`]=String(a.FromPort);if(a.ToPort!==void 0)e[`${s}.ToPort`]=String(a.ToPort);if(a.IpRanges)a.IpRanges.forEach((i,o)=>{if(i.CidrIp)e[`${s}.IpRanges.${o+1}.CidrIp`]=i.CidrIp;if(i.Description)e[`${s}.IpRanges.${o+1}.Description`]=i.Description});if(a.Ipv6Ranges)a.Ipv6Ranges.forEach((i,o)=>{if(i.CidrIpv6)e[`${s}.Ipv6Ranges.${o+1}.CidrIpv6`]=i.CidrIpv6;if(i.Description)e[`${s}.Ipv6Ranges.${o+1}.Description`]=i.Description});if(a.UserIdGroupPairs)a.UserIdGroupPairs.forEach((i,o)=>{if(i.GroupId)e[`${s}.Groups.${o+1}.GroupId`]=i.GroupId;if(i.UserId)e[`${s}.Groups.${o+1}.UserId`]=i.UserId;if(i.Description)e[`${s}.Groups.${o+1}.Description`]=i.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let a of this.parseArray(t?.ipv6AddressesSet?.item))if(a?.ipv6Address)return a.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((a)=>({GroupId:a.groupId,GroupName:a.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((a)=>({DeviceName:a.deviceName,Ebs:a.ebs?{VolumeId:a.ebs.volumeId,Status:a.ebs.status,AttachTime:a.ebs.attachTime,DeleteOnTermination:a.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((a)=>({CidrIp:a.cidrIp,Description:a.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((a)=>({CidrIpv6:a.cidrIpv6,Description:a.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((a)=>({GroupId:a.groupId,UserId:a.userId,Description:a.description}))}))}}class Be{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:a.Version,Tier:a.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:a.Parameter?this.parseParameter(a.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),InvalidParameters:a.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:a.DeletedParameters,InvalidParameters:a.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>({Name:r.Name,Type:r.Type,KeyId:r.KeyId,LastModifiedDate:r.LastModifiedDate,LastModifiedUser:r.LastModifiedUser,Description:r.Description,Value:r.Value,Version:r.Version,Labels:r.Labels,Tier:r.Tier})),NextToken:a.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:a.InvalidLabels,ParameterVersion:a.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"String",Description:a?.description,Overwrite:a?.overwrite??!0,Tags:a?.tags})}async setSecureString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:a?.description,Overwrite:a?.overwrite??!0,KeyId:a?.kmsKeyId,Tags:a?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let a=[],r;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:r});if(s.Parameters)a.push(...s.Parameters);r=s.NextToken}while(r);return a}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:a.Command?.CommandId,Status:a.Command?.Status,StatusDetails:a.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:a.Status,StatusDetails:a.StatusDetails,StandardOutputContent:a.StandardOutputContent,StandardErrorContent:a.StandardErrorContent,ResponseCode:a.ResponseCode}}async runShellCommand(e,t,a){let r=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:a?.timeoutSeconds||600});if(!r.CommandId)return{success:!1,error:"Failed to send command"};if(a?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=a?.pollIntervalMs||2000,i=a?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((c)=>setTimeout(c,s));try{let c=await this.getCommandInvocation({CommandId:r.CommandId,InstanceId:e});if(c.Status==="Success")return{success:!0,output:c.StandardOutputContent,error:c.StandardErrorContent,status:c.Status};if(c.Status==="Failed"||c.Status==="Cancelled"||c.Status==="TimedOut")return{success:!1,output:c.StandardOutputContent,error:c.StandardErrorContent||c.StatusDetails,status:c.Status}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,error:c.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([d,g])=>({Key:`tag:${d}`,Values:[g]})),a=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!a.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let r=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<s){await new Promise((d)=>setTimeout(d,r));try{if(c=await this.listCommandInvocations({CommandId:a.CommandId,Details:!0}),c.length===0)continue;if(c.every((g)=>o.has(g.Status||""))){let g=c.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent||u.StatusDetails})),m=c.every((u)=>u.Status==="Success");return{success:m,instanceCount:c.length,perInstance:g,error:m?void 0:"One or more instances reported a non-success status"}}}catch(d){if(!d.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:d.message}}}return{success:!1,instanceCount:c.length,perInstance:c.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}
4
- export{Hr,Be};
4
+ export{Gr,Be};
@@ -1,16 +1,16 @@
1
- import{Ct,Ni,Bi,xi}from"./chunk-x6a2e5sx.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eA(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function tA(t){if(!t)return[];let e=[];for(let n of t.split(`
1
+ import{Et,xi,Oi,_i}from"./chunk-v90w8kbz.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eA(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function tA(t){if(!t)return[];let e=[];for(let n of t.split(`
2
2
  `)){let r=n.trim();if(!r.startsWith("site:"))continue;let[,s,o,i]=r.split(":");if(!s||o!=="no")continue;e.push({name:s,size:i||"?"})}return e}function rA(t,e,n){let r=t.map((o)=>` ${e}-${o.name} (${o.size})`).join(`
3
3
  `),s=t.length===1?"it":"them";return`This server still holds ${t.length} site tree${t.length===1?"":"s"} with nothing running for ${s}:
4
4
  ${r}
5
5
  `+"A site moved off this box keeps its files here on purpose — they are the rollback, and they are what makes "+`the move reversible until this server is destroyed. Destroying it now discards that.
6
- Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var Tp="ts-cloud/project",wp="ts-cloud/environment",Rp="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function nA(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[Tp]),environment:d(e[wp]),role:d(e[Rp])}}function w(t){return t.slug?.trim()||"app"}function Dp(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function Pp(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function iA(t,e,n=Ct){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,Bi(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
- `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:Dp(xi(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
8
- `)[0]:String(r);return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}}function u(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function sA(t,e,n){let r=new Set(e.filter((a)=>a.slug===n).map((a)=>u(a.host,a.path))),s=[],o=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&r.has(u(a.domain,a.path)))s.push(a);else o.push(a);return{present:s,absent:o,loopback:i,foreign:e.filter((a)=>a.slug!==n)}}function kp(t,e,n){let r=new Set;for(let s of e)for(let o of s.routes)if(o.slug===n)r.add(u(o.host,o.path));return t.filter((s)=>!s.loopbackOnly&&s.domain!==void 0&&!r.has(u(s.domain,s.path)))}function oA(t){let{slug:e,servers:n,probes:r,declared:s}=t,o=[];if(o.push(n.length===0?"No servers found.":`${n.length} server${n.length===1?"":"s"}:`),n.length>0)o.push("");let i=new Map(r.map((a)=>[a.server,a]));for(let a of n){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);o.push(` ${a.name} ${p.join(" ")}`),o.push(` ${k(a)}`);let c=i.get(a.name);if(!c)o.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)o.push(` could not read ${Ct}: ${c.unavailable}`);else o.push(...P(c,e));o.push("")}return o.push(...C(t)),o}function k(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function P(t,e){let n=Pp(t.routes);if(n.length===0)return[` serves nothing: ${Ct} is empty or absent`];let r=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${n.length} project${n.length===1?"":"s"}:`];for(let s of n){r.push(` ${s.slug}${s.slug===e?" (this project)":""}`);for(let o of s.routes)r.push(` ${o.host}${o.path==="/"?"/":o.path} -> ${O(o)}`)}return r}function O(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function C(t){let{slug:e,declared:n,probes:r,servers:s}=t;if(n.length===0)return[`This project ('${e}') declares no sites.`];let o=[`This project ('${e}') declares ${n.length} site${n.length===1?"":"s"}: `+n.map((c)=>c.name).join(", ")],i=n.filter((c)=>c.loopbackOnly);if(i.length>0)o.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=r.filter((c)=>!c.unavailable);if(a.length===0)return o.push(" Nothing to reconcile them against: no box reported what it serves."),o;let p=kp(n,a,e);if(o.push(` ${n.length-i.length-p.length} routed by a box above`),p.length>0){o.push(` ${p.length} not routed by any box above: ${p.map((b)=>b.name).join(", ")}`);let c=r.length-a.length,g=s.length-r.length;if(c>0)o.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(g>0)o.push(` Either they were never deployed, or they are on one of the ${g} server${g===1?"":"s"} this run did not probe.`);else o.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return o}async function aA(t){let e=[];for(let n of t.steps)try{e.push({step:n,state:await n.satisfied()?"satisfied":"pending"})}catch(r){e.push({step:n,state:"unknown",reason:r instanceof Error?r.message:String(r)})}return e}function pd(t){return t.filter((e)=>e.state!=="satisfied")}function Np(t){return pd(t).some((e)=>e.step.destructive===!0)}function cA(t,e){let n=pd(e),r=[`${t.operation} ${t.target}`];if(n.length===0)return r.push(" Nothing to do — every step is already satisfied."),r;for(let{step:o,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[o.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(r.push(` ${p}${o.title}${c.length>0?` [${c.join(", ")}]`:""}`),o.change)r.push(` ${o.change.from} → ${o.change.to}`);if(a)r.push(` could not check: ${a}`)}let s=n.filter((o)=>o.step.destructive).length;return r.push(` ${n.length} step(s) would run`+(s>0?`, ${s} irreversible — re-run with --confirm ${t.target}`:"")),r}async function dA(t,e,n={}){let r={operation:t.operation,target:t.target,steps:[],success:!0};if(Np(e)&&n.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:s,state:o}of e){if(o==="satisfied"){r.steps.push({id:s.id,title:s.title,state:"skipped"}),n.log?.(`skip ${s.title} (already done)`);continue}n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"started"});try{await s.apply(),r.steps.push({id:s.id,title:s.title,state:"applied"}),n.log?.(`done ${s.title}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return r.steps.push({id:s.id,title:s.title,state:"failed",error:a}),r.success=!1,n.log?.(`FAIL ${s.title}: ${a}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"failed",error:a}),r}}return r}function Bp(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function lA(t,e,n){if(Bp(e),t===e)throw Error(`'${t}' is already named that.`);if((await n.takenNames()).some((o)=>o===e&&o!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let s=[];if(n.providerName&&n.renameProvider){let{providerName:o,renameProvider:i}=n;s.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}if(n.stateName&&n.writeStateName){let{stateName:o,writeStateName:i}=n;s.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await o();return a===void 0||a===e},apply:()=>i(e)})}if(n.remoteHostname&&n.setRemoteHostname){let{remoteHostname:o,setRemoteHostname:i}=n;s.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}return s.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>n.inventoryName()===e,apply:async()=>{await n.renameInventory(e)}}),{operation:"server:rename",target:t,steps:s}}function uA(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
9
- `)}function gA(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function pA(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function mA(t,e,n){let r=[],s=Ni(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function fA(t){return t.registryRead&&t.conflicts.length===0}function hA(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function ki(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function md(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function xp(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
6
+ Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var Tp="ts-cloud/project",wp="ts-cloud/environment",Rp="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function nA(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[Tp]),environment:d(e[wp]),role:d(e[Rp])}}function w(t){return t.slug?.trim()||"app"}function Dp(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function Pp(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function iA(t,e,n=Et){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,Oi(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
+ `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:Dp(_i(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
8
+ `)[0]:String(r);return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}}function u(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function sA(t,e,n){let r=new Set(e.filter((a)=>a.slug===n).map((a)=>u(a.host,a.path))),s=[],o=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&r.has(u(a.domain,a.path)))s.push(a);else o.push(a);return{present:s,absent:o,loopback:i,foreign:e.filter((a)=>a.slug!==n)}}function kp(t,e,n){let r=new Set;for(let s of e)for(let o of s.routes)if(o.slug===n)r.add(u(o.host,o.path));return t.filter((s)=>!s.loopbackOnly&&s.domain!==void 0&&!r.has(u(s.domain,s.path)))}function oA(t){let{slug:e,servers:n,probes:r,declared:s}=t,o=[];if(o.push(n.length===0?"No servers found.":`${n.length} server${n.length===1?"":"s"}:`),n.length>0)o.push("");let i=new Map(r.map((a)=>[a.server,a]));for(let a of n){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);o.push(` ${a.name} ${p.join(" ")}`),o.push(` ${k(a)}`);let c=i.get(a.name);if(!c)o.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)o.push(` could not read ${Et}: ${c.unavailable}`);else o.push(...P(c,e));o.push("")}return o.push(...C(t)),o}function k(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function P(t,e){let n=Pp(t.routes);if(n.length===0)return[` serves nothing: ${Et} is empty or absent`];let r=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${n.length} project${n.length===1?"":"s"}:`];for(let s of n){r.push(` ${s.slug}${s.slug===e?" (this project)":""}`);for(let o of s.routes)r.push(` ${o.host}${o.path==="/"?"/":o.path} -> ${O(o)}`)}return r}function O(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function C(t){let{slug:e,declared:n,probes:r,servers:s}=t;if(n.length===0)return[`This project ('${e}') declares no sites.`];let o=[`This project ('${e}') declares ${n.length} site${n.length===1?"":"s"}: `+n.map((c)=>c.name).join(", ")],i=n.filter((c)=>c.loopbackOnly);if(i.length>0)o.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=r.filter((c)=>!c.unavailable);if(a.length===0)return o.push(" Nothing to reconcile them against: no box reported what it serves."),o;let p=kp(n,a,e);if(o.push(` ${n.length-i.length-p.length} routed by a box above`),p.length>0){o.push(` ${p.length} not routed by any box above: ${p.map((b)=>b.name).join(", ")}`);let c=r.length-a.length,g=s.length-r.length;if(c>0)o.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(g>0)o.push(` Either they were never deployed, or they are on one of the ${g} server${g===1?"":"s"} this run did not probe.`);else o.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return o}async function aA(t){let e=[];for(let n of t.steps)try{e.push({step:n,state:await n.satisfied()?"satisfied":"pending"})}catch(r){e.push({step:n,state:"unknown",reason:r instanceof Error?r.message:String(r)})}return e}function md(t){return t.filter((e)=>e.state!=="satisfied")}function Np(t){return md(t).some((e)=>e.step.destructive===!0)}function cA(t,e){let n=md(e),r=[`${t.operation} ${t.target}`];if(n.length===0)return r.push(" Nothing to do — every step is already satisfied."),r;for(let{step:o,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[o.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(r.push(` ${p}${o.title}${c.length>0?` [${c.join(", ")}]`:""}`),o.change)r.push(` ${o.change.from} → ${o.change.to}`);if(a)r.push(` could not check: ${a}`)}let s=n.filter((o)=>o.step.destructive).length;return r.push(` ${n.length} step(s) would run`+(s>0?`, ${s} irreversible — re-run with --confirm ${t.target}`:"")),r}async function dA(t,e,n={}){let r={operation:t.operation,target:t.target,steps:[],success:!0};if(Np(e)&&n.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:s,state:o}of e){if(o==="satisfied"){r.steps.push({id:s.id,title:s.title,state:"skipped"}),n.log?.(`skip ${s.title} (already done)`);continue}n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"started"});try{await s.apply(),r.steps.push({id:s.id,title:s.title,state:"applied"}),n.log?.(`done ${s.title}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return r.steps.push({id:s.id,title:s.title,state:"failed",error:a}),r.success=!1,n.log?.(`FAIL ${s.title}: ${a}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"failed",error:a}),r}}return r}function Bp(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function lA(t,e,n){if(Bp(e),t===e)throw Error(`'${t}' is already named that.`);if((await n.takenNames()).some((o)=>o===e&&o!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let s=[];if(n.providerName&&n.renameProvider){let{providerName:o,renameProvider:i}=n;s.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}if(n.stateName&&n.writeStateName){let{stateName:o,writeStateName:i}=n;s.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await o();return a===void 0||a===e},apply:()=>i(e)})}if(n.remoteHostname&&n.setRemoteHostname){let{remoteHostname:o,setRemoteHostname:i}=n;s.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}return s.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>n.inventoryName()===e,apply:async()=>{await n.renameInventory(e)}}),{operation:"server:rename",target:t,steps:s}}function uA(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
9
+ `)}function gA(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function pA(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function mA(t,e,n){let r=[],s=xi(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function fA(t){return t.registryRead&&t.conflicts.length===0}function hA(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function Bi(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function fd(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function xp(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
10
10
  `)}function m(t,e){return`^${t}-${e}-((queue|daemon)-.*|scheduler)\\.service$`}function Op(t,e){return y(m(t,e))}function y(t){return[`ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(t)} | while read -r unit; do`,' systemctl is-active "$unit" >/dev/null 2>&1 && echo "active:$unit" || true',"done"].join(`
11
11
  `)}function _p(t){return!t.split(`
12
- `).some((e)=>e.trim().startsWith("active:"))}function Lp(t,e,n){let r=ki(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${md(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
- `)}function $p(t,e,n){let r=ki(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(md(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
12
+ `).some((e)=>e.trim().startsWith("active:"))}function Lp(t,e,n){let r=Bi(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${fd(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
+ `)}function $p(t,e,n){let r=Bi(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(fd(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
14
14
  `)}function Mp(t,e,n){return[`test -d ${l(n)} && echo tree:present || echo tree:absent`,`systemctl is-active ${t}-${e}.service >/dev/null 2>&1 && echo unit:active || echo unit:inactive`].join(`
15
15
  `)}function Fp(t){return t.includes("tree:present")&&t.includes("unit:active")}function Up(t,e="/",n=10){let r=`http://127.0.0.1:${t}${e.startsWith("/")?e:`/${e}`}`;return["set -eu",`for i in $(seq 1 ${n}); do`,` if curl -fsS -o /dev/null --max-time 5 ${l(r)}; then echo healthy; exit 0; fi`," sleep 3","done",`echo "no healthy response from ${r}" >&2`,"exit 1"].join(`
16
16
  `)}function Qp(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(v(t,e))} || true); do`,' systemctl disable --now "$unit" 2>/dev/null || true',"done",`rm -f /etc/rpx/sites.d/${t}.json 2>/dev/null || true`,"systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true"].join(`
@@ -19,4 +19,4 @@ Verify the site is serving from its new home first, then re-run with ${n} to des
19
19
  `)}function SA(t){let e=new Map;for(let n of t.split(`
20
20
  `)){let r=n.trim();if(!r.startsWith("cert:"))continue;let[,s,o]=r.split(":");if(s&&o)e.set(s,o)}return e}function IA(t,e){for(let[n,r]of t){if(r==="absent")continue;if(e.get(n)!==r)return!1}return!0}function bA(t,e,n){let r=e.flatMap((s)=>[`${s}.crt`,`${s}.key`]);return["set -eu",`rm -f ${l(n)}`,`cd ${l(t)} 2>/dev/null || { echo "no certs dir at ${t}" >&2; exit 0; }`,`TS_CLOUD_CERTS="$(ls ${r.map(l).join(" ")} 2>/dev/null | tr '\\n' ' ' || true)"`,'[ -n "$TS_CLOUD_CERTS" ] || { echo "no certificates to carry"; exit 0; }',`tar czf ${l(n)} $TS_CLOUD_CERTS`].join(`
21
21
  `)}function CA(t,e){return["set -eu",`[ -s ${l(e)} ] || { echo "no certificate archive staged"; exit 0; }`,`mkdir -p ${l(t)}`,`tar xzf ${l(e)} -C ${l(t)}`,`chmod 600 ${l(t)}/*.key 2>/dev/null || true`,`rm -f ${l(e)}`].join(`
22
- `)}async function EA(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>_p(await e.runOnSource(Op(n,r))),apply:async()=>{await e.runOnSource(xp(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:ki(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(Lp(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:ki(n,r),to:`${i}:${s}`},satisfied:async()=>Fp(await e.runOnTarget(Mp(n,r,s))),apply:async()=>{await e.runOnTarget($p(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(Up(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>Gp(await e.runOnSource(Hp(n,r))),apply:async()=>{await e.runOnSource(Qp(n,r))}}),{operation:"site:move",target:r,steps:p}}export{eA,tA,rA,Tp,wp,Rp,nA,Dp,Pp,iA,sA,kp,oA,aA,pd,Np,cA,dA,Bp,lA,uA,gA,pA,mA,fA,hA,ki,md,xp,Op,_p,Lp,$p,Mp,Fp,Up,Qp,Hp,Gp,AA,yA,SA,IA,bA,CA,EA};
22
+ `)}async function EA(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>_p(await e.runOnSource(Op(n,r))),apply:async()=>{await e.runOnSource(xp(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:Bi(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(Lp(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:Bi(n,r),to:`${i}:${s}`},satisfied:async()=>Fp(await e.runOnTarget(Mp(n,r,s))),apply:async()=>{await e.runOnTarget($p(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(Up(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>Gp(await e.runOnSource(Hp(n,r))),apply:async()=>{await e.runOnSource(Qp(n,r))}}),{operation:"site:move",target:r,steps:p}}export{eA,tA,rA,Tp,wp,Rp,nA,Dp,Pp,iA,sA,kp,oA,aA,md,Np,cA,dA,Bp,lA,uA,gA,pA,mA,fA,hA,Bi,fd,xp,Op,_p,Lp,$p,Mp,Fp,Up,Qp,Hp,Gp,AA,yA,SA,IA,bA,CA,EA};