@stacksjs/ts-cloud 0.16.24 → 0.16.26

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 (155) hide show
  1. package/dist/aws/cloudfront.d.ts +88 -49
  2. package/dist/aws/index.js +1 -1
  3. package/dist/bin/chunk-08hxbrmv.js +1 -0
  4. package/dist/bin/{chunk-xh5jcv64.js → chunk-0apv4e8e.js} +3 -3
  5. package/dist/bin/{chunk-wfa8j3wg.js → chunk-0hbrkdrc.js} +2 -2
  6. package/dist/bin/{chunk-jwdcx0mm.js → chunk-10dnawvx.js} +1 -1
  7. package/dist/bin/{chunk-c35qm7as.js → chunk-2857cbf1.js} +1 -1
  8. package/dist/bin/chunk-2qrr4ydb.js +1 -0
  9. package/dist/bin/{chunk-0ytk5g2t.js → chunk-3rzabz10.js} +1 -1
  10. package/dist/bin/{chunk-jdfbahjb.js → chunk-4a8qt6e8.js} +15 -15
  11. package/dist/bin/chunk-4jgespb7.js +1 -0
  12. package/dist/bin/{chunk-prj5b597.js → chunk-4r46kw46.js} +2 -2
  13. package/dist/bin/{chunk-d1psxeqj.js → chunk-4xfwb21f.js} +1 -1
  14. package/dist/bin/{chunk-wffaqgcc.js → chunk-5ky6qf18.js} +25 -25
  15. package/dist/bin/{chunk-257sygzm.js → chunk-817q3s2p.js} +1 -1
  16. package/dist/bin/{chunk-8e7n357e.js → chunk-85733wwc.js} +63 -63
  17. package/dist/bin/{chunk-r3hkc2s3.js → chunk-8hnph1yy.js} +1 -1
  18. package/dist/bin/{chunk-hjv1k8s9.js → chunk-8k87zpnp.js} +5 -5
  19. package/dist/bin/chunk-8tp6srfc.js +2 -0
  20. package/dist/bin/{chunk-988qv730.js → chunk-92rhkvpx.js} +4 -4
  21. package/dist/bin/chunk-aqreqn37.js +1 -0
  22. package/dist/bin/{chunk-5x59x4qw.js → chunk-ccykpema.js} +1 -1
  23. package/dist/bin/{chunk-6eesa8d1.js → chunk-cgyqnbcm.js} +1 -1
  24. package/dist/bin/{chunk-5kc8s9gp.js → chunk-dh6kj6ce.js} +2 -2
  25. package/dist/bin/{chunk-0md2h0an.js → chunk-e3tjy3wg.js} +6 -6
  26. package/dist/bin/chunk-eh3235zq.js +1 -0
  27. package/dist/bin/chunk-eshss5qy.js +2 -0
  28. package/dist/bin/{chunk-m2gwzksz.js → chunk-f4rp62j4.js} +8 -8
  29. package/dist/bin/chunk-ff888cnm.js +1 -0
  30. package/dist/bin/chunk-fjxsj9z9.js +2 -0
  31. package/dist/bin/{chunk-4sq6cvz5.js → chunk-h3shxxh4.js} +2 -2
  32. package/dist/bin/{chunk-apw5bbjg.js → chunk-hvd87xj9.js} +1 -1
  33. package/dist/bin/chunk-jxyt009c.js +1 -0
  34. package/dist/bin/chunk-kxmq7r53.js +1 -0
  35. package/dist/bin/{chunk-9e7pqhj1.js → chunk-qsyna6ng.js} +1 -1
  36. package/dist/bin/{chunk-4y20ry45.js → chunk-qxssaa4s.js} +1 -1
  37. package/dist/bin/{chunk-k9mzq7z9.js → chunk-r2ft7vek.js} +1 -1
  38. package/dist/bin/{chunk-hez48c69.js → chunk-rfvx641h.js} +2 -2
  39. package/dist/bin/chunk-swnef46q.js +1 -0
  40. package/dist/bin/chunk-v95b2dy0.js +1 -0
  41. package/dist/bin/{chunk-ax41jhq7.js → chunk-w23en85y.js} +2 -2
  42. package/dist/bin/chunk-wjwxtz68.js +1 -0
  43. package/dist/bin/{chunk-1fde3e2c.js → chunk-x2r1zm2r.js} +1 -1
  44. package/dist/bin/chunk-z3962as2.js +34 -0
  45. package/dist/bin/{chunk-3b8a3knq.js → chunk-zvt7as22.js} +1 -1
  46. package/dist/bin/cli.js +375 -375
  47. package/dist/bin/dashboard-server.js +1 -1
  48. package/dist/{chunk-bzbryxfm.js → chunk-08tswmb3.js} +1 -1
  49. package/dist/{chunk-4rkjhvgw.js → chunk-0p7ddjt6.js} +9 -9
  50. package/dist/chunk-2nma0bd8.js +92 -0
  51. package/dist/chunk-31qham3c.js +1 -0
  52. package/dist/chunk-3zv0e36t.js +34 -0
  53. package/dist/{chunk-d8w90gsb.js → chunk-49p5cx21.js} +21 -21
  54. package/dist/{chunk-mv7hne2c.js → chunk-5db32a4x.js} +2 -2
  55. package/dist/chunk-7fbfmpyx.js +1 -0
  56. package/dist/{chunk-rgq7m90a.js → chunk-7p1653g6.js} +56 -56
  57. package/dist/{chunk-hzbyj0xd.js → chunk-98qx6m9h.js} +1 -1
  58. package/dist/{chunk-zv85cpt2.js → chunk-b10n1xy5.js} +1 -1
  59. package/dist/chunk-dschvakr.js +1 -0
  60. package/dist/chunk-e44ajkha.js +5 -0
  61. package/dist/{chunk-vtm83crj.js → chunk-k75jv8s6.js} +129 -129
  62. package/dist/{chunk-65yh2h1e.js → chunk-mdqnpbbc.js} +14 -14
  63. package/dist/{chunk-jrrw3ezm.js → chunk-mte9da2p.js} +4 -4
  64. package/dist/chunk-nkd35khb.js +1 -0
  65. package/dist/{chunk-9ca1yafd.js → chunk-q0g0rjn3.js} +1 -1
  66. package/dist/chunk-rxs4y74z.js +2 -0
  67. package/dist/{chunk-97trx8p9.js → chunk-setpnrtg.js} +2 -2
  68. package/dist/chunk-tvwrthfq.js +2 -0
  69. package/dist/{chunk-v7y50hhf.js → chunk-w23wrsa4.js} +70 -70
  70. package/dist/deploy/index.js +1 -1
  71. package/dist/dns/index.js +1 -1
  72. package/dist/drivers/index.js +1 -1
  73. package/dist/index.d.ts +1 -1
  74. package/dist/index.js +36 -36
  75. package/dist/operations/index.js +1 -1
  76. package/dist/protection/index.js +1 -1
  77. package/dist/spend/index.js +1 -1
  78. package/dist/ui/404.html +1 -1
  79. package/dist/ui/accept-invitation.html +1 -1
  80. package/dist/ui/access-denied.html +1 -1
  81. package/dist/ui/account/automation.html +5 -5
  82. package/dist/ui/account/security.html +2 -2
  83. package/dist/ui/applications/compose.html +6 -6
  84. package/dist/ui/applications/new.html +2 -2
  85. package/dist/ui/data/backups.html +5 -5
  86. package/dist/ui/data/services.html +6 -6
  87. package/dist/ui/data/volumes.html +6 -6
  88. package/dist/ui/index.html +6 -6
  89. package/dist/ui/infrastructure/topology.html +6 -6
  90. package/dist/ui/integrations.html +1 -1
  91. package/dist/ui/operations/alerts.html +6 -6
  92. package/dist/ui/operations/configuration.html +6 -6
  93. package/dist/ui/operations/jobs.html +6 -6
  94. package/dist/ui/operations/maintenance.html +5 -5
  95. package/dist/ui/operations/observability.html +6 -6
  96. package/dist/ui/operations/previews.html +6 -6
  97. package/dist/ui/operations/queue.html +6 -6
  98. package/dist/ui/operations/regions.html +6 -6
  99. package/dist/ui/operations/releases.html +6 -6
  100. package/dist/ui/operations/spend.html +6 -6
  101. package/dist/ui/operations/workloads.html +5 -5
  102. package/dist/ui/security.html +2 -2
  103. package/dist/ui/server/actions.html +6 -6
  104. package/dist/ui/server/activity.html +1 -1
  105. package/dist/ui/server/capacity.html +6 -6
  106. package/dist/ui/server/database.html +6 -6
  107. package/dist/ui/server/deployments.html +6 -6
  108. package/dist/ui/server/diagnostics.html +2 -2
  109. package/dist/ui/server/firewall.html +5 -5
  110. package/dist/ui/server/fleet.html +5 -5
  111. package/dist/ui/server/logs.html +6 -6
  112. package/dist/ui/server/metrics.html +6 -6
  113. package/dist/ui/server/security.html +2 -2
  114. package/dist/ui/server/services.html +2 -2
  115. package/dist/ui/server/sites.html +6 -6
  116. package/dist/ui/server/ssh-keys.html +6 -6
  117. package/dist/ui/server/team.html +6 -6
  118. package/dist/ui/server/terminal.html +2 -2
  119. package/dist/ui/serverless/alarms.html +5 -5
  120. package/dist/ui/serverless/assets.html +2 -2
  121. package/dist/ui/serverless/cost.html +2 -2
  122. package/dist/ui/serverless/data.html +6 -6
  123. package/dist/ui/serverless/deployments.html +2 -2
  124. package/dist/ui/serverless/firewall.html +2 -2
  125. package/dist/ui/serverless/functions.html +6 -6
  126. package/dist/ui/serverless/logs.html +6 -6
  127. package/dist/ui/serverless/metrics.html +2 -2
  128. package/dist/ui/serverless/queues.html +5 -5
  129. package/dist/ui/serverless/secrets.html +6 -6
  130. package/dist/ui/serverless/traces.html +6 -6
  131. package/dist/ui/serverless.html +6 -6
  132. package/package.json +3 -3
  133. package/dist/bin/chunk-6aj3h8yk.js +0 -1
  134. package/dist/bin/chunk-78w3bn85.js +0 -1
  135. package/dist/bin/chunk-9b6af1sj.js +0 -1
  136. package/dist/bin/chunk-a07jfqvs.js +0 -1
  137. package/dist/bin/chunk-a3rq51az.js +0 -2
  138. package/dist/bin/chunk-f0fpp4mk.js +0 -2
  139. package/dist/bin/chunk-fpy7nv5g.js +0 -1
  140. package/dist/bin/chunk-fq4nxfec.js +0 -1
  141. package/dist/bin/chunk-ghe1nawv.js +0 -1
  142. package/dist/bin/chunk-kf1p7s61.js +0 -1
  143. package/dist/bin/chunk-q8crt80d.js +0 -1
  144. package/dist/bin/chunk-rpfvv7hw.js +0 -2
  145. package/dist/bin/chunk-wg20x65t.js +0 -34
  146. package/dist/bin/chunk-xb82bmgf.js +0 -1
  147. package/dist/bin/chunk-xxgybh3b.js +0 -1
  148. package/dist/chunk-1ba6keyk.js +0 -1
  149. package/dist/chunk-3x9g48ey.js +0 -92
  150. package/dist/chunk-e3axmek0.js +0 -1
  151. package/dist/chunk-e7m70ex1.js +0 -2
  152. package/dist/chunk-qa6jjv3m.js +0 -1
  153. package/dist/chunk-qrchr75r.js +0 -5
  154. package/dist/chunk-rnjgde95.js +0 -1
  155. package/dist/chunk-t4ynyk8k.js +0 -34
