@stacksjs/ts-cloud 0.16.65 → 0.16.67

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 (195) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-v6jm8dsa.js → chunk-0h1ae217.js} +1 -1
  3. package/dist/bin/chunk-19dhvnjh.js +1 -0
  4. package/dist/bin/{chunk-0ejp168p.js → chunk-245rppy4.js} +1 -1
  5. package/dist/bin/{chunk-71b4t3d8.js → chunk-2mdh3syn.js} +2 -2
  6. package/dist/bin/chunk-2r9748kw.js +1 -0
  7. package/dist/bin/{chunk-90ds3vw7.js → chunk-34r2fwwn.js} +1 -1
  8. package/dist/bin/chunk-483ppsv0.js +1 -0
  9. package/dist/bin/{chunk-tpttr74v.js → chunk-5zp3s61y.js} +4 -4
  10. package/dist/bin/{chunk-ya1413jw.js → chunk-6rvejkny.js} +2 -2
  11. package/dist/bin/chunk-6stcmq7g.js +1 -0
  12. package/dist/bin/{chunk-zs0q8sh5.js → chunk-7pxqdq44.js} +1 -1
  13. package/dist/bin/chunk-9fn41ztz.js +1 -0
  14. package/dist/bin/{chunk-aekwpste.js → chunk-9vjg754g.js} +1 -1
  15. package/dist/bin/{chunk-5ad4b744.js → chunk-a68bhc0s.js} +2 -2
  16. package/dist/bin/{chunk-6r04kx46.js → chunk-abk97qeq.js} +2 -2
  17. package/dist/bin/chunk-af8511dv.js +1 -0
  18. package/dist/bin/chunk-asvxjh7p.js +1 -0
  19. package/dist/bin/chunk-bphzq12c.js +1 -0
  20. package/dist/bin/{chunk-zesb85ra.js → chunk-bzjr9jwn.js} +1 -1
  21. package/dist/bin/chunk-c6tt4fj9.js +1 -0
  22. package/dist/bin/chunk-c6yrhzw5.js +1 -0
  23. package/dist/bin/chunk-cf2teb1b.js +1 -0
  24. package/dist/bin/{chunk-v3j9wgmn.js → chunk-dbtm1j98.js} +74 -74
  25. package/dist/bin/chunk-dhb1xs5a.js +1 -0
  26. package/dist/bin/{chunk-nn8k84cd.js → chunk-djqrnrpx.js} +1 -1
  27. package/dist/bin/chunk-dwahpsj4.js +1 -0
  28. package/dist/bin/chunk-er5zfr54.js +1 -0
  29. package/dist/bin/chunk-evbh466n.js +1 -0
  30. package/dist/bin/{chunk-2avtspqd.js → chunk-f4v7nm9a.js} +2 -2
  31. package/dist/bin/{chunk-cf2eyje1.js → chunk-g47h6fg3.js} +6 -6
  32. package/dist/bin/{chunk-38qy0dj2.js → chunk-gvk2af4h.js} +3 -3
  33. package/dist/bin/{chunk-6da5c33e.js → chunk-h2f4f194.js} +2 -2
  34. package/dist/bin/{chunk-tcn6qcc4.js → chunk-jq4xyf7y.js} +1 -1
  35. package/dist/bin/{chunk-kmxkwznm.js → chunk-jwby10he.js} +5 -5
  36. package/dist/bin/{chunk-e51cd46z.js → chunk-jyfm20f3.js} +1 -1
  37. package/dist/bin/{chunk-n667tnf3.js → chunk-k20dxfrh.js} +3 -3
  38. package/dist/bin/{chunk-qpvydcfm.js → chunk-kwfbth5c.js} +5 -5
  39. package/dist/bin/{chunk-75x772gr.js → chunk-mn0rzykt.js} +91 -87
  40. package/dist/bin/chunk-n54ssj0h.js +1 -0
  41. package/dist/bin/{chunk-pe18g092.js → chunk-n80ewf4z.js} +3 -3
  42. package/dist/bin/chunk-nj4eg5vt.js +1 -0
  43. package/dist/bin/{chunk-mver6psb.js → chunk-nxsa7efz.js} +2 -2
  44. package/dist/bin/chunk-p6c2d6em.js +1 -0
  45. package/dist/bin/{chunk-9pj5r0x0.js → chunk-p801tzxz.js} +1 -1
  46. package/dist/bin/{chunk-favx96qj.js → chunk-pxm3w8a3.js} +4 -4
  47. package/dist/bin/chunk-pyxmdv8d.js +1 -0
  48. package/dist/bin/{chunk-v5x06h8w.js → chunk-qascek4k.js} +5 -5
  49. package/dist/bin/{chunk-tw6z2mvh.js → chunk-qjh516ah.js} +13 -13
  50. package/dist/bin/{chunk-eap6bmrq.js → chunk-sb29jzvd.js} +35 -35
  51. package/dist/bin/chunk-shxqbkrz.js +1 -0
  52. package/dist/bin/chunk-sz45s7mw.js +1 -0
  53. package/dist/bin/chunk-va3yvvs0.js +1 -0
  54. package/dist/bin/{chunk-8bgfn8ek.js → chunk-vcs8wtay.js} +2 -2
  55. package/dist/bin/{chunk-sbjzewvk.js → chunk-vf5w5aed.js} +4 -4
  56. package/dist/bin/{chunk-vbq4ten8.js → chunk-vwgpwjwh.js} +3 -3
  57. package/dist/bin/chunk-vy27rc50.js +1 -0
  58. package/dist/bin/{chunk-d38cyam8.js → chunk-xkcvfpd0.js} +4 -4
  59. package/dist/bin/chunk-y815amx5.js +1 -0
  60. package/dist/bin/{chunk-d0q93ecd.js → chunk-yc1n2h5w.js} +5 -5
  61. package/dist/bin/chunk-yec39wzh.js +1 -0
  62. package/dist/bin/{chunk-tg3vzzc4.js → chunk-zs1cpqhv.js} +2 -2
  63. package/dist/bin/cli.js +80 -80
  64. package/dist/bin/dashboard-server.js +1 -1
  65. package/dist/{chunk-rs8v7c67.js → chunk-03eny26f.js} +3 -3
  66. package/dist/{chunk-8jqv6wh7.js → chunk-0860mm00.js} +2 -2
  67. package/dist/chunk-0c48hvb8.js +1 -0
  68. package/dist/{chunk-jt044dg9.js → chunk-0dfyn0bv.js} +103 -99
  69. package/dist/{chunk-tt3pn05f.js → chunk-0kemzwpg.js} +1 -1
  70. package/dist/{chunk-betvtvy7.js → chunk-1t3rjvf9.js} +1 -1
  71. package/dist/{chunk-n0xw26th.js → chunk-3ca6cb1s.js} +1 -1
  72. package/dist/{chunk-r41cawtf.js → chunk-7mpbjr6c.js} +2 -2
  73. package/dist/{chunk-t3ssg8p0.js → chunk-83fy36fn.js} +2 -2
  74. package/dist/chunk-8crqfe8x.js +1 -0
  75. package/dist/chunk-949tycxj.js +1 -0
  76. package/dist/{chunk-et77ydjb.js → chunk-9w5ncn9s.js} +5 -5
  77. package/dist/{chunk-f512g4fq.js → chunk-a92gvctb.js} +5 -5
  78. package/dist/{chunk-bydj8p3h.js → chunk-axcxfz8p.js} +1 -1
  79. package/dist/{chunk-4rxsqf12.js → chunk-bkkwtcnf.js} +29 -29
  80. package/dist/chunk-ecnzvq90.js +1 -0
  81. package/dist/{chunk-mqbsnpsv.js → chunk-eva9hz6q.js} +1 -1
  82. package/dist/{chunk-sqtzajrx.js → chunk-hk1frmnn.js} +1 -1
  83. package/dist/{chunk-7s7w8kzc.js → chunk-m2a60evh.js} +3 -3
  84. package/dist/{chunk-k2bb62em.js → chunk-nkx9pn64.js} +2 -2
  85. package/dist/{chunk-b0s2605f.js → chunk-pah2r8a0.js} +4 -4
  86. package/dist/{chunk-v90w8kbz.js → chunk-pymc2aad.js} +3 -3
  87. package/dist/{chunk-bn3jfrg5.js → chunk-q4408fwg.js} +1 -1
  88. package/dist/{chunk-n3sydv3m.js → chunk-q8vvwmka.js} +1 -1
  89. package/dist/{chunk-2phe49y7.js → chunk-qgtydqpj.js} +12 -12
  90. package/dist/{chunk-8z3jfyk8.js → chunk-qqn369pf.js} +2 -2
  91. package/dist/{chunk-pjdp30dn.js → chunk-r49ynkag.js} +1 -1
  92. package/dist/chunk-s3pe89wj.js +1 -0
  93. package/dist/{chunk-7mw4x3ay.js → chunk-tngsyawj.js} +1 -1
  94. package/dist/chunk-wxjd9gyb.js +1 -0
  95. package/dist/{chunk-gj4hj95p.js → chunk-xd67tr7p.js} +1 -1
  96. package/dist/{chunk-r9ydamw0.js → chunk-y9589qef.js} +70 -70
  97. package/dist/{chunk-e97qhzfe.js → chunk-zgfzc46r.js} +19 -19
  98. package/dist/deploy/index.js +1 -1
  99. package/dist/dns/index.js +1 -1
  100. package/dist/drivers/index.d.ts +1 -1
  101. package/dist/drivers/index.js +1 -1
  102. package/dist/drivers/shared/box-converge.d.ts +10 -2
  103. package/dist/drivers/shared/box-sandbox-converge.test.d.ts +1 -0
  104. package/dist/drivers/shared/releases.d.ts +12 -0
  105. package/dist/index.js +14 -14
  106. package/dist/mail/index.js +1 -1
  107. package/dist/operations/index.js +1 -1
  108. package/dist/protection/index.js +1 -1
  109. package/dist/spend/index.js +1 -1
  110. package/dist/ui/404.html +1 -1
  111. package/dist/ui/accept-invitation.html +1 -1
  112. package/dist/ui/access-denied.html +1 -1
  113. package/dist/ui/account/automation.html +5 -5
  114. package/dist/ui/account/security.html +1 -1
  115. package/dist/ui/applications/compose.html +5 -5
  116. package/dist/ui/applications/new.html +1 -1
  117. package/dist/ui/data/backups.html +5 -5
  118. package/dist/ui/data/services.html +6 -6
  119. package/dist/ui/data/volumes.html +6 -6
  120. package/dist/ui/index.html +6 -6
  121. package/dist/ui/infrastructure/topology.html +5 -5
  122. package/dist/ui/integrations.html +2 -2
  123. package/dist/ui/operations/alerts.html +6 -6
  124. package/dist/ui/operations/configuration.html +5 -5
  125. package/dist/ui/operations/jobs.html +6 -6
  126. package/dist/ui/operations/maintenance.html +5 -5
  127. package/dist/ui/operations/observability.html +6 -6
  128. package/dist/ui/operations/previews.html +6 -6
  129. package/dist/ui/operations/queue.html +5 -5
  130. package/dist/ui/operations/regions.html +5 -5
  131. package/dist/ui/operations/releases.html +6 -6
  132. package/dist/ui/operations/spend.html +6 -6
  133. package/dist/ui/operations/workloads.html +5 -5
  134. package/dist/ui/security.html +2 -2
  135. package/dist/ui/server/actions.html +6 -6
  136. package/dist/ui/server/activity.html +1 -1
  137. package/dist/ui/server/capacity.html +5 -5
  138. package/dist/ui/server/database.html +6 -6
  139. package/dist/ui/server/deployments.html +6 -6
  140. package/dist/ui/server/diagnostics.html +2 -2
  141. package/dist/ui/server/firewall.html +6 -6
  142. package/dist/ui/server/fleet.html +6 -6
  143. package/dist/ui/server/logs.html +6 -6
  144. package/dist/ui/server/metrics.html +6 -6
  145. package/dist/ui/server/security.html +2 -2
  146. package/dist/ui/server/services.html +2 -2
  147. package/dist/ui/server/sites.html +5 -5
  148. package/dist/ui/server/ssh-keys.html +6 -6
  149. package/dist/ui/server/team.html +6 -6
  150. package/dist/ui/server/terminal.html +2 -2
  151. package/dist/ui/serverless/alarms.html +6 -6
  152. package/dist/ui/serverless/assets.html +2 -2
  153. package/dist/ui/serverless/cost.html +2 -2
  154. package/dist/ui/serverless/data.html +6 -6
  155. package/dist/ui/serverless/deployments.html +2 -2
  156. package/dist/ui/serverless/firewall.html +1 -1
  157. package/dist/ui/serverless/functions.html +6 -6
  158. package/dist/ui/serverless/logs.html +6 -6
  159. package/dist/ui/serverless/metrics.html +2 -2
  160. package/dist/ui/serverless/queues.html +5 -5
  161. package/dist/ui/serverless/secrets.html +5 -5
  162. package/dist/ui/serverless/traces.html +6 -6
  163. package/dist/ui/serverless.html +6 -6
  164. package/package.json +3 -3
  165. package/dist/bin/chunk-0v5tsfx5.js +0 -1
  166. package/dist/bin/chunk-3x52axr2.js +0 -1
  167. package/dist/bin/chunk-67mww6gq.js +0 -1
  168. package/dist/bin/chunk-7khzyn7k.js +0 -1
  169. package/dist/bin/chunk-97494wnx.js +0 -1
  170. package/dist/bin/chunk-agmznzms.js +0 -1
  171. package/dist/bin/chunk-ambf5hpg.js +0 -1
  172. package/dist/bin/chunk-b39h9as6.js +0 -1
  173. package/dist/bin/chunk-dfgzav9j.js +0 -1
  174. package/dist/bin/chunk-g0w0jec3.js +0 -1
  175. package/dist/bin/chunk-g514nb80.js +0 -1
  176. package/dist/bin/chunk-hknz7fsr.js +0 -1
  177. package/dist/bin/chunk-k8qrjnyg.js +0 -1
  178. package/dist/bin/chunk-kqstefmv.js +0 -1
  179. package/dist/bin/chunk-mk2h37pm.js +0 -1
  180. package/dist/bin/chunk-mxa9rrw0.js +0 -1
  181. package/dist/bin/chunk-nrtjmzzn.js +0 -1
  182. package/dist/bin/chunk-q3rch5hc.js +0 -1
  183. package/dist/bin/chunk-qqb6h33k.js +0 -1
  184. package/dist/bin/chunk-r1p3k2tn.js +0 -1
  185. package/dist/bin/chunk-t8xq3v3j.js +0 -1
  186. package/dist/bin/chunk-xb48vxmk.js +0 -1
  187. package/dist/bin/chunk-yehb738r.js +0 -1
  188. package/dist/bin/chunk-ythfx8pv.js +0 -1
  189. package/dist/bin/chunk-zynfzzjk.js +0 -1
  190. package/dist/chunk-3b08b1zx.js +0 -1
  191. package/dist/chunk-9sdkhmav.js +0 -1
  192. package/dist/chunk-fc9n4dpq.js +0 -1
  193. package/dist/chunk-kfcct0jz.js +0 -1
  194. package/dist/chunk-v34tdcwv.js +0 -1
  195. package/dist/chunk-xq7xs8bh.js +0 -1
@@ -0,0 +1 @@
1
+ import{Kl,k,Wl,ra,ES,Gf,vS,TS,wS,RS,DS,PS,kS,NS}from"./chunk-m2a60evh.js";export{DS as clearSigningKeyCache,ra as createPresignedUrl,ES as createPresignedUrlAsync,Kl as detectServiceRegion,PS as getSigningKeyCacheSize,kS as isNodeCryptoAvailable,NS as isWebCryptoAvailable,Gf as makeAWSRequest,TS as makeAWSRequestAsync,vS as makeAWSRequestOnce,RS as parseJSONResponse,wS as parseXMLResponse,k as signRequest,Wl as signRequestAsync};
@@ -1 +1 @@
1
- import{on}from"./chunk-8z3jfyk8.js";var Jl="\x00";function na(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function f(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function ss(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!na(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function os(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class ia{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>ss(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=os(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!ss(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=os(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Xl(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function Yl(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var Zl="protection.controls",as=24,sa=4,g={ipRules:{allow:[],block:[]}};function m(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function p(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(as,Math.max(0.25,e))}var h=500;class oa{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Zl);if(!t||typeof t!=="object"||Array.isArray(t))return{...g,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(Zl,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:m(i.attackMode,t),mitigationPause:m(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+p(t.hours,sa)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+p(t.hours,as)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!on(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>h)throw Error(`At most ${h} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function eu(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function tu(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function aa(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function xS(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:aa(o,i)}}}}export{Jl,na,ss,os,ia,Xl,Yl,Zl,as,sa,oa,eu,tu,aa,xS};
1
+ import{on}from"./chunk-qqn369pf.js";var Jl="\x00";function na(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function f(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function ss(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!na(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function os(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class ia{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>ss(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=os(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!ss(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=os(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Xl(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function Yl(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var Zl="protection.controls",as=24,sa=4,g={ipRules:{allow:[],block:[]}};function m(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function p(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(as,Math.max(0.25,e))}var h=500;class oa{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Zl);if(!t||typeof t!=="object"||Array.isArray(t))return{...g,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(Zl,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:m(i.attackMode,t),mitigationPause:m(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+p(t.hours,sa)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+p(t.hours,as)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!on(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>h)throw Error(`At most ${h} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function eu(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function tu(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function aa(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function OS(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:aa(o,i)}}}}export{Jl,na,ss,os,ia,Xl,Yl,Zl,as,sa,oa,eu,tu,aa,OS};
@@ -1,4 +1,4 @@
1
- import{Ko,pn,Ql,fn,ea,ta}from"./chunk-r9ydamw0.js";import{He}from"./chunk-n0xw26th.js";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function b(t,e){return`${r[e]}${t}${r.reset}`}function $n(t){console.log(`${r.green}✓${r.reset} ${t}`)}function Ig(t){console.error(`${r.red}✗${r.reset} ${t}`)}function Bs(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function L(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function P(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function xs(t){console.log(`
1
+ import{Ko,pn,Ql,fn,ea,ta}from"./chunk-y9589qef.js";import{He}from"./chunk-3ca6cb1s.js";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function b(t,e){return`${r[e]}${t}${r.reset}`}function $n(t){console.log(`${r.green}✓${r.reset} ${t}`)}function Ig(t){console.error(`${r.red}✗${r.reset} ${t}`)}function Bs(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function L(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function P(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function xs(t){console.log(`
2
2
  ${r.bright}${r.cyan}${t}${r.reset}
3
3
  `)}var F=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function bg(t,e="cyan"){let n=t.split(`
4
4
  `),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(b(`┌${a}┐`,e)),n.forEach((l)=>{console.log(b(`│ ${l.padEnd(i)} │`,e))}),console.log(b(`└${a}┘`,e))}import{execFileSync as k}from"node:child_process";import{mkdirSync as I,mkdtempSync as M,rmSync as U,writeFileSync as d}from"node:fs";import{tmpdir as O}from"node:os";import{dirname as j,join as s}from"node:path";function C(t,e){for(let n of e){let i=s(t,n.name);I(j(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function hc(t){let{app:e,projectRoot:n,region:i,repository:a}=t,l=e.architecture??"x86_64",A=l==="arm64"?"linux/arm64":"linux/amd64",R=e.kind==="php",c=t.onStep??(()=>{}),p=M(s(O(),"tscloud-img-"));try{let f=s(p,"app");I(f,{recursive:!0});let y,w;if(R){ea({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c}),c("staging application tree");let o=ta(n);C(f,o),C(s(p,"runtime"),fn().map((g)=>({name:g.path,data:g.contents,mode:g.mode})));let B=e.handlers?.http??"public/index.php";y={http:B,queue:e.handlers?.queue??B,cli:e.handlers?.cli??B},w=Ko(o.map((g)=>`${g.name}:${g.data.length}`).join("|"))}else{c("bundling application");let o=await pn({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c});d(s(f,"index.mjs"),o.bundle),y=o.handlers,w=o.sha256}let S=w.slice(0,16);d(s(p,"Dockerfile"),Ql({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:l}));let v=new He(i),u;try{u=(await v.describeRepositories({repositoryNames:[a]})).repositories?.[0]?.repositoryUri??""}catch{u=""}if(!u)c(`creating ECR repository ${a}`),u=(await v.createRepository({repositoryName:a,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!u)throw Error(`could not resolve ECR repository URI for ${a}`);let m=`${u}:${S}`;c("docker build"),k("docker",["build","--platform",A,"--provenance=false","--sbom=false","-t",m,p],{stdio:"inherit"}),c("ecr auth + push");let h=(await v.getAuthorizationToken()).authorizationData?.[0];if(!h?.authorizationToken||!h.proxyEndpoint)throw Error("failed to get an ECR authorization token");let E=h.proxyEndpoint.replace(/^https?:\/\//,""),x=s(p,".docker");return I(x,{recursive:!0}),d(s(x,"config.json"),JSON.stringify({auths:{[E]:{auth:h.authorizationToken}}})),k("docker",["push",m],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:x}}),L(`Image: ${m}`),{imageUri:m,tag:S,handlers:y}}finally{U(p,{recursive:!0,force:!0})}}
@@ -8,7 +8,7 @@ var q;try{q=await import("node:crypto")}catch{}var v=new Map,_=100,ee={appstream
8
8
  `),w=J(r,d,h,a,R,g??v);return o.searchParams.set("X-Amz-Signature",w),{url:o.toString(),method:t,headers:{},body:s||void 0}}async function ne(e){let{urlObj:n,method:t,body:s,accessKeyId:c,secretAccessKey:r,sessionToken:i,service:a,region:h,timestamp:m,date:d,credentialScope:f,algorithm:p,expiresIn:u,cache:g}=e,o=new URL(n.toString());o.searchParams.set("X-Amz-Algorithm",p),o.searchParams.set("X-Amz-Credential",`${c}/${f}`),o.searchParams.set("X-Amz-Date",m),o.searchParams.set("X-Amz-Expires",String(u));let y=a==="s3"?"UNSIGNED-PAYLOAD":await T(s);if(a==="s3")o.searchParams.set("X-Amz-Content-Sha256",y);let S="host";if(o.searchParams.set("X-Amz-SignedHeaders",S),i)o.searchParams.set("X-Amz-Security-Token",i);let b=O(o.pathname||"/"),A=`host:${o.hostname}
9
9
  `,x=j(o.searchParams),l=[t,b,x,A,S,y].join(`
10
10
  `),R=[p,m,f,await T(l)].join(`
11
- `),w=await V(r,d,h,a,R,g??v);return o.searchParams.set("X-Amz-Signature",w),{url:o.toString(),method:t,headers:{},body:s||void 0}}function ra(e){let{url:n,method:t="GET",expiresIn:s=3600,...c}=e,r=Math.min(s,604800);return k({...c,url:n,method:t,signQuery:!0,expiresIn:r}).url}async function CS(e){let{url:n,method:t="GET",expiresIn:s=3600,...c}=e,r=Math.min(s,604800);return(await Wl({...c,url:n,method:t,signQuery:!0,expiresIn:r})).url}function N(e){return Object.keys(e).sort().map((n)=>`${n.toLowerCase()}:${e[n].trim().replace(/\s+/g," ")}`).join(`
11
+ `),w=await V(r,d,h,a,R,g??v);return o.searchParams.set("X-Amz-Signature",w),{url:o.toString(),method:t,headers:{},body:s||void 0}}function ra(e){let{url:n,method:t="GET",expiresIn:s=3600,...c}=e,r=Math.min(s,604800);return k({...c,url:n,method:t,signQuery:!0,expiresIn:r}).url}async function ES(e){let{url:n,method:t="GET",expiresIn:s=3600,...c}=e,r=Math.min(s,604800);return(await Wl({...c,url:n,method:t,signQuery:!0,expiresIn:r})).url}function N(e){return Object.keys(e).sort().map((n)=>`${n.toLowerCase()}:${e[n].trim().replace(/\s+/g," ")}`).join(`
12
12
  `)+`
13
- `}function G(e){return Object.keys(e).sort().map((n)=>n.toLowerCase()).join(";")}function j(e){let n=[];return e.forEach((t,s)=>{n.push([Q(s),Q(t)])}),n.sort((t,s)=>{if(t[0]<s[0])return-1;if(t[0]>s[0])return 1;if(t[1]<s[1])return-1;if(t[1]>s[1])return 1;return 0}),n.map(([t,s])=>`${t}=${s}`).join("&")}function O(e){return e.split("/").map((n)=>Q(n)).join("/")}function Q(e){return encodeURIComponent(e).replace(/[!'()*]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}function E(e){if(!q)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return q.createHash("sha256").update(e,"utf8").digest("hex")}function C(e,n){if(!q)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return q.createHmac("sha256",e).update(n,"utf8").digest()}async function T(e){let t=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",t);return Y(new Uint8Array(s))}async function z(e,n){let t=new TextEncoder,s=typeof e==="string"?t.encode(e):e,c=t.encode(n),r=await crypto.subtle.importKey("raw",s.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",r,c.buffer);return new Uint8Array(i)}function Y(e){return Array.from(e).map((n)=>n.toString(16).padStart(2,"0")).join("")}function J(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let h=C(`AWS4${e}`,n),m=C(h,t),d=C(m,s);if(a=C(d,"aws4_request"),r.size>=_){let f=r.keys().next().value;if(f)r.delete(f)}r.set(i,a)}return C(a,c).toString("hex")}async function V(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let m=await z(`AWS4${e}`,n),d=await z(m,t),f=await z(d,s);if(a=await z(f,"aws4_request"),r.size>=_){let p=r.keys().next().value;if(p)r.delete(p)}r.set(i,a)}let h=await z(a,c);return Y(h)}function Z(e,n){return n.includes(e)}function H(e,n,t){let s=n*Math.pow(2,e),c=Math.random()*0.3*s;return Math.min(s+c,t)}function I(e){return new Promise((n)=>setTimeout(n,e))}async function Hf(e,n){let{maxRetries:t=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:r=[429,500,502,503,504],timeoutMs:i=30000}=n??{},a,h;for(let m=0;m<=t;m++){let d=k(e),f={method:d.method,headers:d.headers};if(d.body)f.body=d.body;let p=new AbortController,u=setTimeout(()=>p.abort(),i);f.signal=p.signal;try{let g=await fetch(d.url,f);if(clearTimeout(u),h=g,g.ok)return g;if(m<t&&Z(g.status,r)){let y=H(m,s,c);await I(y);continue}let o=await g.text();throw Error(`AWS API request failed (${g.status}): ${o}`)}catch(g){if(clearTimeout(u),a=g,g instanceof Error&&g.name==="AbortError")a=Error(`Request timed out after ${i}ms`);if(m<t&&!(g instanceof Error&&g.message.includes("AWS API request failed"))){let o=H(m,s,c);await I(o);continue}throw a}}throw a??Error("Request failed after retries")}async function ES(e){return Hf(e,{maxRetries:0})}async function vS(e,n){let{maxRetries:t=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:r=[429,500,502,503,504],timeoutMs:i=30000}=n??{},a;for(let h=0;h<=t;h++){let m=await Wl(e),d={method:m.method,headers:m.headers};if(m.body)d.body=m.body;let f=new AbortController,p=setTimeout(()=>f.abort(),i);d.signal=f.signal;try{let u=await fetch(m.url,d);if(clearTimeout(p),u.ok)return u;if(h<t&&Z(u.status,r)){let o=H(h,s,c);await I(o);continue}let g=await u.text();throw Error(`AWS API request failed (${u.status}): ${g}`)}catch(u){if(clearTimeout(p),a=u,u instanceof Error&&u.name==="AbortError")a=Error(`Request timed out after ${i}ms`);if(h<t&&!(u instanceof Error&&u.message.includes("AWS API request failed"))){let g=H(h,s,c);await I(g);continue}throw a}}throw a??Error("Request failed after retries")}async function TS(e){let n=await e.text(),t={},s=/<(\w+)>([^<]+)<\/\1>/g,c;while((c=s.exec(n))!==null){let[,r,i]=c;t[r]=i}return t}async function wS(e){return await e.json()}function RS(){v.clear()}function DS(){return v.size}function PS(){return q!==void 0}function kS(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}
14
- export{Kl,k,Wl,ra,CS,Hf,ES,vS,TS,wS,RS,DS,PS,kS};
13
+ `}function G(e){return Object.keys(e).sort().map((n)=>n.toLowerCase()).join(";")}function j(e){let n=[];return e.forEach((t,s)=>{n.push([Q(s),Q(t)])}),n.sort((t,s)=>{if(t[0]<s[0])return-1;if(t[0]>s[0])return 1;if(t[1]<s[1])return-1;if(t[1]>s[1])return 1;return 0}),n.map(([t,s])=>`${t}=${s}`).join("&")}function O(e){return e.split("/").map((n)=>Q(n)).join("/")}function Q(e){return encodeURIComponent(e).replace(/[!'()*]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}function E(e){if(!q)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return q.createHash("sha256").update(e,"utf8").digest("hex")}function C(e,n){if(!q)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return q.createHmac("sha256",e).update(n,"utf8").digest()}async function T(e){let t=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",t);return Y(new Uint8Array(s))}async function z(e,n){let t=new TextEncoder,s=typeof e==="string"?t.encode(e):e,c=t.encode(n),r=await crypto.subtle.importKey("raw",s.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",r,c.buffer);return new Uint8Array(i)}function Y(e){return Array.from(e).map((n)=>n.toString(16).padStart(2,"0")).join("")}function J(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let h=C(`AWS4${e}`,n),m=C(h,t),d=C(m,s);if(a=C(d,"aws4_request"),r.size>=_){let f=r.keys().next().value;if(f)r.delete(f)}r.set(i,a)}return C(a,c).toString("hex")}async function V(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let m=await z(`AWS4${e}`,n),d=await z(m,t),f=await z(d,s);if(a=await z(f,"aws4_request"),r.size>=_){let p=r.keys().next().value;if(p)r.delete(p)}r.set(i,a)}let h=await z(a,c);return Y(h)}function Z(e,n){return n.includes(e)}function H(e,n,t){let s=n*Math.pow(2,e),c=Math.random()*0.3*s;return Math.min(s+c,t)}function I(e){return new Promise((n)=>setTimeout(n,e))}async function Gf(e,n){let{maxRetries:t=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:r=[429,500,502,503,504],timeoutMs:i=30000}=n??{},a,h;for(let m=0;m<=t;m++){let d=k(e),f={method:d.method,headers:d.headers};if(d.body)f.body=d.body;let p=new AbortController,u=setTimeout(()=>p.abort(),i);f.signal=p.signal;try{let g=await fetch(d.url,f);if(clearTimeout(u),h=g,g.ok)return g;if(m<t&&Z(g.status,r)){let y=H(m,s,c);await I(y);continue}let o=await g.text();throw Error(`AWS API request failed (${g.status}): ${o}`)}catch(g){if(clearTimeout(u),a=g,g instanceof Error&&g.name==="AbortError")a=Error(`Request timed out after ${i}ms`);if(m<t&&!(g instanceof Error&&g.message.includes("AWS API request failed"))){let o=H(m,s,c);await I(o);continue}throw a}}throw a??Error("Request failed after retries")}async function vS(e){return Gf(e,{maxRetries:0})}async function TS(e,n){let{maxRetries:t=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:r=[429,500,502,503,504],timeoutMs:i=30000}=n??{},a;for(let h=0;h<=t;h++){let m=await Wl(e),d={method:m.method,headers:m.headers};if(m.body)d.body=m.body;let f=new AbortController,p=setTimeout(()=>f.abort(),i);d.signal=f.signal;try{let u=await fetch(m.url,d);if(clearTimeout(p),u.ok)return u;if(h<t&&Z(u.status,r)){let o=H(h,s,c);await I(o);continue}let g=await u.text();throw Error(`AWS API request failed (${u.status}): ${g}`)}catch(u){if(clearTimeout(p),a=u,u instanceof Error&&u.name==="AbortError")a=Error(`Request timed out after ${i}ms`);if(h<t&&!(u instanceof Error&&u.message.includes("AWS API request failed"))){let g=H(h,s,c);await I(g);continue}throw a}}throw a??Error("Request failed after retries")}async function wS(e){let n=await e.text(),t={},s=/<(\w+)>([^<]+)<\/\1>/g,c;while((c=s.exec(n))!==null){let[,r,i]=c;t[r]=i}return t}async function RS(e){return await e.json()}function DS(){v.clear()}function PS(){return v.size}function kS(){return q!==void 0}function NS(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}
14
+ export{Kl,k,Wl,ra,ES,Gf,vS,TS,wS,RS,DS,PS,kS,NS};
@@ -33,5 +33,5 @@ fi
33
33
 
34
34
  mv "${s}.new" "${s}"
35
35
  echo "ts-cloud: WAF config installed (mode: ${n.mode})"
36
- `}function Sp(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
- export{oe,Pi,lo,cd,ki,Sp};
36
+ `}function Ip(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
+ export{oe,Pi,lo,cd,ki,Ip};
@@ -1,4 +1,4 @@
1
- import{dn,pr}from"./chunk-r9ydamw0.js";import{zr,d}from"./chunk-8jqv6wh7.js";import{isIP as L}from"node:net";var uo="/etc/rpx/certs",A="/etc/rpx/local-ca",M="rpx-root-ca.crt";function go(e=A){return`${e.replace(/\/+$/,"")}/${M}`}function po(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function mo(e,t={}){let r=new Set;for(let o of Object.values(e)){if(!o?.domain)continue;if(d(o)==="bucket")continue;r.add(o.domain)}let n=new Set;for(let o of Object.values(e)){if(!o?.domain||d(o)==="bucket")continue;for(let u of o.aliases??[]){let i=String(u).trim().toLowerCase();if(i&&i!==o.domain)n.add(i)}}if(t.autoWww!==!1)for(let o of[...r]){if(!po(o))continue;r.add(`www.${o}`)}for(let o of n)r.add(o);return[...r]}var k=["1.1.1.1","8.8.8.8"],I="/var/www/acme-challenge";function W(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function U(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function dd(e){if(!e)return;return e.tls??"local-ca"}function Ip(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function bp(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function X(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(L(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function F(e,t,r){let n=[],o=new Set,u=(g,a)=>{let p=g.trim().toLowerCase();if(!p||o.has(p))return;o.add(p),n.push({host:p,source:a})},i=t.hostname?.trim(),c=(i||`${r}.local`).toLowerCase();if(u(c,i?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([g,a])=>!!a&&pr(g)))u(`dashboard.${c}`,"the management dashboard site");for(let[g,a]of Object.entries(e)){if(!a?.domain)continue;if(d(a)==="bucket")continue;if(!X(a.domain))continue;u(a.domain,`site "${g}"`)}return n}function H(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function K(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let o=H(r,t.allowedSuffixes);if(!o)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${o}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function V(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function D(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function Yh(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ld(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Y(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function N(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),o=t.slug??"app",u=t.proxy.certsDir??uo,i=t.proxy.loadBalancer,c=[],f=new Set,g=new Map;for(let[l,s]of Object.entries(e)){if(!s||!s.domain)continue;let w=d(s);if(w==="bucket")continue;let v=c.length,E=[...new Set((s.aliases??[]).map((m)=>String(m).trim().toLowerCase()).filter((m)=>m&&m!==s.domain))],b=()=>{let m=c.slice(v).filter((h)=>h.to===s.domain);for(let h of E){for(let O of m)c.push({...O,to:h,id:ld(h,O.path)});if(V(h)){if(!g.has(h))g.set(h,{domain:h,dnsEnvFile:`${n}/${o}-${l}/shared/.env`})}else f.add(h)}},C=Yh(s.path),S=ld(s.domain,C),y=U(s);if(w==="redirect"){c.push({to:s.domain,path:C,redirect:W(s.redirect),id:S,...y?{auth:y}:{}}),f.add(s.domain),b();continue}if(w==="proxy"){let m=zr(s);if(m.length===0)continue;let h=m.length===1?m[0]:m;c.push({to:s.domain,path:C,from:h,id:S,...y?{auth:y}:{},...Array.isArray(h)&&i?{loadBalancer:i}:{}}),f.add(s.domain),b();continue}if(w==="server-app"){if(typeof s.port!=="number")continue;let m=Y(s.port,r);c.push({to:s.domain,path:C,from:m,id:S,...y?{auth:y}:{},...Array.isArray(m)&&i?{loadBalancer:i}:{}})}else c.push({to:s.domain,path:C,static:{dir:`${n}/${o}-${l}/current`,spa:s.spa??!1,pathRewriteStyle:s.pathRewriteStyle??"directory"},cleanUrls:s.pathRewriteStyle!=="flat",...y?{auth:y}:{},id:S});f.add(s.domain),b()}if(t.proxy.autoWww!==!1)for(let l of[...f]){if(!po(l))continue;let s=`www.${l}`;if(f.has(s))continue;c.push({to:s,redirect:{to:`https://${l}`},id:ld(s)}),f.add(s)}c.sort((l,s)=>{if(l.to!==s.to)return l.to.localeCompare(s.to);return(s.path?.length??0)-(l.path?.length??0)});let a={proxies:c,productionCerts:{certsDir:u,certsDirServerNames:[...f,...g.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...g.size>0?{wildcardCerts:[...g.values()]}:{}};if(t.proxy.onDemandTls&&f.size>0)a.onDemandTls={enabled:!0,allowedSuffixes:[...f],email:t.proxy.onDemandTlsEmail,certsDir:u,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)a.acmeChallengeWebroot=t.proxy.acmeWebroot??I;let p=t.proxy.cdn,x=p?.frontedHosts?.length?p.frontedHosts:[...f];if(p?.secret&&x.length>0)a.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:x};if(t.lan)if(dd(t.lan)==="off")a.https=!1;else{let l=F(e,t.lan,o);K(l,a.onDemandTls);let s=t.lan.ip&&L(t.lan.ip)!==0?[t.lan.ip]:[];a.localCa={dir:A,hosts:l.map((w)=>w.host),...s.length>0?{ips:s}:{},installTrust:!0}}return a}function B(e,t){return N({...e,...t.mail?dn(t.mail):{}},t)}function tr(e,t,r){return N({...e,...r.mail?dn(r.mail):{}},r,t)}function DI(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
1
+ import{dn,pr}from"./chunk-y9589qef.js";import{zr,d}from"./chunk-0860mm00.js";import{isIP as L}from"node:net";var uo="/etc/rpx/certs",A="/etc/rpx/local-ca",M="rpx-root-ca.crt";function go(e=A){return`${e.replace(/\/+$/,"")}/${M}`}function po(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function mo(e,t={}){let r=new Set;for(let o of Object.values(e)){if(!o?.domain)continue;if(d(o)==="bucket")continue;r.add(o.domain)}let n=new Set;for(let o of Object.values(e)){if(!o?.domain||d(o)==="bucket")continue;for(let u of o.aliases??[]){let i=String(u).trim().toLowerCase();if(i&&i!==o.domain)n.add(i)}}if(t.autoWww!==!1)for(let o of[...r]){if(!po(o))continue;r.add(`www.${o}`)}for(let o of n)r.add(o);return[...r]}var k=["1.1.1.1","8.8.8.8"],I="/var/www/acme-challenge";function W(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function U(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function dd(e){if(!e)return;return e.tls??"local-ca"}function bp(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Cp(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function X(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(L(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function F(e,t,r){let n=[],o=new Set,u=(g,a)=>{let p=g.trim().toLowerCase();if(!p||o.has(p))return;o.add(p),n.push({host:p,source:a})},i=t.hostname?.trim(),c=(i||`${r}.local`).toLowerCase();if(u(c,i?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([g,a])=>!!a&&pr(g)))u(`dashboard.${c}`,"the management dashboard site");for(let[g,a]of Object.entries(e)){if(!a?.domain)continue;if(d(a)==="bucket")continue;if(!X(a.domain))continue;u(a.domain,`site "${g}"`)}return n}function H(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function K(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let o=H(r,t.allowedSuffixes);if(!o)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${o}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function V(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function D(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function Zh(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ld(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Y(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function N(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),o=t.slug??"app",u=t.proxy.certsDir??uo,i=t.proxy.loadBalancer,c=[],f=new Set,g=new Map;for(let[l,s]of Object.entries(e)){if(!s||!s.domain)continue;let w=d(s);if(w==="bucket")continue;let v=c.length,E=[...new Set((s.aliases??[]).map((m)=>String(m).trim().toLowerCase()).filter((m)=>m&&m!==s.domain))],b=()=>{let m=c.slice(v).filter((h)=>h.to===s.domain);for(let h of E){for(let O of m)c.push({...O,to:h,id:ld(h,O.path)});if(V(h)){if(!g.has(h))g.set(h,{domain:h,dnsEnvFile:`${n}/${o}-${l}/shared/.env`})}else f.add(h)}},C=Zh(s.path),S=ld(s.domain,C),y=U(s);if(w==="redirect"){c.push({to:s.domain,path:C,redirect:W(s.redirect),id:S,...y?{auth:y}:{}}),f.add(s.domain),b();continue}if(w==="proxy"){let m=zr(s);if(m.length===0)continue;let h=m.length===1?m[0]:m;c.push({to:s.domain,path:C,from:h,id:S,...y?{auth:y}:{},...Array.isArray(h)&&i?{loadBalancer:i}:{}}),f.add(s.domain),b();continue}if(w==="server-app"){if(typeof s.port!=="number")continue;let m=Y(s.port,r);c.push({to:s.domain,path:C,from:m,id:S,...y?{auth:y}:{},...Array.isArray(m)&&i?{loadBalancer:i}:{}})}else c.push({to:s.domain,path:C,static:{dir:`${n}/${o}-${l}/current`,spa:s.spa??!1,pathRewriteStyle:s.pathRewriteStyle??"directory"},cleanUrls:s.pathRewriteStyle!=="flat",...y?{auth:y}:{},id:S});f.add(s.domain),b()}if(t.proxy.autoWww!==!1)for(let l of[...f]){if(!po(l))continue;let s=`www.${l}`;if(f.has(s))continue;c.push({to:s,redirect:{to:`https://${l}`},id:ld(s)}),f.add(s)}c.sort((l,s)=>{if(l.to!==s.to)return l.to.localeCompare(s.to);return(s.path?.length??0)-(l.path?.length??0)});let a={proxies:c,productionCerts:{certsDir:u,certsDirServerNames:[...f,...g.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...g.size>0?{wildcardCerts:[...g.values()]}:{}};if(t.proxy.onDemandTls&&f.size>0)a.onDemandTls={enabled:!0,allowedSuffixes:[...f],email:t.proxy.onDemandTlsEmail,certsDir:u,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)a.acmeChallengeWebroot=t.proxy.acmeWebroot??I;let p=t.proxy.cdn,x=p?.frontedHosts?.length?p.frontedHosts:[...f];if(p?.secret&&x.length>0)a.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:x};if(t.lan)if(dd(t.lan)==="off")a.https=!1;else{let l=F(e,t.lan,o);K(l,a.onDemandTls);let s=t.lan.ip&&L(t.lan.ip)!==0?[t.lan.ip]:[];a.localCa={dir:A,hosts:l.map((w)=>w.host),...s.length>0?{ips:s}:{},installTrust:!0}}return a}function B(e,t){return N({...e,...t.mail?dn(t.mail):{}},t)}function tr(e,t,r){return N({...e,...r.mail?dn(r.mail):{}},r,t)}function PI(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
2
2
  // Routes are derived from the \`sites\` model on every \`buddy deploy\`.
3
3
  import { startProxies } from '@stacksjs/rpx'
4
4
 
@@ -7,7 +7,7 @@ const config = ${D(e)} as const
7
7
  // Verbose is the hard default for ts-cloud-installed gateways (RPX_VERBOSE=false
8
8
  // opts out) — without it rpx's TLS/routing diagnostics never reach the journal.
9
9
  await startProxies({ verbose: process.env.RPX_VERBOSE !== 'false', ...config } as any)
10
- `}function j(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var fo="/etc/rpx",R="/opt/rpx-gateway",Cp="/etc/rpx/gateway.ts",bt="/etc/rpx/gateway",ze="rpx-gateway.service",z="/etc/rpx/sites.d";function J(e=z,t=uo){return`// Generated by ts-cloud — rpx gateway assembler.
10
+ `}function j(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var fo="/etc/rpx",R="/opt/rpx-gateway",Ep="/etc/rpx/gateway.ts",bt="/etc/rpx/gateway",ze="rpx-gateway.service",z="/etc/rpx/sites.d";function J(e=z,t=uo){return`// Generated by ts-cloud — rpx gateway assembler.
11
11
  // Merges every app's fragment in ${e} so independent deploys compose
12
12
  // without clobbering each other. Each deploy writes only its own <slug>.json.
13
13
  import { startProxies } from '@stacksjs/rpx'
@@ -133,6 +133,6 @@ writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode:
133
133
  `.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${n.bunBin} -e ${q(o)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Q={high:"256M",max:"384M"},Z={high:"512M",max:"768M"};function ud(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function gd(e){let t=new Set;for(let r of e.proxies){let n=r.to;if(!n||n.startsWith("*")||n.includes(":")||!n.includes("."))continue;t.add(n)}return[...t]}function ee(e){if(e.length===0)return[];let t=["# Wildcards: dns-01 (Porkbun), keys read from the site's env file for tlsx alone.","dns_env() {",' [ -r "$1" ] || return 0',` sed -n "s/^$2=//p" "$1" | tail -n 1 | sed -e 's/^"\\(.*\\)"$/\\1/' -e "s/^'\\(.*\\)'$/\\1/"`,"}","wildcard() {",' apex="$1"',' envfile="$2"',' name="*.$apex"',' key=$(dns_env "$envfile" PORKBUN_API_KEY)',' secret=$(dns_env "$envfile" PORKBUN_SECRET_KEY)',' if [ -z "$key" ] || [ -z "$secret" ]; then',' echo "wildcard $name skipped: no PORKBUN_API_KEY / PORKBUN_SECRET_KEY in $envfile (non-fatal)"'," return 0"," fi",' if [ ! -s "$CERTS/_wildcard.$apex.crt" ]; then',' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:issue -d "$name" --method dns-01 --dns-provider porkbun --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $name failed (non-fatal)"'," else",' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:renew --domains "$name" --method dns-01 --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew $name failed (non-fatal)"'," fi","}"];for(let r of e){let n=r.domain.replace(/^\*\./,"");t.push(`wildcard '${n}' '${r.dnsEnvFile.replace(/'/g,"")}'`)}return t}function P(e){let{config:t,proxy:r}=e,n=t.acmeChallengeWebroot,o=gd(t);if(!r.onDemandTls||!n||o.length===0)return[];let u=e.bunBin??"/usr/local/bin/bun",i=r.tlsxVersion??"latest",c=t.productionCerts.certsDir,f=r.onDemandTlsEmail??`webmaster@${o[0]}`,g=`${u} ${R}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,a=o.join(","),p=o.join(" "),x=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),l=`${fo}/renew-certs-${x}.sh`,s=ud(x),w=`rpx-cert-renew-${x}.timer`,v=t.wildcardCerts??[],E=v.length>0?"tlsx http-01 + dns-01 wildcard":"tlsx http-01",b=["#!/bin/sh",`# Generated by ts-cloud — issue/renew rpx gateway TLS certs via ${E}.`,"# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${c}'`,`WEBROOT='${n}'`,`EMAIL='${f}'`,`TLSX="${g}"`,`BUN='${u}'`,`DOMAINS='${a}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${k.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${p}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${ze}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"',...ee(v),'rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${ze}`].join(`
134
134
  `),C=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${x} (${E})`,`After=network-online.target ${ze}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${l}`].join(`
135
135
  `),S=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${x}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
136
- `);return[`mkdir -p ${n}`,...e.tenant?[]:[`(cd ${R} && ${u} add @stacksjs/tlsx@${i}) || true`],..._(l,b,"TS_CLOUD_RENEW_EOF"),`chmod +x ${l}`,..._(`/etc/systemd/system/${s}`,C,"TS_CLOUD_RENEW_SVC_EOF"),..._(`/etc/systemd/system/${w}`,S,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${w} || true`,`${l} || true`]}function G(e){let{config:t,proxy:r}=e,n=e.bunBin??"/usr/local/bin/bun",o=r.version??"latest",u=t.productionCerts.certsDir,i=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),c=D(t,{slug:i}),f=J(z,u);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${bt} ] || [ ! -d ${R}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${z} ${u}`,`__tsc_rpx_before="$(sha256sum ${z}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...T(`${z}/${i}.json`,c,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${z}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${ze}; then`,` systemctl restart ${ze}`,"else",` echo "[ts-cloud] rpx routes for ${i} unchanged - leaving the shared gateway alone"`,"fi",...P(e)];let a=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")a.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let p=e.profile==="raspberry-pi"?Q:Z,x=r.memoryHigh??p.high,l=r.memoryMax??p.max;return["set -euo pipefail",`mkdir -p ${fo} ${z} ${u} ${R}`,`rm -rf ${R}.next ${R}.prev`,`mkdir -p ${R}.next`,`(cd ${R}.next && ${n} add @stacksjs/rpx@${o})`,`mv ${R} ${R}.prev`,`mv ${R}.next ${R}`,`rm -rf ${R}.prev`,`ln -sfn ${R}/node_modules ${fo}/node_modules`,...T(`${z}/${i}.json`,c,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),..._(Cp,f,"TS_CLOUD_RPX_EOF"),`${n} build --production --compile --outfile ${bt}.next ${Cp}`,`chmod 0755 ${bt}.next`,`mv -f ${bt}.next ${bt}`,..._(`/etc/systemd/system/${ze}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${bt}`,`WorkingDirectory=${R}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...a,"MemoryAccounting=true",`MemoryHigh=${x}`,`MemoryMax=${l}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
136
+ `);return[`mkdir -p ${n}`,...e.tenant?[]:[`(cd ${R} && ${u} add @stacksjs/tlsx@${i}) || true`],..._(l,b,"TS_CLOUD_RENEW_EOF"),`chmod +x ${l}`,..._(`/etc/systemd/system/${s}`,C,"TS_CLOUD_RENEW_SVC_EOF"),..._(`/etc/systemd/system/${w}`,S,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${w} || true`,`${l} || true`]}function G(e){let{config:t,proxy:r}=e,n=e.bunBin??"/usr/local/bin/bun",o=r.version??"latest",u=t.productionCerts.certsDir,i=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),c=D(t,{slug:i}),f=J(z,u);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${bt} ] || [ ! -d ${R}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${z} ${u}`,`__tsc_rpx_before="$(sha256sum ${z}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...T(`${z}/${i}.json`,c,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${z}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${ze}; then`,` systemctl restart ${ze}`,"else",` echo "[ts-cloud] rpx routes for ${i} unchanged - leaving the shared gateway alone"`,"fi",...P(e)];let a=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")a.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let p=e.profile==="raspberry-pi"?Q:Z,x=r.memoryHigh??p.high,l=r.memoryMax??p.max;return["set -euo pipefail",`mkdir -p ${fo} ${z} ${u} ${R}`,`rm -rf ${R}.next ${R}.prev`,`mkdir -p ${R}.next`,`(cd ${R}.next && ${n} add @stacksjs/rpx@${o})`,`mv ${R} ${R}.prev`,`mv ${R}.next ${R}`,`rm -rf ${R}.prev`,`ln -sfn ${R}/node_modules ${fo}/node_modules`,...T(`${z}/${i}.json`,c,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),..._(Ep,f,"TS_CLOUD_RPX_EOF"),`${n} build --production --compile --outfile ${bt}.next ${Ep}`,`chmod 0755 ${bt}.next`,`mv -f ${bt}.next ${bt}`,..._(`/etc/systemd/system/${ze}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${bt}`,`WorkingDirectory=${R}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...a,"MemoryAccounting=true",`MemoryHigh=${x}`,`MemoryMax=${l}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
137
137
  `),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${z}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${fo}/renew-certs-$tenant.sh"; done`,`systemctl enable ${ze}`,`systemctl restart ${ze}`,...P(e)]}function Ne(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=D(e.config,{slug:t});return["set -euo pipefail",`mkdir -p ${z}`,...T(`${z}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${ze}`]}
138
- export{uo,go,po,mo,dd,Ip,bp,Yh,ld,B,tr,DI,j,fo,R,Cp,bt,ze,z,ud,gd,G,Ne};
138
+ export{uo,go,po,mo,dd,bp,Cp,Zh,ld,B,tr,PI,j,fo,R,Ep,bt,ze,z,ud,gd,G,Ne};
@@ -1,4 +1,4 @@
1
- import{d}from"./chunk-8jqv6wh7.js";var Et="/etc/rpx/sites.d",vA={start:3000,end:3999};function g(t){return t.slug?.trim()||"app"}function hd(t){let r=t.lastIndexOf(":");if(r<0||r===t.length-1)return;let e=t.slice(r+1).trim();if(!/^\d+$/.test(e))return;let n=Number(e);return n>=1&&n<=65535?n:void 0}function xi(t,r={}){let e=r.ignoreSlug?.trim(),n=new Map;for(let o of t){let c=g(o);if(e&&c===e)continue;for(let a of o.proxies??[]){let f=typeof a.from==="string"?[a.from]:a.from??[];for(let i of f){let u=hd(i);if(u!==void 0&&!n.has(u))n.set(u,c)}}}return n}function Oi(t=Et){return[`for __tsc_fragment in ${t}/*.json; do`,' [ -f "$__tsc_fragment" ] || continue',` base64 < "$__tsc_fragment" | tr -d '\\n'`," printf '\\n'","done"].join(`
1
+ import{d}from"./chunk-0860mm00.js";var Et="/etc/rpx/sites.d",TA={start:3000,end:3999};function g(t){return t.slug?.trim()||"app"}function hd(t){let r=t.lastIndexOf(":");if(r<0||r===t.length-1)return;let e=t.slice(r+1).trim();if(!/^\d+$/.test(e))return;let n=Number(e);return n>=1&&n<=65535?n:void 0}function xi(t,r={}){let e=r.ignoreSlug?.trim(),n=new Map;for(let o of t){let c=g(o);if(e&&c===e)continue;for(let a of o.proxies??[]){let f=typeof a.from==="string"?[a.from]:a.from??[];for(let i of f){let u=hd(i);if(u!==void 0&&!n.has(u))n.set(u,c)}}}return n}function Oi(t=Et){return[`for __tsc_fragment in ${t}/*.json; do`,' [ -f "$__tsc_fragment" ] || continue',` base64 < "$__tsc_fragment" | tr -d '\\n'`," printf '\\n'","done"].join(`
2
2
  `)}function _i(t){let r=[];for(let e of t.split(`
3
- `)){let n=e.trim();if(!n)continue;try{let o=JSON.parse(Buffer.from(n,"base64").toString("utf8"));if(o&&typeof o==="object"&&!Array.isArray(o))r.push(o)}catch{continue}}return r}function Vp(t,r,e=vA){let n=[],o=[],c=new Set(r.keys());for(let[a,f]of Object.entries(t.sites??{})){if(!f||d(f)!=="server-app")continue;let i=typeof f.port==="number"?f.port:void 0,u=Math.max(i??e.start,e.start),p;for(let s=u;s<=e.end;s++)if(!c.has(s)){p=s;break}if(p===void 0){let s=i!==void 0?r.get(i):void 0;o.push(`No free port for site '${a}' in ${e.start}-${e.end}${i!==void 0?` (wanted ${i}${s?`, held by '${s}'`:""})`:""}. Widen the range or free a port on the box.`);continue}c.add(p),n.push({site:a,port:p,declared:i,moved:i!==void 0&&p!==i})}return{allocations:n,errors:o}}
4
- export{Et,vA,hd,xi,Oi,_i,Vp};
3
+ `)){let n=e.trim();if(!n)continue;try{let o=JSON.parse(Buffer.from(n,"base64").toString("utf8"));if(o&&typeof o==="object"&&!Array.isArray(o))r.push(o)}catch{continue}}return r}function qp(t,r,e=TA){let n=[],o=[],c=new Set(r.keys());for(let[a,f]of Object.entries(t.sites??{})){if(!f||d(f)!=="server-app")continue;let i=typeof f.port==="number"?f.port:void 0,u=Math.max(i??e.start,e.start),p;for(let s=u;s<=e.end;s++)if(!c.has(s)){p=s;break}if(p===void 0){let s=i!==void 0?r.get(i):void 0;o.push(`No free port for site '${a}' in ${e.start}-${e.end}${i!==void 0?` (wanted ${i}${s?`, held by '${s}'`:""})`:""}. Widen the range or free a port on the box.`);continue}c.add(p),n.push({site:a,port:p,declared:i,moved:i!==void 0&&p!==i})}return{allocations:n,errors:o}}
4
+ export{Et,TA,hd,xi,Oi,_i,qp};
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-et77ydjb.js";import{b}from"./chunk-n3sydv3m.js";var pt=new Set(["A","AAAA","CNAME"]);function V(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function E(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,i=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,i))}class he{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let i,o=new AbortController,a=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{i=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(d){if(r=d,s===8)throw d;await E(s);continue}finally{clearTimeout(a)}if(!i.ok){let d=await i.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${i.status} ${i.statusText}${d?`: ${d}`:""}`),!V(i.status)||s===8)throw r;await E(s,i);continue}let c=await i.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!V(0,c.message)||s===8)throw r;await E(s,i);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!he.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${i.message??"unknown provider error"}`];let o=[];for(let a of i.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)o.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return!0;return i.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===s&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)i.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,i);if(he.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(i.success){let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(o?.id&&o.content===t.content&&(t.ttl===void 0||o.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||o.priority===t.priority))return{success:!0,id:o.id,message:"Record already up to date"};if(o?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,a),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return{success:!1,message:"Failed to list records"};let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class Ge{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,i={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let a=await fetch(s,o);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),i={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)i.priority=e.priority;return i}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),o=i.filter((a)=>a.data!==t.content);if(o.length===i.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var Pg=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],U=[{name:"x-stx-router",value:"true"}];function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Z(e){return`{${e.map(C).join(" ")}}`}function j(e){let t=`http.request.headers[${C(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${C(e.value)})`}function qt(e){if(e.length===1)return`http.host eq ${C(e[0])}`;return`http.host in ${Z(e)}`}function Pc(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=qt(e),s=[],o=(t.bypassPaths??[]).map((v)=>`starts_with(http.request.uri.path, ${C(v)})`),c=(t.negotiatedRequestHeaders??U).map(j),d=[...o,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let g=u?`${r} and not ${u}`:r,m=t.assetExtensions??Pg,p=m.length>0?`lower(http.request.uri.path.extension) in ${Z([...m])}`:void 0;if(p)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${p})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let y=p?`(${g} and not ${p})`:`(${g})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:y,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function kc(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${qt(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var F="https://api.cloudflare.com/client/v4",jt="[ts-cloud]";class H{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${F}${t}`,i={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let c=await(await fetch(s,o)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let i=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!i.result||i.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=i.result[0].id;return this.zoneCache.set(r,o),{id:o,name:i.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},i=r??e.proxied;if(i!==void 0&&pt.has(e.type)){if(s.proxied=i,i)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let o=W(e);if(o)s.data=o,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??o?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let a=o.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let i=[],o=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${o}`);if(i.push(...c.result||[]),c.result_info)a=o<c.result_info.total_pages,o++;else a=!1}return{success:!0,records:i.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let i=await this.getZoneDetails(r);if(i)return{...i,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(o){let a=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(a))throw o;let c=await this.getZoneDetails(r);if(!c)throw o;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let i of r.result||[]){if(i.status!=="active")continue;for(let o of i.hosts||[])s.add(o.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(o.result&&o.result.length>0)return o.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),i=s.id,o=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${i}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${i}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let i of r.result||[])s[i.id]=i.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),i=[],o=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&_(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),i.push({id:a,from:d,to:c})}catch(u){o.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:i,failed:o}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let i of r.result?.managed_request_headers||[])s[i.id]=i.enabled===!0;return s}async applyTieredCache(e,t){let r=[],s=[],i=await this.getZoneId(e),o=[["tiered_caching",`/zones/${i}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${i}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")o.reverse();for(let[a,c,d]of o)try{let g=(await this.request("GET",c)).result?.value;if(g===d)continue;await this.request("PATCH",c,{value:d}),r.push({id:a,from:g,to:d})}catch(u){s.push({id:a,error:u instanceof Error?u.message:String(u)})}return{changed:r,failed:s}}async applyManagedRequestHeaders(e,t){let r=[],s=[],i=Object.entries(t).filter(([,d])=>d!==void 0);if(i.length===0)return{changed:r,failed:s};let o=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of i)s.push({id:g,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of i){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${o}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of c)s.push({id:g,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),i=await this.getPhaseRules(e,t),o=r.map((d)=>({...d,description:d.description?.startsWith(jt)?d.description:`${jt} ${d.description||t}`})),c=K(i,o).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var x=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function zn(e){return x.test(e)?e.replace(x,"\x00hosts\x00"):null}function O(e,t){return e.replace(x,qt(t))}function P(e){if(Array.isArray(e))return`[${e.map(P).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${P(s)}`).join(",")}}`;return JSON.stringify(e)}function G(e,t){let r=zn(e.expression);return r!==null&&r===zn(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&P(e.action_parameters)===P(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((o)=>zt(o.expression))),s=(o)=>(o.description||"").startsWith(jt),i=[];for(let o of e){if(!s(o)){i.push(o);continue}let a=zt(o.expression);if(a.length===0){if(r.size>0)i.push(o);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)i.push(o);else if(c.length>0)i.push({...o,expression:O(o.expression,c)})}for(let o of t){let a=zt(o.expression),c=a.length>0?i.findIndex((g)=>s(g)&&G(g,o)):-1;if(c===-1){i.push(o);continue}let d=i[c],u=[...new Set([...zt(d.expression),...a])];i[c]={...d,expression:O(d.expression,u)}}return i}function zt(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function _(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((i,o)=>_(i,t[o]))}let r=e,s=t;return Object.keys(s).every((i)=>_(r[i],s[i]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:M(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,i,o]=r.slice(0,3).map(Number);if(![s,i,o].every(Number.isFinite))return null;return{priority:s,weight:i,port:o,target:M(r.slice(3).join(" "))}}function M(e){return e.replace(/\.$/,"")}var B=new Set(["A","AAAA","CNAME","ALIAS"]);function Kt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function Kn(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let i=w(s);if(i===r||i.endsWith(`.${r}`))return i;return`${i}.${r}`}function Us(e,t){return e.map((r)=>({...r,name:Kn(r.name,t),proxied:r.proxied??!1}))}function X(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(B.has(t.type))return!0;if(t.type==="TXT"){let r=Kt(t.content);if(r)return Kt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Y(e,t){if(R(e.content)!==R(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Qs(e){let{provider:t,zone:r,records:s}=e,i={outcomes:[],warnings:[]};if(s.length===0)return i;let o=await t.listRecords(r);if(!o.success)return i.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),i;let a=o.records;for(let c of s){let d=a.filter((p)=>X(p,c));if(d.length>0&&d.every((p)=>Y(p,c))){i.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},g=c.type==="TXT"&&Kt(c.content)!==void 0;if(g)for(let p of d){let y=await t.deleteRecord(r,{name:p.name,type:p.type,content:p.content});if(!y.success)i.warnings.push(`could not remove superseded ${p.type} at ${p.name}: ${y.message||"unknown error"}`)}let m=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)i.outcomes.push({record:c,action:d.length>0?"updated":"created"});else i.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let g=new Set(s.filter((p)=>p.type===c&&w(p.name)===u).map((p)=>R(p.content).toLowerCase())),m=a.filter((p)=>p.type===c&&w(p.name)===u&&!g.has(R(p.content).toLowerCase()));for(let p of m)i.warnings.push(`${u} has an undeclared ${c} record (${p.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return i}function Pr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function kr(e){return Boolean(e&&typeof e.createZone==="function")}var J=new Set(["NS"]);function D(e){return e.replace(/\.$/,"").toLowerCase()}function Wn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(D)),s=new Set(t.map(D));if(r.size!==s.size)return!1;for(let i of r)if(!s.has(i))return!1;return!0}function Q(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:D(r)}var ee=new Set(["MX","SRV"]),te=new Set(["A","AAAA","CNAME"]);function S(e){let t=ee.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${D(e.name)}|${Q(e)}|${t}`}function re(e,t){return S(e)===S(t)}async function Nr(e){let{domain:t,registrar:r,host:s,dryRun:i=!1}=e,o=new Set([...e.proxiedHosts??[]].map(D)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(Wn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let g=await r.listRecords(t);if(!g.success)return a.push(`Could not read ${t} from ${r.name}: ${g.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of g.records){if(J.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=pt.has(l.type)&&o.has(D(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...pt.has(l.type)?{proxied:f}:{}})}if(i){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let p=new Map;for(let l of m){let f=`${l.type}|${D(l.name)}`;p.set(f,(p.get(f)??0)+1)}let y=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])y.add(S(f))}catch{}for(let l of m){let f=te.has(l.type)&&p.get(`${l.type}|${D(l.name)}`)===1;if(!f&&y.has(S(l))){u.records.push({record:l,status:"present"});continue}let A;try{A=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(I){A={success:!1,message:I instanceof Error?I.message:String(I)}}if(A.success)y.add(S(l));u.records.push(A.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:A.message})}let v=await s.listRecords(t);if(!v.success)return a.push(`Could not read back ${t} from ${s.name}: ${v.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!v.records.some((f)=>re(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ne={add_visitor_location_headers:"visitorLocationHeaders"};function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function se(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new he(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new Ge(t.godaddyApiKey,t.godaddyApiSecret);if(!Pr(r))return"the GoDaddy provider cannot change nameservers";return r}async function Hs(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=se(r.provider,s);if(typeof i==="string")return{status:"skipped",reason:i};let o=new H(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!kr(o))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return Nr({domain:e.domain,registrar:i,host:o,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function Gs(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function oe(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function ae(e){let t={};for(let[r,s]of Object.entries(ne)){let i=e[s];if(typeof i==="boolean")t[r]=i}return t}async function Vs(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=oe(e.zone),s=ae(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0&&!e.zone.tieredCache)return{status:"skipped",reason:"dns.zone declares no settings"};let i=t.credentials??z(t.env??process.env);if(!i.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=new H(i.cloudflareApiToken,{accountId:i.cloudflareAccountId}),a=await o.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await o.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=e.zone.tieredCache?await o.applyTieredCache(e.domain,e.zone.tieredCache):{changed:[],failed:[]},u=[...a.changed,...c.changed,...d.changed],g=[...a.failed,...c.failed,...d.failed];return{status:u.length>0?"applied":"unchanged",domain:e.domain,changed:u,failed:g}}function qs(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class ie{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new b(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let i=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,i),i}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ce(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?k(t)===k(r):t===r}async currentSet(e,t,r){let i=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!i||i.Name.toLowerCase()!==t.toLowerCase()||i.Type!==r||i.AliasTarget||i.SetIdentifier)return null;return{ttl:i.TTL??300,values:(i.ResourceRecords??[]).map((o)=>o.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(o?.values.some((d)=>this.sameValue(t.type,d,i)))return{success:!0,message:"Record already present"};let a=[...o?.values??[],i];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:o?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:i}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(!o||!o.values.some((c)=>this.sameValue(t.type,c,i)))return{success:!0,message:"Record already absent"};let a=o.values.filter((c)=>!this.sameValue(t.type,c,i));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o.ttl,ResourceRecords:(a.length>0?a:o.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),i=[];for(let o of s.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let a of o.ResourceRecords||[]){let c=a.Value,d;if(o.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(o.Type==="TXT"&&c.startsWith('"'))c=k(c);i.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:c,ttl:o.TTL,priority:d})}}return{success:!0,records:i}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:b.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=b.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var q=255;function ce(e){let t=[];for(let r=0;r<e.length;r+=q)t.push(e.slice(r,r+q));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function k(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(!r){if(i==='"')r=!0;continue}if(i==="\\"&&s+1<e.length){t+=e[++s];continue}if(i==='"'){r=!1;continue}t+=i}return t}async function js(e,t){let r=[],s,i;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:i,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(s=o.NextRecordName,i=o.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function T(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function de(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function zs(e,t){let r=h(t),s=[],i=[],o=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){i.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){i.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let g=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)o.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of c.ResourceRecords||[]){let m=ue(d,u,g.Value,c.TTL);if("reason"in m){i.push({name:d,type:u,reason:m.reason}),o.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:i,warnings:o}}function ue(e,t,r,s){let i={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...i,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...i,type:"TXT",content:de(r)};case"MX":{let[o,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...i,type:"MX",content:h(a.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=o.slice(0,3).map(Number);return{...i,type:"SRV",content:h(o.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...i,type:"NS",content:h(r)};case"CAA":return{...i,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var le=new Set(["TXT","MX","SRV","NS","CAA"]);async function Ks(e,t){let r=[],s=[],i=new Set;try{let o=await e.listRecords(t.zone);for(let a of o.records||[])i.add(`${h(a.name)}|${a.type}|${T(a)}`)}catch{}for(let o of t.records){let a={...o,proxied:!1},c=`${h(o.name)}|${o.type}|${T(o)}`;if(!le.has(o.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(o);else s.push({record:o,message:u.message||"unknown provider error"});continue}if(i.has(c)){r.push(o);continue}let d=await e.createRecord(t.zone,a);if(d.success)i.add(c),r.push(o);else s.push({record:o,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function Ws(e,t){let r=await e.listRecords(t.zone),s=[],i=[],o=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=o.get(c)??[];d.push(T(a)),o.set(c,d)}for(let a of t.records){let c=o.get(`${h(a.name)}|${a.type}`),d=T(a);if(c?.some((u)=>u===d))s.push(a);else i.push({record:a,found:c?.join(", ")})}return{matched:s,missing:i,ok:i.length===0}}class Ae{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ye(t),"provider"in e)this.dnsProvider=N(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:i=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let a=await this.acm.getDnsValidationRecords(o);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(o,i*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,records:i.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!a.success)s.push(`Failed to delete record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:i}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let a=o.SubjectAlternativeNames||[o.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:i})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:i=[],waitForValidation:o=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...i),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function Js(e,t,r){return new Ae({provider:"porkbun",apiKey:e,secretKey:t},r)}function Xs(e,t,r,s){return new Ae({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function Ys(e,t,r){return new Ae({provider:"route53",region:e,hostedZoneId:t},r||e)}function N(e){switch(e.provider){case"route53":return new ie(e.region,e.hostedZoneId);case"porkbun":return new he(e.apiKey,e.secretKey);case"godaddy":return new Ge(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new H(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Nc(e,t){for(let r of t){let s=N(r);if(await s.canManageDomain(e))return s}return null}class Jn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,o)}let i=process.env.CLOUDFLARE_API_TOKEN;if(i)this.addCloudflare(i,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((i)=>i.provider===e);if(!r)return null;let s=N(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=N(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>N(e))}}var Bc=new Jn;class ye{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let i=await this.describeCertificate({CertificateArn:e});if(i.Status==="ISSUED")return i;if(i.Status==="FAILED"||i.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),i=t.split("."),o=s.split(".");if(i.slice(-o.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let i=s.slice(2),o=t.split("."),a=i.split(".");if(o.slice(-a.length).join(".")===i)return!0}}return!1}}class Br{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ye(e),this.route53=new b,t&&t.provider!=="route53")this.dnsProvider=N(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:i=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(i){if(!await this.acm.waitForCertificateValidation(a,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let a=s||i[0]?.domainName;for(let c of i){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});o.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of i){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});o.push({...a,changeId:c.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,i=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=s||i[0]?.domainName;for(let a of i)try{await this.dnsProvider.deleteRecord(o,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let o of i)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
1
+ import{n}from"./chunk-9w5ncn9s.js";import{b}from"./chunk-q8vvwmka.js";var pt=new Set(["A","AAAA","CNAME"]);function V(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function E(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,i=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,i))}class he{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let i,o=new AbortController,a=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{i=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(d){if(r=d,s===8)throw d;await E(s);continue}finally{clearTimeout(a)}if(!i.ok){let d=await i.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${i.status} ${i.statusText}${d?`: ${d}`:""}`),!V(i.status)||s===8)throw r;await E(s,i);continue}let c=await i.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!V(0,c.message)||s===8)throw r;await E(s,i);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!he.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${i.message??"unknown provider error"}`];let o=[];for(let a of i.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)o.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return!0;return i.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===s&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)i.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,i);if(he.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(i.success){let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(o?.id&&o.content===t.content&&(t.ttl===void 0||o.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||o.priority===t.priority))return{success:!0,id:o.id,message:"Record already up to date"};if(o?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,a),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return{success:!1,message:"Failed to list records"};let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class Ge{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,i={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let a=await fetch(s,o);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),i={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)i.priority=e.priority;return i}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),o=i.filter((a)=>a.data!==t.content);if(o.length===i.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var Pg=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],U=[{name:"x-stx-router",value:"true"}];function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Z(e){return`{${e.map(C).join(" ")}}`}function j(e){let t=`http.request.headers[${C(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${C(e.value)})`}function qt(e){if(e.length===1)return`http.host eq ${C(e[0])}`;return`http.host in ${Z(e)}`}function Pc(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=qt(e),s=[],o=(t.bypassPaths??[]).map((v)=>`starts_with(http.request.uri.path, ${C(v)})`),c=(t.negotiatedRequestHeaders??U).map(j),d=[...o,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let g=u?`${r} and not ${u}`:r,m=t.assetExtensions??Pg,p=m.length>0?`lower(http.request.uri.path.extension) in ${Z([...m])}`:void 0;if(p)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${p})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let y=p?`(${g} and not ${p})`:`(${g})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:y,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function kc(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${qt(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var F="https://api.cloudflare.com/client/v4",jt="[ts-cloud]";class H{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${F}${t}`,i={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let c=await(await fetch(s,o)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let i=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!i.result||i.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=i.result[0].id;return this.zoneCache.set(r,o),{id:o,name:i.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},i=r??e.proxied;if(i!==void 0&&pt.has(e.type)){if(s.proxied=i,i)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let o=W(e);if(o)s.data=o,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??o?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let a=o.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let i=[],o=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${o}`);if(i.push(...c.result||[]),c.result_info)a=o<c.result_info.total_pages,o++;else a=!1}return{success:!0,records:i.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let i=await this.getZoneDetails(r);if(i)return{...i,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(o){let a=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(a))throw o;let c=await this.getZoneDetails(r);if(!c)throw o;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let i of r.result||[]){if(i.status!=="active")continue;for(let o of i.hosts||[])s.add(o.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(o.result&&o.result.length>0)return o.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),i=s.id,o=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${i}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${i}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let i of r.result||[])s[i.id]=i.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),i=[],o=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&_(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),i.push({id:a,from:d,to:c})}catch(u){o.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:i,failed:o}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let i of r.result?.managed_request_headers||[])s[i.id]=i.enabled===!0;return s}async applyTieredCache(e,t){let r=[],s=[],i=await this.getZoneId(e),o=[["tiered_caching",`/zones/${i}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${i}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")o.reverse();for(let[a,c,d]of o)try{let g=(await this.request("GET",c)).result?.value;if(g===d)continue;await this.request("PATCH",c,{value:d}),r.push({id:a,from:g,to:d})}catch(u){s.push({id:a,error:u instanceof Error?u.message:String(u)})}return{changed:r,failed:s}}async applyManagedRequestHeaders(e,t){let r=[],s=[],i=Object.entries(t).filter(([,d])=>d!==void 0);if(i.length===0)return{changed:r,failed:s};let o=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of i)s.push({id:g,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of i){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${o}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of c)s.push({id:g,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),i=await this.getPhaseRules(e,t),o=r.map((d)=>({...d,description:d.description?.startsWith(jt)?d.description:`${jt} ${d.description||t}`})),c=K(i,o).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var x=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function zn(e){return x.test(e)?e.replace(x,"\x00hosts\x00"):null}function O(e,t){return e.replace(x,qt(t))}function P(e){if(Array.isArray(e))return`[${e.map(P).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${P(s)}`).join(",")}}`;return JSON.stringify(e)}function G(e,t){let r=zn(e.expression);return r!==null&&r===zn(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&P(e.action_parameters)===P(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((o)=>zt(o.expression))),s=(o)=>(o.description||"").startsWith(jt),i=[];for(let o of e){if(!s(o)){i.push(o);continue}let a=zt(o.expression);if(a.length===0){if(r.size>0)i.push(o);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)i.push(o);else if(c.length>0)i.push({...o,expression:O(o.expression,c)})}for(let o of t){let a=zt(o.expression),c=a.length>0?i.findIndex((g)=>s(g)&&G(g,o)):-1;if(c===-1){i.push(o);continue}let d=i[c],u=[...new Set([...zt(d.expression),...a])];i[c]={...d,expression:O(d.expression,u)}}return i}function zt(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function _(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((i,o)=>_(i,t[o]))}let r=e,s=t;return Object.keys(s).every((i)=>_(r[i],s[i]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:M(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,i,o]=r.slice(0,3).map(Number);if(![s,i,o].every(Number.isFinite))return null;return{priority:s,weight:i,port:o,target:M(r.slice(3).join(" "))}}function M(e){return e.replace(/\.$/,"")}var B=new Set(["A","AAAA","CNAME","ALIAS"]);function Kt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function Kn(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let i=w(s);if(i===r||i.endsWith(`.${r}`))return i;return`${i}.${r}`}function Us(e,t){return e.map((r)=>({...r,name:Kn(r.name,t),proxied:r.proxied??!1}))}function X(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(B.has(t.type))return!0;if(t.type==="TXT"){let r=Kt(t.content);if(r)return Kt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Y(e,t){if(R(e.content)!==R(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Qs(e){let{provider:t,zone:r,records:s}=e,i={outcomes:[],warnings:[]};if(s.length===0)return i;let o=await t.listRecords(r);if(!o.success)return i.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),i;let a=o.records;for(let c of s){let d=a.filter((p)=>X(p,c));if(d.length>0&&d.every((p)=>Y(p,c))){i.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},g=c.type==="TXT"&&Kt(c.content)!==void 0;if(g)for(let p of d){let y=await t.deleteRecord(r,{name:p.name,type:p.type,content:p.content});if(!y.success)i.warnings.push(`could not remove superseded ${p.type} at ${p.name}: ${y.message||"unknown error"}`)}let m=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)i.outcomes.push({record:c,action:d.length>0?"updated":"created"});else i.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let g=new Set(s.filter((p)=>p.type===c&&w(p.name)===u).map((p)=>R(p.content).toLowerCase())),m=a.filter((p)=>p.type===c&&w(p.name)===u&&!g.has(R(p.content).toLowerCase()));for(let p of m)i.warnings.push(`${u} has an undeclared ${c} record (${p.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return i}function Pr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function kr(e){return Boolean(e&&typeof e.createZone==="function")}var J=new Set(["NS"]);function D(e){return e.replace(/\.$/,"").toLowerCase()}function Wn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(D)),s=new Set(t.map(D));if(r.size!==s.size)return!1;for(let i of r)if(!s.has(i))return!1;return!0}function Q(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:D(r)}var ee=new Set(["MX","SRV"]),te=new Set(["A","AAAA","CNAME"]);function S(e){let t=ee.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${D(e.name)}|${Q(e)}|${t}`}function re(e,t){return S(e)===S(t)}async function Nr(e){let{domain:t,registrar:r,host:s,dryRun:i=!1}=e,o=new Set([...e.proxiedHosts??[]].map(D)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(Wn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let g=await r.listRecords(t);if(!g.success)return a.push(`Could not read ${t} from ${r.name}: ${g.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of g.records){if(J.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=pt.has(l.type)&&o.has(D(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...pt.has(l.type)?{proxied:f}:{}})}if(i){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let p=new Map;for(let l of m){let f=`${l.type}|${D(l.name)}`;p.set(f,(p.get(f)??0)+1)}let y=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])y.add(S(f))}catch{}for(let l of m){let f=te.has(l.type)&&p.get(`${l.type}|${D(l.name)}`)===1;if(!f&&y.has(S(l))){u.records.push({record:l,status:"present"});continue}let A;try{A=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(I){A={success:!1,message:I instanceof Error?I.message:String(I)}}if(A.success)y.add(S(l));u.records.push(A.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:A.message})}let v=await s.listRecords(t);if(!v.success)return a.push(`Could not read back ${t} from ${s.name}: ${v.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!v.records.some((f)=>re(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ne={add_visitor_location_headers:"visitorLocationHeaders"};function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function se(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new he(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new Ge(t.godaddyApiKey,t.godaddyApiSecret);if(!Pr(r))return"the GoDaddy provider cannot change nameservers";return r}async function Hs(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=se(r.provider,s);if(typeof i==="string")return{status:"skipped",reason:i};let o=new H(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!kr(o))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return Nr({domain:e.domain,registrar:i,host:o,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function Gs(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function oe(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function ae(e){let t={};for(let[r,s]of Object.entries(ne)){let i=e[s];if(typeof i==="boolean")t[r]=i}return t}async function Vs(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=oe(e.zone),s=ae(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0&&!e.zone.tieredCache)return{status:"skipped",reason:"dns.zone declares no settings"};let i=t.credentials??z(t.env??process.env);if(!i.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=new H(i.cloudflareApiToken,{accountId:i.cloudflareAccountId}),a=await o.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await o.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=e.zone.tieredCache?await o.applyTieredCache(e.domain,e.zone.tieredCache):{changed:[],failed:[]},u=[...a.changed,...c.changed,...d.changed],g=[...a.failed,...c.failed,...d.failed];return{status:u.length>0?"applied":"unchanged",domain:e.domain,changed:u,failed:g}}function qs(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class ie{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new b(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let i=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,i),i}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ce(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?k(t)===k(r):t===r}async currentSet(e,t,r){let i=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!i||i.Name.toLowerCase()!==t.toLowerCase()||i.Type!==r||i.AliasTarget||i.SetIdentifier)return null;return{ttl:i.TTL??300,values:(i.ResourceRecords??[]).map((o)=>o.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(o?.values.some((d)=>this.sameValue(t.type,d,i)))return{success:!0,message:"Record already present"};let a=[...o?.values??[],i];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:o?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:i}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(!o||!o.values.some((c)=>this.sameValue(t.type,c,i)))return{success:!0,message:"Record already absent"};let a=o.values.filter((c)=>!this.sameValue(t.type,c,i));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o.ttl,ResourceRecords:(a.length>0?a:o.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),i=[];for(let o of s.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let a of o.ResourceRecords||[]){let c=a.Value,d;if(o.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(o.Type==="TXT"&&c.startsWith('"'))c=k(c);i.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:c,ttl:o.TTL,priority:d})}}return{success:!0,records:i}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:b.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=b.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var q=255;function ce(e){let t=[];for(let r=0;r<e.length;r+=q)t.push(e.slice(r,r+q));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function k(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(!r){if(i==='"')r=!0;continue}if(i==="\\"&&s+1<e.length){t+=e[++s];continue}if(i==='"'){r=!1;continue}t+=i}return t}async function js(e,t){let r=[],s,i;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:i,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(s=o.NextRecordName,i=o.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function T(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function de(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function zs(e,t){let r=h(t),s=[],i=[],o=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){i.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){i.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let g=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)o.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of c.ResourceRecords||[]){let m=ue(d,u,g.Value,c.TTL);if("reason"in m){i.push({name:d,type:u,reason:m.reason}),o.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:i,warnings:o}}function ue(e,t,r,s){let i={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...i,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...i,type:"TXT",content:de(r)};case"MX":{let[o,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...i,type:"MX",content:h(a.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=o.slice(0,3).map(Number);return{...i,type:"SRV",content:h(o.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...i,type:"NS",content:h(r)};case"CAA":return{...i,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var le=new Set(["TXT","MX","SRV","NS","CAA"]);async function Ks(e,t){let r=[],s=[],i=new Set;try{let o=await e.listRecords(t.zone);for(let a of o.records||[])i.add(`${h(a.name)}|${a.type}|${T(a)}`)}catch{}for(let o of t.records){let a={...o,proxied:!1},c=`${h(o.name)}|${o.type}|${T(o)}`;if(!le.has(o.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(o);else s.push({record:o,message:u.message||"unknown provider error"});continue}if(i.has(c)){r.push(o);continue}let d=await e.createRecord(t.zone,a);if(d.success)i.add(c),r.push(o);else s.push({record:o,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function Ws(e,t){let r=await e.listRecords(t.zone),s=[],i=[],o=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=o.get(c)??[];d.push(T(a)),o.set(c,d)}for(let a of t.records){let c=o.get(`${h(a.name)}|${a.type}`),d=T(a);if(c?.some((u)=>u===d))s.push(a);else i.push({record:a,found:c?.join(", ")})}return{matched:s,missing:i,ok:i.length===0}}class Ae{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ye(t),"provider"in e)this.dnsProvider=N(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:i=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let a=await this.acm.getDnsValidationRecords(o);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(o,i*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,records:i.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!a.success)s.push(`Failed to delete record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:i}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let a=o.SubjectAlternativeNames||[o.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:i})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:i=[],waitForValidation:o=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...i),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function Js(e,t,r){return new Ae({provider:"porkbun",apiKey:e,secretKey:t},r)}function Xs(e,t,r,s){return new Ae({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function Ys(e,t,r){return new Ae({provider:"route53",region:e,hostedZoneId:t},r||e)}function N(e){switch(e.provider){case"route53":return new ie(e.region,e.hostedZoneId);case"porkbun":return new he(e.apiKey,e.secretKey);case"godaddy":return new Ge(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new H(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Nc(e,t){for(let r of t){let s=N(r);if(await s.canManageDomain(e))return s}return null}class Jn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,o)}let i=process.env.CLOUDFLARE_API_TOKEN;if(i)this.addCloudflare(i,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((i)=>i.provider===e);if(!r)return null;let s=N(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=N(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>N(e))}}var Bc=new Jn;class ye{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let i=await this.describeCertificate({CertificateArn:e});if(i.Status==="ISSUED")return i;if(i.Status==="FAILED"||i.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),i=t.split("."),o=s.split(".");if(i.slice(-o.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let i=s.slice(2),o=t.split("."),a=i.split(".");if(o.slice(-a.length).join(".")===i)return!0}}return!1}}class Br{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ye(e),this.route53=new b,t&&t.provider!=="route53")this.dnsProvider=N(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:i=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(i){if(!await this.acm.waitForCertificateValidation(a,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let a=s||i[0]?.domainName;for(let c of i){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});o.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of i){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});o.push({...a,changeId:c.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,i=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=s||i[0]?.domainName;for(let a of i)try{await this.dnsProvider.deleteRecord(o,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let o of i)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
2
  export{pt,he,Ge,Pg,qt,Pc,kc,jt,H,zn,zt,Kt,Kn,Us,Qs,Pr,kr,Wn,Nr,Hs,Gs,Vs,qs,ie,js,zs,Ks,Ws,Ae,Js,Xs,Ys,N,Nc,Jn,Bc,ye,Br};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-et77ydjb.js";class b{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{n}from"./chunk-9w5ncn9s.js";class b{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
3
3
  <Name>${e.Name}</Name>
4
4
  <CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`