@@ -0,0 +1 @@
1
+ import{w}from"./chunk-f4rp62j4.js";import"./chunk-q3xwh0r8.js";export{w as CloudFrontClient};
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-q3xwh0r8.js";import{U}from"./chunk-5kc8s9gp.js";var S=new Set(["A","AAAA","CNAME"]);function E(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 P(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((s)=>setTimeout(s,o))}class Qe{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 n=1;n<=8;n+=1){let o,s=new AbortController,i=setTimeout(()=>{s.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=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:s.signal})}catch(c){if(r=c,n===8)throw c;await P(n);continue}finally{clearTimeout(i)}if(!o.ok){let c=await o.clone().json().then((d)=>d?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${c?`: ${c}`:""}`),!E(o.status)||n===8)throw r;await P(n,o);continue}let a=await o.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!E(0,a.message)||n===8)throw r;await P(n,o);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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(!Qe.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let s=[];for(let i of o.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)s.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return s}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((s)=>s.type===t.type&&this.getSubdomain(s.name,r)===n&&s.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)o.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let s=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,o);if(Qe.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${s.length>0?` (${s.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(s?.id&&s.content===t.content&&(t.ttl===void 0||s.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||s.priority===t.priority))return{success:!0,id:s.id,message:"Record already up to date"};if(s?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;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}`;return await this.request(`/dns/edit/${r}/${s.id}`,i),{success:!0,id:s.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 n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!s?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${s.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),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(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 Ot{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 n=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let i=await fetch(n,s);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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),n=this.getSubdomain(e.name,r),o={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),s=o.filter((i)=>i.data!==t.content);if(s.length===o.length)return{success:!1,message:"Record not found"};if(s.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,s);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),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((s)=>this.fromGoDaddyRecord(s,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 q=["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"],j=[{name:"x-stx-router",value:"true"}];function y(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function x(e){return`{${e.map(y).join(" ")}}`}function H(e){let t=`http.request.headers[${y(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${y(e.value)})`}function D(e){if(e.length===1)return`http.host eq ${y(e[0])}`;return`http.host in ${x(e)}`}function bs(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=D(e),n=[],s=(t.bypassPaths??[]).map((z)=>`starts_with(http.request.uri.path, ${y(z)})`),a=(t.negotiatedRequestHeaders??j).map(H),c=[...s,...a],d=c.length>0?`(${c.join(" or ")})`:void 0;if(d)n.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${d})`,enabled:!0,action_parameters:{cache:!1}});let g=d?`${r} and not ${d}`:r,p=t.assetExtensions??q,l=p.length>0?`lower(http.request.uri.path.extension) in ${x([...p])}`:void 0;if(l)n.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${l})`,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 R=l?`(${g} and not ${l})`:`(${g})`;if(t.documentEdgeTtl===0)return n.push({action:"set_cache_settings",description:"bypass documents",expression:R,enabled:!0,action_parameters:{cache:!1}}),n;return n.push({action:"set_cache_settings",description:"cache documents",expression:R,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),n}function vs(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${D(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var F="https://api.cloudflare.com/client/v4",T="[ts-cloud]";class Ye{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 n=`${F}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let a=await(await fetch(n,s)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}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 i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.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 s=o.result[0].id;return this.zoneCache.set(r,s),{id:s,name:o.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 n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&S.has(e.type)){if(n.proxied=o,o)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let s=B(e);if(s)n.data=s,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}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),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),n=this.getFullRecordName(t.name,r.name),s=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??s?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(s)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${s.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!s.result||s.result.length===0)return{success:!1,message:"Record not found"};let i=s.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let o=[],s=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${s}`);if(o.push(...a.result||[]),a.result_info)i=s<a.result_info.total_pages,s++;else i=!1}return{success:!0,records:o.map((a)=>this.fromCloudflareRecord(a))}}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 n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(s){let i=s instanceof Error?s.message:String(s);if(!/already exists|1061/i.test(i))throw s;let a=await this.getZoneDetails(r);if(!a)throw s;return{...a,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`),n=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let s of o.hosts||[])n.add(s.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(s.result&&s.result.length>0)return s.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),o=n.id,s=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${a.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`),n={};for(let o of r.result||[])n[o.id]=o.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),o=[],s=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&b(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),o.push({id:i,from:c,to:a})}catch(d){s.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:o,failed:s}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),n={};for(let o of r.result?.managed_request_headers||[])n[o.id]=o.enabled===!0;return n}async applyManagedRequestHeaders(e,t){let r=[],n=[],o=Object.entries(t).filter(([,c])=>c!==void 0);if(o.length===0)return{changed:r,failed:n};let s=await this.getZoneId(e),i;try{i=await this.getManagedRequestHeaders(e)}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of o)n.push({id:g,error:`could not read managed headers — ${d}`});return{changed:r,failed:n}}let a=[];for(let[c,d]of o){if(!(c in i)){n.push({id:c,error:"not a managed request header transform on this zone"});continue}if(i[c]!==d)a.push([c,d])}if(a.length===0)return{changed:r,failed:n};try{await this.request("PATCH",`/zones/${s}/managed_headers`,{managed_request_headers:a.map(([c,d])=>({id:c,enabled:d})),managed_response_headers:[]});for(let[c,d]of a)r.push({id:c,from:i[c],to:d})}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of a)n.push({id:g,error:d})}return{changed:r,failed:n}}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 n=await this.getZoneId(e),o=await this.getPhaseRules(e,t),s=r.map((c)=>({...c,description:c.description?.startsWith(T)?c.description:`${T} ${c.description||t}`})),a=K(o,s).map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}var N=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function _(e){return N.test(e)?e.replace(N,"\x00hosts\x00"):null}function k(e,t){return e.replace(N,D(t))}function w(e){if(Array.isArray(e))return`[${e.map(w).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${w(n)}`).join(",")}}`;return JSON.stringify(e)}function G(e,t){let r=_(e.expression);return r!==null&&r===_(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&w(e.action_parameters)===w(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((s)=>v(s.expression))),n=(s)=>(s.description||"").startsWith(T),o=[];for(let s of e){if(!n(s)){o.push(s);continue}let i=v(s.expression);if(i.length===0){if(r.size>0)o.push(s);continue}let a=i.filter((c)=>!r.has(c));if(a.length===i.length)o.push(s);else if(a.length>0)o.push({...s,expression:k(s.expression,a)})}for(let s of t){let i=v(s.expression),a=i.length>0?o.findIndex((g)=>n(g)&&G(g,s)):-1;if(a===-1){o.push(s);continue}let c=o[a],d=[...new Set([...v(c.expression),...i])];o[a]={...c,expression:k(c.expression,d)}}return o}function v(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 n of r[1].matchAll(/"([^"]+)"/g))t.push(n[1]);return t}function b(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((o,s)=>b(o,t[s]))}let r=e,n=t;return Object.keys(n).every((o)=>b(r[o],n[o]))}function B(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:V(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,o,s]=r.slice(0,3).map(Number);if(![n,o,s].every(Number.isFinite))return null;return{priority:n,weight:o,port:s,target:V(r.slice(3).join(" "))}}function V(e){return e.replace(/\.$/,"")}var X=new Set(["A","AAAA","CNAME","ALIAS"]);function A(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function Z(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let o=h(n);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function eo(e,t){return e.map((r)=>({...r,name:Z(r.name,t),proxied:r.proxied??!1}))}function Y(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(X.has(t.type))return!0;if(t.type==="TXT"){let r=A(t.content);if(r)return A(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function J(e,t){if(f(e.content)!==f(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 to(e){let{provider:t,zone:r,records:n}=e,o={outcomes:[],warnings:[]};if(n.length===0)return o;let s=await t.listRecords(r);if(!s.success)return o.warnings.push(`could not list ${r}: ${s.message||"unknown provider error"} — records not reconciled`),o;let i=s.records;for(let a of n){let c=i.filter((l)=>Y(l,a));if(c.length>0&&c.every((l)=>J(l,a))){o.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},g=a.type==="TXT"&&A(a.content)!==void 0;if(g)for(let l of c){let R=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!R.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${R.message||"unknown error"}`)}let p=g||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)o.outcomes.push({record:a,action:c.length>0?"updated":"created"});else o.outcomes.push({record:a,action:"failed",message:p.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let g=new Set(n.filter((l)=>l.type===a&&h(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&h(l.name)===d&&!g.has(f(l.content).toLowerCase()));for(let l of p)o.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class Yr{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new U(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 n=await this.client.findHostedZoneForDomain(e);if(n){let o=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=re(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?I(t)===I(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((s)=>s.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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(s?.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already present"};let i=[...s?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:s?"UPSERT":"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s?.ttl??t.ttl??300,ResourceRecords:i.map((c)=>({Value:c}))}}]}})).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 n=this.normalizeName(e,t.name),o=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:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(!s||!s.values.some((a)=>this.sameValue(t.type,a,o)))return{success:!0,message:"Record already absent"};let i=s.values.filter((a)=>!this.sameValue(t.type,a,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:i.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s.ttl,ResourceRecords:(i.length>0?i:s.values).map((a)=>({Value:a}))}}]}}),{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 n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let s of n.ResourceRecordSets){if(t&&s.Type!==t)continue;if(s.AliasTarget)continue;for(let i of s.ResourceRecords||[]){let a=i.Value,c;if(s.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(s.Type==="TXT"&&a.startsWith('"'))a=I(a);o.push({name:s.Name.replace(/\.$/,""),type:s.Type,content:a,ttl:s.TTL,priority:c})}}return{success:!0,records:o}}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:U.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=U.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 M=255;function re(e){let t=[];for(let r=0;r<e.length;r+=M)t.push(e.slice(r,r+M));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function I(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&n+1<e.length){t+=e[++n];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function ro(e,t){let r=[],n,o;for(;;){let s=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:o,MaxItems:"100"});if(r.push(...s.ResourceRecordSets),!s.IsTruncated)break;if(n=s.NextRecordName,o=s.NextRecordType,!n)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function O(e){return e.replace(/\.$/,"")}function C(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${O(e.content)}`;return O(e.content)}function ne(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function no(e,t){let r=m(t),n=[],o=[],s=[],i=new Set;for(let a of e){let c=m(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){o.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){o.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),s.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let g=m(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:g,ttl:300,translatedFrom:`${d} ALIAS → ${g}`}),a.AliasTarget.EvaluateTargetHealth)s.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of a.ResourceRecords||[]){let p=se(c,d,g.Value,a.TTL);if("reason"in p){o.push({name:c,type:d,reason:p.reason}),s.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:o,warnings:s}}function se(e,t,r,n){let o={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:ne(r)};case"MX":{let[s,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(i.join(" ")),priority:Number(s)}}case"SRV":{let s=r.trim().split(/\s+/);if(s.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=s.slice(0,3).map(Number);return{...o,type:"SRV",content:m(s.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var oe=new Set(["TXT","MX","SRV","NS","CAA"]);async function io(e,t){let r=[],n=[],o=new Set;try{let s=await e.listRecords(t.zone);for(let i of s.records||[])o.add(`${m(i.name)}|${i.type}|${C(i)}`)}catch{}for(let s of t.records){let i={...s,proxied:!1},a=`${m(s.name)}|${s.type}|${C(s)}`;if(!oe.has(s.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(s);else n.push({record:s,message:d.message||"unknown provider error"});continue}if(o.has(a)){r.push(s);continue}let c=await e.createRecord(t.zone,i);if(c.success)o.add(a),r.push(s);else n.push({record:s,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function oo(e,t){let r=await e.listRecords(t.zone),n=[],o=[],s=new Map;for(let i of r.records||[]){let a=`${m(i.name)}|${i.type}`,c=s.get(a)??[];c.push(C(i)),s.set(a,c)}for(let i of t.records){let a=s.get(`${m(i.name)}|${i.type}`),c=C(i);if(a?.some((d)=>d===c))n.push(i);else o.push({record:i,found:a?.join(", ")})}return{matched:n,missing:o,ok:o.length===0}}class Lt{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new W(t),"provider"in e)this.dnsProvider=L(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:o=30}=e,{CertificateArn:s}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(s);let i=await this.acm.getDnsValidationRecords(s);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(s,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:s,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.upsertRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,records:o.map((s)=>({domainName:s.domainName,recordName:s.recordName,recordType:s.recordType,recordValue:s.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.deleteRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue});if(!i.success)n.push(`Failed to delete record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:o}=e,s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED"){let i=s.SubjectAlternativeNames||[s.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:s.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:n,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:o=[],waitForValidation:s=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:s})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,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 L(e){switch(e.provider){case"route53":return new Yr(e.region,e.hostedZoneId);case"porkbun":return new Qe(e.apiKey,e.secretKey);case"godaddy":return new Ot(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new Ye(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class si{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_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,n=process.env.GODADDY_API_SECRET;if(r&&n){let s=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,s)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{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((o)=>o.provider===e);if(!r)return null;let n=L(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=L(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>L(e))}}var ze=new si;class W{client;region;constructor(e="us-east-1"){this.client=new u,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((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(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((n)=>({CertificateArn:n.CertificateArn,DomainName:n.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((n)=>n.DomainName===e||n.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 n=0;n<t;n++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((s)=>setTimeout(s,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 n=r.DomainName.slice(2),o=t.split("."),s=n.split(".");if(o.slice(-s.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let o=n.slice(2),s=t.split("."),i=o.split(".");if(s.slice(-i.length).join(".")===o)return!0}}return!1}}class so{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new W(e),this.route53=new U,t&&t.provider!=="route53")this.dnsProvider=L(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:o=!1,maxWaitMinutes:s=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(i,s*2,30000))throw Error(`Certificate validation timed out after ${s} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),s=[];if(this.dnsProvider){let i=n||o[0]?.domainName;for(let a of o){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});s.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of o){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});s.push({...i,changeId:a.ChangeInfo?.Id})}return s}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let s=n||o[0]?.domainName;for(let i of o)try{await this.dnsProvider.deleteRecord(s,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let s of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${s.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s.recordName,Type:s.recordType,TTL:300,ResourceRecords:[{Value:s.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED")return{certificateArn:s.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
- export{Qe,Ot,bs,vs,Ye,eo,to,Yr,ro,no,io,oo,W,so,Lt,L,si};
1
+ import{u}from"./chunk-q3xwh0r8.js";import{B}from"./chunk-dh6kj6ce.js";var S=new Set(["A","AAAA","CNAME"]);function E(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 P(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((s)=>setTimeout(s,o))}class Qe{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 n=1;n<=8;n+=1){let o,s=new AbortController,i=setTimeout(()=>{s.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=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:s.signal})}catch(c){if(r=c,n===8)throw c;await P(n);continue}finally{clearTimeout(i)}if(!o.ok){let c=await o.clone().json().then((d)=>d?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${c?`: ${c}`:""}`),!E(o.status)||n===8)throw r;await P(n,o);continue}let a=await o.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!E(0,a.message)||n===8)throw r;await P(n,o);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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(!Qe.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let s=[];for(let i of o.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)s.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return s}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((s)=>s.type===t.type&&this.getSubdomain(s.name,r)===n&&s.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)o.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let s=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,o);if(Qe.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${s.length>0?` (${s.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(s?.id&&s.content===t.content&&(t.ttl===void 0||s.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||s.priority===t.priority))return{success:!0,id:s.id,message:"Record already up to date"};if(s?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;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}`;return await this.request(`/dns/edit/${r}/${s.id}`,i),{success:!0,id:s.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 n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!s?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${s.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),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(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 Ot{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 n=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let i=await fetch(n,s);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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),n=this.getSubdomain(e.name,r),o={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),s=o.filter((i)=>i.data!==t.content);if(s.length===o.length)return{success:!1,message:"Record not found"};if(s.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,s);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),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((s)=>this.fromGoDaddyRecord(s,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 L=["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 y(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function x(e){return`{${e.map(y).join(" ")}}`}function j(e){let t=`http.request.headers[${y(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${y(e.value)})`}function D(e){if(e.length===1)return`http.host eq ${y(e[0])}`;return`http.host in ${x(e)}`}function bs(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=D(e),n=[],s=(t.bypassPaths??[]).map((q)=>`starts_with(http.request.uri.path, ${y(q)})`),a=(t.negotiatedRequestHeaders??U).map(j),c=[...s,...a],d=c.length>0?`(${c.join(" or ")})`:void 0;if(d)n.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${d})`,enabled:!0,action_parameters:{cache:!1}});let g=d?`${r} and not ${d}`:r,p=t.assetExtensions??L,l=p.length>0?`lower(http.request.uri.path.extension) in ${x([...p])}`:void 0;if(l)n.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${l})`,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 R=l?`(${g} and not ${l})`:`(${g})`;if(t.documentEdgeTtl===0)return n.push({action:"set_cache_settings",description:"bypass documents",expression:R,enabled:!0,action_parameters:{cache:!1}}),n;return n.push({action:"set_cache_settings",description:"cache documents",expression:R,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),n}function vs(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${D(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var H="https://api.cloudflare.com/client/v4",T="[ts-cloud]";class Ye{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 n=`${H}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let a=await(await fetch(n,s)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}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 i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.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 s=o.result[0].id;return this.zoneCache.set(r,s),{id:s,name:o.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 n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&S.has(e.type)){if(n.proxied=o,o)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let s=W(e);if(s)n.data=s,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}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),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),n=this.getFullRecordName(t.name,r.name),s=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??s?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(s)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${s.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!s.result||s.result.length===0)return{success:!1,message:"Record not found"};let i=s.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let o=[],s=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${s}`);if(o.push(...a.result||[]),a.result_info)i=s<a.result_info.total_pages,s++;else i=!1}return{success:!0,records:o.map((a)=>this.fromCloudflareRecord(a))}}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 n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(s){let i=s instanceof Error?s.message:String(s);if(!/already exists|1061/i.test(i))throw s;let a=await this.getZoneDetails(r);if(!a)throw s;return{...a,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`),n=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let s of o.hosts||[])n.add(s.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(s.result&&s.result.length>0)return s.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),o=n.id,s=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${a.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`),n={};for(let o of r.result||[])n[o.id]=o.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),o=[],s=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&b(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),o.push({id:i,from:c,to:a})}catch(d){s.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:o,failed:s}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),n={};for(let o of r.result?.managed_request_headers||[])n[o.id]=o.enabled===!0;return n}async applyManagedRequestHeaders(e,t){let r=[],n=[],o=Object.entries(t).filter(([,c])=>c!==void 0);if(o.length===0)return{changed:r,failed:n};let s=await this.getZoneId(e),i;try{i=await this.getManagedRequestHeaders(e)}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of o)n.push({id:g,error:`could not read managed headers — ${d}`});return{changed:r,failed:n}}let a=[];for(let[c,d]of o){if(!(c in i)){n.push({id:c,error:"not a managed request header transform on this zone"});continue}if(i[c]!==d)a.push([c,d])}if(a.length===0)return{changed:r,failed:n};try{await this.request("PATCH",`/zones/${s}/managed_headers`,{managed_request_headers:a.map(([c,d])=>({id:c,enabled:d})),managed_response_headers:[]});for(let[c,d]of a)r.push({id:c,from:i[c],to:d})}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of a)n.push({id:g,error:d})}return{changed:r,failed:n}}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 n=await this.getZoneId(e),o=await this.getPhaseRules(e,t),s=r.map((c)=>({...c,description:c.description?.startsWith(T)?c.description:`${T} ${c.description||t}`})),a=K(o,s).map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}var N=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function _(e){return N.test(e)?e.replace(N,"\x00hosts\x00"):null}function k(e,t){return e.replace(N,D(t))}function w(e){if(Array.isArray(e))return`[${e.map(w).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${w(n)}`).join(",")}}`;return JSON.stringify(e)}function F(e,t){let r=_(e.expression);return r!==null&&r===_(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&w(e.action_parameters)===w(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((s)=>v(s.expression))),n=(s)=>(s.description||"").startsWith(T),o=[];for(let s of e){if(!n(s)){o.push(s);continue}let i=v(s.expression);if(i.length===0){if(r.size>0)o.push(s);continue}let a=i.filter((c)=>!r.has(c));if(a.length===i.length)o.push(s);else if(a.length>0)o.push({...s,expression:k(s.expression,a)})}for(let s of t){let i=v(s.expression),a=i.length>0?o.findIndex((g)=>n(g)&&F(g,s)):-1;if(a===-1){o.push(s);continue}let c=o[a],d=[...new Set([...v(c.expression),...i])];o[a]={...c,expression:k(c.expression,d)}}return o}function v(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 n of r[1].matchAll(/"([^"]+)"/g))t.push(n[1]);return t}function b(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((o,s)=>b(o,t[s]))}let r=e,n=t;return Object.keys(n).every((o)=>b(r[o],n[o]))}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:V(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,o,s]=r.slice(0,3).map(Number);if(![n,o,s].every(Number.isFinite))return null;return{priority:n,weight:o,port:s,target:V(r.slice(3).join(" "))}}function V(e){return e.replace(/\.$/,"")}var X=new Set(["A","AAAA","CNAME","ALIAS"]);function A(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function Z(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let o=h(n);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function eo(e,t){return e.map((r)=>({...r,name:Z(r.name,t),proxied:r.proxied??!1}))}function Y(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(X.has(t.type))return!0;if(t.type==="TXT"){let r=A(t.content);if(r)return A(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function J(e,t){if(f(e.content)!==f(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 to(e){let{provider:t,zone:r,records:n}=e,o={outcomes:[],warnings:[]};if(n.length===0)return o;let s=await t.listRecords(r);if(!s.success)return o.warnings.push(`could not list ${r}: ${s.message||"unknown provider error"} — records not reconciled`),o;let i=s.records;for(let a of n){let c=i.filter((l)=>Y(l,a));if(c.length>0&&c.every((l)=>J(l,a))){o.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},g=a.type==="TXT"&&A(a.content)!==void 0;if(g)for(let l of c){let R=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!R.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${R.message||"unknown error"}`)}let p=g||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)o.outcomes.push({record:a,action:c.length>0?"updated":"created"});else o.outcomes.push({record:a,action:"failed",message:p.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let g=new Set(n.filter((l)=>l.type===a&&h(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&h(l.name)===d&&!g.has(f(l.content).toLowerCase()));for(let l of p)o.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class Yr{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 n=await this.client.findHostedZoneForDomain(e);if(n){let o=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=re(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?I(t)===I(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((s)=>s.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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(s?.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already present"};let i=[...s?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:s?"UPSERT":"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s?.ttl??t.ttl??300,ResourceRecords:i.map((c)=>({Value:c}))}}]}})).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 n=this.normalizeName(e,t.name),o=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:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(!s||!s.values.some((a)=>this.sameValue(t.type,a,o)))return{success:!0,message:"Record already absent"};let i=s.values.filter((a)=>!this.sameValue(t.type,a,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:i.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s.ttl,ResourceRecords:(i.length>0?i:s.values).map((a)=>({Value:a}))}}]}}),{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 n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let s of n.ResourceRecordSets){if(t&&s.Type!==t)continue;if(s.AliasTarget)continue;for(let i of s.ResourceRecords||[]){let a=i.Value,c;if(s.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(s.Type==="TXT"&&a.startsWith('"'))a=I(a);o.push({name:s.Name.replace(/\.$/,""),type:s.Type,content:a,ttl:s.TTL,priority:c})}}return{success:!0,records:o}}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 O=255;function re(e){let t=[];for(let r=0;r<e.length;r+=O)t.push(e.slice(r,r+O));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function I(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&n+1<e.length){t+=e[++n];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function ro(e,t){let r=[],n,o;for(;;){let s=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:o,MaxItems:"100"});if(r.push(...s.ResourceRecordSets),!s.IsTruncated)break;if(n=s.NextRecordName,o=s.NextRecordType,!n)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function z(e){return e.replace(/\.$/,"")}function C(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${z(e.content)}`;return z(e.content)}function ne(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function no(e,t){let r=m(t),n=[],o=[],s=[],i=new Set;for(let a of e){let c=m(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){o.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){o.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),s.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let g=m(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:g,ttl:300,translatedFrom:`${d} ALIAS → ${g}`}),a.AliasTarget.EvaluateTargetHealth)s.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of a.ResourceRecords||[]){let p=se(c,d,g.Value,a.TTL);if("reason"in p){o.push({name:c,type:d,reason:p.reason}),s.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:o,warnings:s}}function se(e,t,r,n){let o={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:ne(r)};case"MX":{let[s,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(i.join(" ")),priority:Number(s)}}case"SRV":{let s=r.trim().split(/\s+/);if(s.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=s.slice(0,3).map(Number);return{...o,type:"SRV",content:m(s.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var oe=new Set(["TXT","MX","SRV","NS","CAA"]);async function io(e,t){let r=[],n=[],o=new Set;try{let s=await e.listRecords(t.zone);for(let i of s.records||[])o.add(`${m(i.name)}|${i.type}|${C(i)}`)}catch{}for(let s of t.records){let i={...s,proxied:!1},a=`${m(s.name)}|${s.type}|${C(s)}`;if(!oe.has(s.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(s);else n.push({record:s,message:d.message||"unknown provider error"});continue}if(o.has(a)){r.push(s);continue}let c=await e.createRecord(t.zone,i);if(c.success)o.add(a),r.push(s);else n.push({record:s,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function oo(e,t){let r=await e.listRecords(t.zone),n=[],o=[],s=new Map;for(let i of r.records||[]){let a=`${m(i.name)}|${i.type}`,c=s.get(a)??[];c.push(C(i)),s.set(a,c)}for(let i of t.records){let a=s.get(`${m(i.name)}|${i.type}`),c=C(i);if(a?.some((d)=>d===c))n.push(i);else o.push({record:i,found:a?.join(", ")})}return{matched:n,missing:o,ok:o.length===0}}class Lt{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new G(t),"provider"in e)this.dnsProvider=M(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:o=30}=e,{CertificateArn:s}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(s);let i=await this.acm.getDnsValidationRecords(s);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(s,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:s,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.upsertRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,records:o.map((s)=>({domainName:s.domainName,recordName:s.recordName,recordType:s.recordType,recordValue:s.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.deleteRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue});if(!i.success)n.push(`Failed to delete record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:o}=e,s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED"){let i=s.SubjectAlternativeNames||[s.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:s.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:n,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:o=[],waitForValidation:s=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:s})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,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 M(e){switch(e.provider){case"route53":return new Yr(e.region,e.hostedZoneId);case"porkbun":return new Qe(e.apiKey,e.secretKey);case"godaddy":return new Ot(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new Ye(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class si{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_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,n=process.env.GODADDY_API_SECRET;if(r&&n){let s=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,s)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{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((o)=>o.provider===e);if(!r)return null;let n=M(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=M(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>M(e))}}var ze=new si;class G{client;region;constructor(e="us-east-1"){this.client=new u,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((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(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((n)=>({CertificateArn:n.CertificateArn,DomainName:n.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((n)=>n.DomainName===e||n.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 n=0;n<t;n++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((s)=>setTimeout(s,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 n=r.DomainName.slice(2),o=t.split("."),s=n.split(".");if(o.slice(-s.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let o=n.slice(2),s=t.split("."),i=o.split(".");if(s.slice(-i.length).join(".")===o)return!0}}return!1}}class so{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new G(e),this.route53=new B,t&&t.provider!=="route53")this.dnsProvider=M(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:o=!1,maxWaitMinutes:s=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(i,s*2,30000))throw Error(`Certificate validation timed out after ${s} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),s=[];if(this.dnsProvider){let i=n||o[0]?.domainName;for(let a of o){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});s.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of o){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});s.push({...i,changeId:a.ChangeInfo?.Id})}return s}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let s=n||o[0]?.domainName;for(let i of o)try{await this.dnsProvider.deleteRecord(s,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let s of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${s.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s.recordName,Type:s.recordType,TTL:300,ResourceRecords:[{Value:s.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED")return{certificateArn:s.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
+ export{Qe,Ot,bs,vs,Ye,eo,to,Yr,ro,no,io,oo,G,so,Lt,M,si};
@@ -1,2 +1,2 @@
1
- import{Mo,dn,ya,Ai,Fo,jo}from"./chunk-jdfbahjb.js";import{e}from"./chunk-3jjggqfj.js";import{ht}from"./chunk-y6rgvb7r.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Fu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Fo({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=jo(r);E(h,i),E(o(a,"runtime"),Ai().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Mo(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await dn({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),ya({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new ht(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
1
+ import{Mo,dn,ya,Ai,Fo,jo}from"./chunk-4a8qt6e8.js";import{e}from"./chunk-3jjggqfj.js";import{ht}from"./chunk-y6rgvb7r.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Fu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Fo({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=jo(r);E(h,i),E(o(a,"runtime"),Ai().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Mo(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await dn({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),ya({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new ht(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
2
2
  export{Fu};