@stacksjs/ts-cloud 0.12.13 → 0.12.14

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 (118) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-bnv8yd9w.js → chunk-16rs9egs.js} +1 -1
  3. package/dist/bin/{chunk-w7k5rvmw.js → chunk-1rcsm0px.js} +1 -1
  4. package/dist/bin/{chunk-nnkhrm4n.js → chunk-1wvrtg42.js} +2 -2
  5. package/dist/bin/{chunk-96xtj5j6.js → chunk-1x7mm26k.js} +1 -1
  6. package/dist/bin/{chunk-7h6h8yxm.js → chunk-2paqksap.js} +3 -3
  7. package/dist/bin/{chunk-2hpnd4g4.js → chunk-3gwmejhk.js} +1 -1
  8. package/dist/bin/{chunk-jcyrm5q0.js → chunk-4201mvaj.js} +1 -1
  9. package/dist/bin/chunk-61ysn56t.js +1 -0
  10. package/dist/bin/{chunk-d5qhwtkg.js → chunk-6vay4ggv.js} +4 -4
  11. package/dist/bin/{chunk-xgepx8yx.js → chunk-92nng29y.js} +1 -1
  12. package/dist/bin/{chunk-1fj5gk6r.js → chunk-9q8zjavc.js} +52 -52
  13. package/dist/bin/{chunk-5gehfky4.js → chunk-a929za72.js} +2 -2
  14. package/dist/bin/{chunk-6xw0r4gn.js → chunk-bj5nq0kn.js} +11 -11
  15. package/dist/bin/{chunk-13dhcjjb.js → chunk-dbmk60r7.js} +2 -2
  16. package/dist/bin/chunk-f1ke4ygp.js +1 -0
  17. package/dist/bin/{chunk-p9hd27k4.js → chunk-f8mbjwme.js} +1 -1
  18. package/dist/bin/{chunk-ymbwekjm.js → chunk-fnr6k11h.js} +1 -1
  19. package/dist/bin/chunk-mzfct5en.js +1 -0
  20. package/dist/bin/{chunk-6zk2n3wk.js → chunk-n6qqa2fr.js} +29 -29
  21. package/dist/bin/{chunk-wvhqjr80.js → chunk-ngav845g.js} +2 -2
  22. package/dist/bin/{chunk-jh1593zx.js → chunk-nrnq9adz.js} +1 -1
  23. package/dist/bin/{chunk-84tvv3x1.js → chunk-pega3x2x.js} +1 -1
  24. package/dist/bin/{chunk-55kmbzr5.js → chunk-pt2bz3kr.js} +1 -1
  25. package/dist/bin/chunk-q5aj280b.js +1 -0
  26. package/dist/bin/{chunk-0vsxpmfj.js → chunk-rpg5k3wt.js} +2 -2
  27. package/dist/bin/{chunk-dh2qmxw9.js → chunk-vwyq2s2k.js} +1 -1
  28. package/dist/bin/{chunk-x5x9dzk7.js → chunk-w637s5q0.js} +1 -1
  29. package/dist/bin/{chunk-gj5jkhfr.js → chunk-wr6a423y.js} +3 -3
  30. package/dist/bin/{chunk-9jfjzycs.js → chunk-y7ece16e.js} +10 -10
  31. package/dist/bin/{chunk-12e9v1dw.js → chunk-ydpnsp4x.js} +1 -1
  32. package/dist/bin/cli.js +76 -76
  33. package/dist/bin/dashboard-server.js +1 -1
  34. package/dist/{chunk-edqhhcg9.js → chunk-5g1hsrab.js} +3 -3
  35. package/dist/chunk-5qqb671d.js +1 -0
  36. package/dist/{chunk-zmyv76f0.js → chunk-5ww7kc5z.js} +4 -4
  37. package/dist/{chunk-sct6mdgc.js → chunk-6j8f4ahv.js} +16 -16
  38. package/dist/{chunk-3qp10j0j.js → chunk-7hy9p6xr.js} +3 -3
  39. package/dist/{chunk-tnjae324.js → chunk-7kwha0fw.js} +61 -61
  40. package/dist/{chunk-g8fpsdyq.js → chunk-9mhcjht7.js} +4 -4
  41. package/dist/{chunk-wpqj98h8.js → chunk-bqaqkmtr.js} +2 -2
  42. package/dist/{chunk-7ww65b66.js → chunk-djd9xgkz.js} +70 -70
  43. package/dist/{chunk-1kp3y2s7.js → chunk-hw3p6pth.js} +1 -1
  44. package/dist/{chunk-emg3shmb.js → chunk-pkan6evc.js} +2 -2
  45. package/dist/{chunk-13d54txj.js → chunk-qzwack6w.js} +2 -2
  46. package/dist/{chunk-9c29rnk3.js → chunk-ttq6dvft.js} +7 -7
  47. package/dist/chunk-vpy3zjqv.js +1 -0
  48. package/dist/{chunk-ej4sm2tw.js → chunk-vva43vnp.js} +5 -5
  49. package/dist/{chunk-1n3ckctd.js → chunk-xxbvjq8g.js} +22 -22
  50. package/dist/deploy/index.js +1 -1
  51. package/dist/dns/index.js +1 -1
  52. package/dist/drivers/index.js +1 -1
  53. package/dist/index.d.ts +1 -1
  54. package/dist/index.js +19 -19
  55. package/dist/operations/index.js +1 -1
  56. package/dist/protection/index.js +1 -1
  57. package/dist/spend/index.js +1 -1
  58. package/dist/ui/404.html +1 -1
  59. package/dist/ui/accept-invitation.html +1 -1
  60. package/dist/ui/access-denied.html +1 -1
  61. package/dist/ui/account/automation.html +6 -6
  62. package/dist/ui/account/security.html +2 -2
  63. package/dist/ui/applications/compose.html +6 -6
  64. package/dist/ui/applications/new.html +1 -1
  65. package/dist/ui/data/backups.html +6 -6
  66. package/dist/ui/data/services.html +6 -6
  67. package/dist/ui/data/volumes.html +6 -6
  68. package/dist/ui/index.html +6 -6
  69. package/dist/ui/infrastructure/topology.html +6 -6
  70. package/dist/ui/integrations.html +2 -2
  71. package/dist/ui/operations/alerts.html +6 -6
  72. package/dist/ui/operations/configuration.html +6 -6
  73. package/dist/ui/operations/jobs.html +6 -6
  74. package/dist/ui/operations/maintenance.html +6 -6
  75. package/dist/ui/operations/observability.html +6 -6
  76. package/dist/ui/operations/previews.html +5 -5
  77. package/dist/ui/operations/queue.html +6 -6
  78. package/dist/ui/operations/regions.html +6 -6
  79. package/dist/ui/operations/releases.html +6 -6
  80. package/dist/ui/operations/spend.html +6 -6
  81. package/dist/ui/operations/workloads.html +6 -6
  82. package/dist/ui/security.html +2 -2
  83. package/dist/ui/server/actions.html +5 -5
  84. package/dist/ui/server/activity.html +2 -2
  85. package/dist/ui/server/capacity.html +5 -5
  86. package/dist/ui/server/database.html +5 -5
  87. package/dist/ui/server/deployments.html +6 -6
  88. package/dist/ui/server/diagnostics.html +1 -1
  89. package/dist/ui/server/firewall.html +6 -6
  90. package/dist/ui/server/fleet.html +6 -6
  91. package/dist/ui/server/logs.html +6 -6
  92. package/dist/ui/server/metrics.html +6 -6
  93. package/dist/ui/server/security.html +2 -2
  94. package/dist/ui/server/services.html +2 -2
  95. package/dist/ui/server/sites.html +5 -5
  96. package/dist/ui/server/ssh-keys.html +6 -6
  97. package/dist/ui/server/team.html +5 -5
  98. package/dist/ui/server/terminal.html +2 -2
  99. package/dist/ui/serverless/alarms.html +6 -6
  100. package/dist/ui/serverless/assets.html +2 -2
  101. package/dist/ui/serverless/cost.html +2 -2
  102. package/dist/ui/serverless/data.html +6 -6
  103. package/dist/ui/serverless/deployments.html +2 -2
  104. package/dist/ui/serverless/firewall.html +2 -2
  105. package/dist/ui/serverless/functions.html +6 -6
  106. package/dist/ui/serverless/logs.html +6 -6
  107. package/dist/ui/serverless/metrics.html +2 -2
  108. package/dist/ui/serverless/queues.html +5 -5
  109. package/dist/ui/serverless/secrets.html +6 -6
  110. package/dist/ui/serverless/traces.html +6 -6
  111. package/dist/ui/serverless.html +5 -5
  112. package/package.json +3 -3
  113. package/dist/bin/chunk-de88yqwy.js +0 -1
  114. package/dist/bin/chunk-qz3za76g.js +0 -1
  115. package/dist/bin/chunk-rxwecjgc.js +0 -1
  116. package/dist/bin/chunk-xaafj6kf.js +0 -1
  117. package/dist/chunk-7by4rm7y.js +0 -1
  118. package/dist/chunk-n688m5fp.js +0 -1
@@ -1 +1 @@
1
- import{Dr}from"./chunk-13d54txj.js";var Sd="\x00";function ro(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 Ai(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&&!ro(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function yi(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 no{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)=>Ai(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=yi(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(!Ai(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=yi(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 Cd(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 bd(){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 Ed="protection.controls",Ii=24,io=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(Ii,Math.max(0.25,e))}var h=500;class so{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Ed);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(Ed,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,io)*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,Ii)*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(!Dr(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 vd(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 Td(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 oo(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 uA(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:oo(o,i)}}}}export{Sd,ro,Ai,yi,no,Cd,bd,Ed,Ii,io,so,vd,Td,oo,uA};
1
+ import{Dr}from"./chunk-qzwack6w.js";var Sd="\x00";function no(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 yi(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&&!no(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function Ii(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 io{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)=>yi(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=Ii(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(!yi(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=Ii(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 Cd(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 bd(){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 Ed="protection.controls",Si=24,so=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(Si,Math.max(0.25,e))}var h=500;class oo{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Ed);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(Ed,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,so)*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,Si)*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(!Dr(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 vd(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 Td(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 ao(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 uA(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:ao(o,i)}}}}export{Sd,no,yi,Ii,io,Cd,bd,Ed,Si,so,oo,vd,Td,ao,uA};
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-30h9rgfn.js";import{h}from"./chunk-wjgnfg6q.js";var un=new Set(["A","AAAA","CNAME"]);function A(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 D(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((i)=>setTimeout(i,o))}class Ne{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 o,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:i.signal})}catch(d){if(r=d,s===8)throw d;await D(s);continue}finally{clearTimeout(a)}if(!o.ok){if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}`),!A(o.status)||s===8)throw r;await D(s,o);continue}let c=await o.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!A(0,c.message)||s===8)throw r;await D(s,o);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(!Ne.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let i=[];for(let a of o.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)i.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return i}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((i)=>i.type===t.type&&this.getSubdomain(i.name,r)===s&&i.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)o.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let i=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,o);if(Ne.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${i.length>0?` (${i.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),o=await this.listRecords(e,t.type);if(o.success){let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(i?.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}/${i.id}`,a),{success:!0,id:i.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),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!i?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let 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(`/dns/getNS/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/dns/updateNS/${r}`,{ns:t}),!0}catch{return!1}}}class Ct{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}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let a=await fetch(s,i);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),o={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),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),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),i=o.filter((a)=>a.data!==t.content);if(i.length===o.length)return{success:!1,message:"Record not found"};if(i.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}`,i);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((i)=>this.fromGoDaddyRecord(i,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 N="https://api.cloudflare.com/client/v4",Ji="[ts-cloud]";class bt{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=`${N}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let c=await(await fetch(s,i)).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 o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let i=o.result[0].id;return this.zoneCache.set(r,i),{id:i,name:o.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&un.has(e.type)){if(s.proxied=o,o)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let i=S(e);if(i)s.data=i,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),i=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??i?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(i)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${i.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,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return{success:!1,message:"Record not found"};let a=i.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 o=[],i=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${i}`);if(o.push(...c.result||[]),c.result_info)a=i<c.result_info.total_pages,i++;else a=!1}return{success:!0,records:o.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 o=await this.getZoneDetails(r);if(o)return{...o,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(i){let a=i instanceof Error?i.message:String(i);if(!/already exists|1061/i.test(a))throw i;let c=await this.getZoneDetails(r);if(!c)throw i;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 o of r.result||[]){if(o.status!=="active")continue;for(let i of o.hosts||[])s.add(i.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,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(i.result&&i.result.length>0)return i.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),o=s.id,i=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);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/${o}/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 o of r.result||[])s[o.id]=o.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),o=[],i=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&w(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),o.push({id:a,from:d,to:c})}catch(u){i.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:o,failed:i}}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)).filter((d)=>!(d.description||"").startsWith(Ji)),a=r.map((d)=>({...d,description:d.description?.startsWith(Ji)?d.description:`${Ji} ${d.description||t}`})),c=[...i,...a].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)}}}}function w(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((o,i)=>w(o,t[i]))}let r=e,s=t;return Object.keys(s).every((o)=>w(r[o],s[o]))}function S(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:C(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,o,i]=r.slice(0,3).map(Number);if(![s,o,i].every(Number.isFinite))return null;return{priority:s,weight:o,port:i,target:C(r.slice(3).join(" "))}}function C(e){return e.replace(/\.$/,"")}var b=new Set(["A","AAAA","CNAME","ALIAS"]);function Et(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function R(e){return e.replace(/\.$/,"").toLowerCase()}function pn(e,t){let r=R(t),s=(e??"@").trim();if(!s||s==="@")return r;let o=R(s);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function Xi(e,t){return e.map((r)=>({...r,name:pn(r.name,t),proxied:r.proxied??!1}))}function I(e,t){if(e.type!==t.type)return!1;if(R(e.name)!==R(t.name))return!1;if(b.has(t.type))return!0;if(t.type==="TXT"){let r=Et(t.content);if(r)return Et(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function E(e,t){if(f(e.content)!==f(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Yi(e){let{provider:t,zone:r,records:s}=e,o={outcomes:[],warnings:[]};if(s.length===0)return o;let i=await t.listRecords(r);if(!i.success)return o.warnings.push(`could not list ${r}: ${i.message||"unknown provider error"} — records not reconciled`),o;let a=i.records;for(let c of s){let d=a.filter((l)=>I(l,c));if(d.length>0&&d.every((l)=>E(l,c))){o.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"&&Et(c.content)!==void 0;if(g)for(let l of d){let v=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!v.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${v.message||"unknown error"}`)}let p=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(p.success)o.outcomes.push({record:c,action:d.length>0?"updated":"created"});else o.outcomes.push({record:c,action:"failed",message:p.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>R(u.name)));for(let u of d){let g=new Set(s.filter((l)=>l.type===c&&R(l.name)===u).map((l)=>f(l.content).toLowerCase())),p=a.filter((l)=>l.type===c&&R(l.name)===u&&!g.has(f(l.content).toLowerCase()));for(let l of p)o.warnings.push(`${u} has an undeclared ${c} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class ge{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new h(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 o=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}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}.`}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),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;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:o}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}}),{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}),o=[];for(let i of s.ResourceRecordSets){if(t&&i.Type!==t)continue;if(i.AliasTarget)continue;for(let a of i.ResourceRecords||[]){let c=a.Value,d;if(i.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(i.Type==="TXT"&&c.startsWith('"')&&c.endsWith('"'))c=c.slice(1,-1);o.push({name:i.Name.replace(/\.$/,""),type:i.Type,content:c,ttl:i.TTL,priority:d})}}return{success:!0,records:o}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:h.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=h.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})}}async function Zi(e,t){let r=[],s,o;for(;;){let i=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:o,MaxItems:"100"});if(r.push(...i.ResourceRecordSets),!i.IsTruncated)break;if(s=i.NextRecordName,o=i.NextRecordType,!s)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function P(e){return e.replace(/\.$/,"")}function y(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${P(e.content)}`;return P(e.content)}function x(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function es(e,t){let r=m(t),s=[],o=[],i=[],a=new Set;for(let c of e){let d=m(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){o.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){o.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),i.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=m(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)i.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 p=V(d,u,g.Value,c.TTL);if("reason"in p){o.push({name:d,type:u,reason:p.reason}),i.push(`${u} ${d}: ${p.reason}`);continue}s.push(p)}}return{zone:r,records:s,skipped:o,warnings:i}}function V(e,t,r,s){let o={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:x(r)};case"MX":{let[i,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(a.join(" ")),priority:Number(i)}}case"SRV":{let i=r.trim().split(/\s+/);if(i.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=i.slice(0,3).map(Number);return{...o,type:"SRV",content:m(i.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var M=new Set(["TXT","MX","SRV","NS","CAA"]);async function ts(e,t){let r=[],s=[],o=new Set;try{let i=await e.listRecords(t.zone);for(let a of i.records||[])o.add(`${m(a.name)}|${a.type}|${y(a)}`)}catch{}for(let i of t.records){let a={...i,proxied:!1},c=`${m(i.name)}|${i.type}|${y(i)}`;if(!M.has(i.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(i);else s.push({record:i,message:u.message||"unknown provider error"});continue}if(o.has(c)){r.push(i);continue}let d=await e.createRecord(t.zone,a);if(d.success)o.add(c),r.push(i);else s.push({record:i,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function rs(e,t){let r=await e.listRecords(t.zone),s=[],o=[],i=new Map;for(let a of r.records||[]){let c=`${m(a.name)}|${a.type}`,d=i.get(c)??[];d.push(y(a)),i.set(c,d)}for(let a of t.records){let c=i.get(`${m(a.name)}|${a.type}`),d=y(a);if(c?.some((u)=>u===d))s.push(a);else o.push({record:a,found:c?.join(", ")})}return{matched:s,missing:o,ok:o.length===0}}class ie{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 o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((i)=>setTimeout(i,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),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let o=s.slice(2),i=t.split("."),a=o.split(".");if(i.slice(-a.length).join(".")===o)return!0}}return!1}}class rr{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ie(e),this.route53=new h,t&&t.provider!=="route53")this.dnsProvider=T(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:o=!1,maxWaitMinutes:i=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(o){if(!await this.acm.waitForCertificateValidation(a,i*2,30000))throw Error(`Certificate validation timed out after ${i} 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((o)=>setTimeout(o,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 o=await this.acm.getDnsValidationRecords(t),i=[];if(this.dnsProvider){let a=s||o[0]?.domainName;for(let c of o){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});i.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of o){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}]}}]}});i.push({...a,changeId:c.ChangeInfo?.Id})}return i}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let i=s||o[0]?.domainName;for(let a of o)try{await this.dnsProvider.deleteRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let i of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${i.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED")return{certificateArn:i.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class ne{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ie(t),"provider"in e)this.dnsProvider=T(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e,{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);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(i,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:i,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=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.upsertRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,records:o.map((i)=>({domainName:i.domainName,recordName:i.recordName,recordType:i.recordType,recordValue:i.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.deleteRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue});if(!a.success)s.push(`Failed to delete record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:o}=e,i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED"){let a=i.SubjectAlternativeNames||[i.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:i.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:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:o=[],waitForValidation:i=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:i})}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((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function ns(e,t,r){return new ne({provider:"porkbun",apiKey:e,secretKey:t},r)}function is(e,t,r,s){return new ne({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function ss(e,t,r){return new ne({provider:"route53",region:e,hostedZoneId:t},r||e)}function T(e){switch(e.provider){case"route53":return new ge(e.region,e.hostedZoneId);case"porkbun":return new Ne(e.apiKey,e.secretKey);case"godaddy":return new Ct(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new bt(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Da(e,t){for(let r of t){let s=T(r);if(await s.canManageDomain(e))return s}return null}class gn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let i=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,i)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((o)=>o.provider===e);if(!r)return null;let s=T(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=T(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>T(e))}}var Pa=new gn;
2
- export{un,Ne,Ct,Ji,bt,Et,pn,Xi,Yi,ge,Zi,es,ts,rs,ne,ns,is,ss,T,Da,gn,Pa,ie,rr};
1
+ import{n}from"./chunk-30h9rgfn.js";import{h}from"./chunk-wjgnfg6q.js";var un=new Set(["A","AAAA","CNAME"]);function A(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 D(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((i)=>setTimeout(i,o))}class Ne{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 o,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:i.signal})}catch(d){if(r=d,s===8)throw d;await D(s);continue}finally{clearTimeout(a)}if(!o.ok){if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}`),!A(o.status)||s===8)throw r;await D(s,o);continue}let c=await o.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!A(0,c.message)||s===8)throw r;await D(s,o);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(!Ne.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let i=[];for(let a of o.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)i.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return i}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((i)=>i.type===t.type&&this.getSubdomain(i.name,r)===s&&i.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)o.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let i=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,o);if(Ne.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${i.length>0?` (${i.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),o=await this.listRecords(e,t.type);if(o.success){let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(i?.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}/${i.id}`,a),{success:!0,id:i.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),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let i=o.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!i?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let 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(`/dns/getNS/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/dns/updateNS/${r}`,{ns:t}),!0}catch{return!1}}}class Ct{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}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let a=await fetch(s,i);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),o={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),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),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),i=o.filter((a)=>a.data!==t.content);if(i.length===o.length)return{success:!1,message:"Record not found"};if(i.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}`,i);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((i)=>this.fromGoDaddyRecord(i,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 N="https://api.cloudflare.com/client/v4",Xi="[ts-cloud]";class bt{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=`${N}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},i={method:e,headers:o};if(r)i.body=JSON.stringify(r);let c=await(await fetch(s,i)).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 o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let i=o.result[0].id;return this.zoneCache.set(r,i),{id:i,name:o.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&un.has(e.type)){if(s.proxied=o,o)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let i=S(e);if(i)s.data=i,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),i=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??i?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(i)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${i.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,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!i.result||i.result.length===0)return{success:!1,message:"Record not found"};let a=i.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 o=[],i=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${i}`);if(o.push(...c.result||[]),c.result_info)a=i<c.result_info.total_pages,i++;else a=!1}return{success:!0,records:o.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 o=await this.getZoneDetails(r);if(o)return{...o,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(i){let a=i instanceof Error?i.message:String(i);if(!/already exists|1061/i.test(a))throw i;let c=await this.getZoneDetails(r);if(!c)throw i;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 o of r.result||[]){if(o.status!=="active")continue;for(let i of o.hosts||[])s.add(i.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,o=this.getFullRecordName(t.name,r.name),i=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(i.result&&i.result.length>0)return i.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),o=s.id,i=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);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/${o}/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 o of r.result||[])s[o.id]=o.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),o=[],i=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&w(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),o.push({id:a,from:d,to:c})}catch(u){i.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:o,failed:i}}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)).filter((d)=>!(d.description||"").startsWith(Xi)),a=r.map((d)=>({...d,description:d.description?.startsWith(Xi)?d.description:`${Xi} ${d.description||t}`})),c=[...i,...a].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)}}}}function w(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((o,i)=>w(o,t[i]))}let r=e,s=t;return Object.keys(s).every((o)=>w(r[o],s[o]))}function S(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:C(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,o,i]=r.slice(0,3).map(Number);if(![s,o,i].every(Number.isFinite))return null;return{priority:s,weight:o,port:i,target:C(r.slice(3).join(" "))}}function C(e){return e.replace(/\.$/,"")}var b=new Set(["A","AAAA","CNAME","ALIAS"]);function Et(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function R(e){return e.replace(/\.$/,"").toLowerCase()}function pn(e,t){let r=R(t),s=(e??"@").trim();if(!s||s==="@")return r;let o=R(s);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function Yi(e,t){return e.map((r)=>({...r,name:pn(r.name,t),proxied:r.proxied??!1}))}function I(e,t){if(e.type!==t.type)return!1;if(R(e.name)!==R(t.name))return!1;if(b.has(t.type))return!0;if(t.type==="TXT"){let r=Et(t.content);if(r)return Et(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function E(e,t){if(f(e.content)!==f(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Zi(e){let{provider:t,zone:r,records:s}=e,o={outcomes:[],warnings:[]};if(s.length===0)return o;let i=await t.listRecords(r);if(!i.success)return o.warnings.push(`could not list ${r}: ${i.message||"unknown provider error"} — records not reconciled`),o;let a=i.records;for(let c of s){let d=a.filter((l)=>I(l,c));if(d.length>0&&d.every((l)=>E(l,c))){o.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"&&Et(c.content)!==void 0;if(g)for(let l of d){let v=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!v.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${v.message||"unknown error"}`)}let p=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(p.success)o.outcomes.push({record:c,action:d.length>0?"updated":"created"});else o.outcomes.push({record:c,action:"failed",message:p.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>R(u.name)));for(let u of d){let g=new Set(s.filter((l)=>l.type===c&&R(l.name)===u).map((l)=>f(l.content).toLowerCase())),p=a.filter((l)=>l.type===c&&R(l.name)===u&&!g.has(f(l.content).toLowerCase()));for(let l of p)o.warnings.push(`${u} has an undeclared ${c} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class ge{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new h(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 o=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}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}.`}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),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;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:o}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),o=t.content;if(t.type==="TXT"&&!o.startsWith('"'))o=`"${o}"`;if(t.type==="MX"&&t.priority!==void 0)o=`${t.priority} ${o}`;return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}}),{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}),o=[];for(let i of s.ResourceRecordSets){if(t&&i.Type!==t)continue;if(i.AliasTarget)continue;for(let a of i.ResourceRecords||[]){let c=a.Value,d;if(i.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(i.Type==="TXT"&&c.startsWith('"')&&c.endsWith('"'))c=c.slice(1,-1);o.push({name:i.Name.replace(/\.$/,""),type:i.Type,content:c,ttl:i.TTL,priority:d})}}return{success:!0,records:o}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:h.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=h.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})}}async function es(e,t){let r=[],s,o;for(;;){let i=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:o,MaxItems:"100"});if(r.push(...i.ResourceRecordSets),!i.IsTruncated)break;if(s=i.NextRecordName,o=i.NextRecordType,!s)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function P(e){return e.replace(/\.$/,"")}function y(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${P(e.content)}`;return P(e.content)}function x(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function ts(e,t){let r=m(t),s=[],o=[],i=[],a=new Set;for(let c of e){let d=m(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){o.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){o.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),i.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=m(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)i.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 p=V(d,u,g.Value,c.TTL);if("reason"in p){o.push({name:d,type:u,reason:p.reason}),i.push(`${u} ${d}: ${p.reason}`);continue}s.push(p)}}return{zone:r,records:s,skipped:o,warnings:i}}function V(e,t,r,s){let o={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:x(r)};case"MX":{let[i,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(a.join(" ")),priority:Number(i)}}case"SRV":{let i=r.trim().split(/\s+/);if(i.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=i.slice(0,3).map(Number);return{...o,type:"SRV",content:m(i.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var M=new Set(["TXT","MX","SRV","NS","CAA"]);async function rs(e,t){let r=[],s=[],o=new Set;try{let i=await e.listRecords(t.zone);for(let a of i.records||[])o.add(`${m(a.name)}|${a.type}|${y(a)}`)}catch{}for(let i of t.records){let a={...i,proxied:!1},c=`${m(i.name)}|${i.type}|${y(i)}`;if(!M.has(i.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(i);else s.push({record:i,message:u.message||"unknown provider error"});continue}if(o.has(c)){r.push(i);continue}let d=await e.createRecord(t.zone,a);if(d.success)o.add(c),r.push(i);else s.push({record:i,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function ns(e,t){let r=await e.listRecords(t.zone),s=[],o=[],i=new Map;for(let a of r.records||[]){let c=`${m(a.name)}|${a.type}`,d=i.get(c)??[];d.push(y(a)),i.set(c,d)}for(let a of t.records){let c=i.get(`${m(a.name)}|${a.type}`),d=y(a);if(c?.some((u)=>u===d))s.push(a);else o.push({record:a,found:c?.join(", ")})}return{matched:s,missing:o,ok:o.length===0}}class ie{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 o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((i)=>setTimeout(i,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),o=t.split("."),i=s.split(".");if(o.slice(-i.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let o=s.slice(2),i=t.split("."),a=o.split(".");if(i.slice(-a.length).join(".")===o)return!0}}return!1}}class rr{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ie(e),this.route53=new h,t&&t.provider!=="route53")this.dnsProvider=T(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:o=!1,maxWaitMinutes:i=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(o){if(!await this.acm.waitForCertificateValidation(a,i*2,30000))throw Error(`Certificate validation timed out after ${i} 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((o)=>setTimeout(o,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 o=await this.acm.getDnsValidationRecords(t),i=[];if(this.dnsProvider){let a=s||o[0]?.domainName;for(let c of o){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});i.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of o){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}]}}]}});i.push({...a,changeId:c.ChangeInfo?.Id})}return i}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let i=s||o[0]?.domainName;for(let a of o)try{await this.dnsProvider.deleteRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let i of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${i.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED")return{certificateArn:i.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:o});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class ne{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ie(t),"provider"in e)this.dnsProvider=T(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:o=30}=e,{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);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(i,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:i,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=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.upsertRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,records:o.map((i)=>({domainName:i.domainName,recordName:i.recordName,recordType:i.recordType,recordValue:i.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],o=await this.acm.getDnsValidationRecords(t);for(let i of o){let a=await this.dnsProvider.deleteRecord(r,{name:i.recordName,type:i.recordType,content:i.recordValue});if(!a.success)s.push(`Failed to delete record for ${i.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:o}=e,i=await this.acm.findCertificateByDomain(t);if(i&&i.Status==="ISSUED"){let a=i.SubjectAlternativeNames||[i.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:i.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:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:o=[],waitForValidation:i=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:i})}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((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function is(e,t,r){return new ne({provider:"porkbun",apiKey:e,secretKey:t},r)}function ss(e,t,r,s){return new ne({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function os(e,t,r){return new ne({provider:"route53",region:e,hostedZoneId:t},r||e)}function T(e){switch(e.provider){case"route53":return new ge(e.region,e.hostedZoneId);case"porkbun":return new Ne(e.apiKey,e.secretKey);case"godaddy":return new Ct(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new bt(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Pa(e,t){for(let r of t){let s=T(r);if(await s.canManageDomain(e))return s}return null}class gn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let i=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,i)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((o)=>o.provider===e);if(!r)return null;let s=T(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=T(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>T(e))}}var Na=new gn;
2
+ export{un,Ne,Ct,Xi,bt,Et,pn,Yi,Zi,ge,es,ts,rs,ns,ne,is,ss,os,T,Pa,gn,Na,ie,rr};
@@ -1,7 +1,7 @@
1
1
  var Vc={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Vc,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Dr(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Dr))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function jc(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function zc(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(jc(e)))t.push(`${n} = ${s}`);return`${t.join(`
2
2
  `)}
3
3
  `}function Kc(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
- `)}function di(e={}){return`#!/usr/bin/env bash
4
+ `)}function li(e={}){return`#!/usr/bin/env bash
5
5
  # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
6
  set -euo pipefail
7
7
 
@@ -41,4 +41,4 @@ fi
41
41
  systemctl enable nftables >/dev/null 2>&1 || true
42
42
  echo "ts-cloud: L3/L4 mitigation active"
43
43
  `}var b=["off","monitor","rate_limit","challenge","lockdown"];function Ip(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function Pr(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
- export{Vc,Dr,jc,zc,Kc,di,Ip,Pr};
44
+ export{Vc,Dr,jc,zc,Kc,li,Ip,Pr};
@@ -1,16 +1,16 @@
1
- import{rt,zn,Kn,Wn}from"./chunk-edqhhcg9.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rh(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function nh(t){if(!t)return[];let e=[];for(let n of t.split(`
1
+ import{rt,Kn,Wn,Jn}from"./chunk-5g1hsrab.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rh(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function nh(t){if(!t)return[];let e=[];for(let n of t.split(`
2
2
  `)){let r=n.trim();if(!r.startsWith("site:"))continue;let[,s,o,i]=r.split(":");if(!s||o!=="no")continue;e.push({name:s,size:i||"?"})}return e}function ih(t,e,n){let r=t.map((o)=>` ${e}-${o.name} (${o.size})`).join(`
3
3
  `),s=t.length===1?"it":"them";return`This server still holds ${t.length} site tree${t.length===1?"":"s"} with nothing running for ${s}:
4
4
  ${r}
5
5
  `+"A site moved off this box keeps its files here on purpose — they are the rollback, and they are what makes "+`the move reversible until this server is destroyed. Destroying it now discards that.
6
- Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var Du="ts-cloud/project",Pu="ts-cloud/environment",Nu="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function sh(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[Du]),environment:d(e[Pu]),role:d(e[Nu])}}function w(t){return t.slug?.trim()||"app"}function ku(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function Bu(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function oh(t,e,n=rt){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,Kn(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
- `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:ku(Wn(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
6
+ Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var Du="ts-cloud/project",Pu="ts-cloud/environment",Nu="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function sh(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[Du]),environment:d(e[Pu]),role:d(e[Nu])}}function w(t){return t.slug?.trim()||"app"}function ku(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function Bu(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function oh(t,e,n=rt){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,Wn(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
+ `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:ku(Jn(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
8
8
  `)[0]:String(r);return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}}function u(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function ah(t,e,n){let r=new Set(e.filter((a)=>a.slug===n).map((a)=>u(a.host,a.path))),s=[],o=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&r.has(u(a.domain,a.path)))s.push(a);else o.push(a);return{present:s,absent:o,loopback:i,foreign:e.filter((a)=>a.slug!==n)}}function xu(t,e,n){let r=new Set;for(let s of e)for(let o of s.routes)if(o.slug===n)r.add(u(o.host,o.path));return t.filter((s)=>!s.loopbackOnly&&s.domain!==void 0&&!r.has(u(s.domain,s.path)))}function ch(t){let{slug:e,servers:n,probes:r,declared:s}=t,o=[];if(o.push(n.length===0?"No servers found.":`${n.length} server${n.length===1?"":"s"}:`),n.length>0)o.push("");let i=new Map(r.map((a)=>[a.server,a]));for(let a of n){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);o.push(` ${a.name} ${p.join(" ")}`),o.push(` ${k(a)}`);let c=i.get(a.name);if(!c)o.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)o.push(` could not read ${rt}: ${c.unavailable}`);else o.push(...P(c,e));o.push("")}return o.push(...C(t)),o}function k(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function P(t,e){let n=Bu(t.routes);if(n.length===0)return[` serves nothing: ${rt} is empty or absent`];let r=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${n.length} project${n.length===1?"":"s"}:`];for(let s of n){r.push(` ${s.slug}${s.slug===e?" (this project)":""}`);for(let o of s.routes)r.push(` ${o.host}${o.path==="/"?"/":o.path} -> ${O(o)}`)}return r}function O(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function C(t){let{slug:e,declared:n,probes:r,servers:s}=t;if(n.length===0)return[`This project ('${e}') declares no sites.`];let o=[`This project ('${e}') declares ${n.length} site${n.length===1?"":"s"}: `+n.map((c)=>c.name).join(", ")],i=n.filter((c)=>c.loopbackOnly);if(i.length>0)o.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=r.filter((c)=>!c.unavailable);if(a.length===0)return o.push(" Nothing to reconcile them against: no box reported what it serves."),o;let p=xu(n,a,e);if(o.push(` ${n.length-i.length-p.length} routed by a box above`),p.length>0){o.push(` ${p.length} not routed by any box above: ${p.map((b)=>b.name).join(", ")}`);let c=r.length-a.length,g=s.length-r.length;if(c>0)o.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(g>0)o.push(` Either they were never deployed, or they are on one of the ${g} server${g===1?"":"s"} this run did not probe.`);else o.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return o}async function dh(t){let e=[];for(let n of t.steps)try{e.push({step:n,state:await n.satisfied()?"satisfied":"pending"})}catch(r){e.push({step:n,state:"unknown",reason:r instanceof Error?r.message:String(r)})}return e}function ac(t){return t.filter((e)=>e.state!=="satisfied")}function _u(t){return ac(t).some((e)=>e.step.destructive===!0)}function lh(t,e){let n=ac(e),r=[`${t.operation} ${t.target}`];if(n.length===0)return r.push(" Nothing to do — every step is already satisfied."),r;for(let{step:o,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[o.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(r.push(` ${p}${o.title}${c.length>0?` [${c.join(", ")}]`:""}`),o.change)r.push(` ${o.change.from} → ${o.change.to}`);if(a)r.push(` could not check: ${a}`)}let s=n.filter((o)=>o.step.destructive).length;return r.push(` ${n.length} step(s) would run`+(s>0?`, ${s} irreversible — re-run with --confirm ${t.target}`:"")),r}async function uh(t,e,n={}){let r={operation:t.operation,target:t.target,steps:[],success:!0};if(_u(e)&&n.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:s,state:o}of e){if(o==="satisfied"){r.steps.push({id:s.id,title:s.title,state:"skipped"}),n.log?.(`skip ${s.title} (already done)`);continue}n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"started"});try{await s.apply(),r.steps.push({id:s.id,title:s.title,state:"applied"}),n.log?.(`done ${s.title}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return r.steps.push({id:s.id,title:s.title,state:"failed",error:a}),r.success=!1,n.log?.(`FAIL ${s.title}: ${a}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"failed",error:a}),r}}return r}function Ou(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function ph(t,e,n){if(Ou(e),t===e)throw Error(`'${t}' is already named that.`);if((await n.takenNames()).some((o)=>o===e&&o!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let s=[];if(n.providerName&&n.renameProvider){let{providerName:o,renameProvider:i}=n;s.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}if(n.stateName&&n.writeStateName){let{stateName:o,writeStateName:i}=n;s.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await o();return a===void 0||a===e},apply:()=>i(e)})}if(n.remoteHostname&&n.setRemoteHostname){let{remoteHostname:o,setRemoteHostname:i}=n;s.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}return s.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>n.inventoryName()===e,apply:async()=>{await n.renameInventory(e)}}),{operation:"server:rename",target:t,steps:s}}function gh(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
9
- `)}function mh(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function hh(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function fh(t,e,n){let r=[],s=zn(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function Ah(t){return t.registryRead&&t.conflicts.length===0}function yh(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function jn(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function cc(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function Lu(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
9
+ `)}function mh(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function hh(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function fh(t,e,n){let r=[],s=Kn(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function Ah(t){return t.registryRead&&t.conflicts.length===0}function yh(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function zn(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function cc(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function Lu(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
10
10
  `)}function m(t,e){return`^${t}-${e}-((queue|daemon)-.*|scheduler)\\.service$`}function $u(t,e){return y(m(t,e))}function y(t){return[`ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(t)} | while read -r unit; do`,' systemctl is-active "$unit" >/dev/null 2>&1 && echo "active:$unit" || true',"done"].join(`
11
11
  `)}function Mu(t){return!t.split(`
12
- `).some((e)=>e.trim().startsWith("active:"))}function Fu(t,e,n){let r=jn(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${cc(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
- `)}function Uu(t,e,n){let r=jn(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(cc(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
12
+ `).some((e)=>e.trim().startsWith("active:"))}function Fu(t,e,n){let r=zn(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${cc(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
+ `)}function Uu(t,e,n){let r=zn(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(cc(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
14
14
  `)}function Qu(t,e,n){return[`test -d ${l(n)} && echo tree:present || echo tree:absent`,`systemctl is-active ${t}-${e}.service >/dev/null 2>&1 && echo unit:active || echo unit:inactive`].join(`
15
15
  `)}function Hu(t){return t.includes("tree:present")&&t.includes("unit:active")}function Gu(t,e="/",n=10){let r=`http://127.0.0.1:${t}${e.startsWith("/")?e:`/${e}`}`;return["set -eu",`for i in $(seq 1 ${n}); do`,` if curl -fsS -o /dev/null --max-time 5 ${l(r)}; then echo healthy; exit 0; fi`," sleep 3","done",`echo "no healthy response from ${r}" >&2`,"exit 1"].join(`
16
16
  `)}function qu(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(v(t,e))} || true); do`,' systemctl disable --now "$unit" 2>/dev/null || true',"done",`rm -f /etc/rpx/sites.d/${t}.json 2>/dev/null || true`,"systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true"].join(`
@@ -19,4 +19,4 @@ Verify the site is serving from its new home first, then re-run with ${n} to des
19
19
  `)}function Ch(t){let e=new Map;for(let n of t.split(`
20
20
  `)){let r=n.trim();if(!r.startsWith("cert:"))continue;let[,s,o]=r.split(":");if(s&&o)e.set(s,o)}return e}function bh(t,e){for(let[n,r]of t){if(r==="absent")continue;if(e.get(n)!==r)return!1}return!0}function Eh(t,e,n){let r=e.flatMap((s)=>[`${s}.crt`,`${s}.key`]);return["set -eu",`rm -f ${l(n)}`,`cd ${l(t)} 2>/dev/null || { echo "no certs dir at ${t}" >&2; exit 0; }`,`TS_CLOUD_CERTS="$(ls ${r.map(l).join(" ")} 2>/dev/null | tr '\\n' ' ' || true)"`,'[ -n "$TS_CLOUD_CERTS" ] || { echo "no certificates to carry"; exit 0; }',`tar czf ${l(n)} $TS_CLOUD_CERTS`].join(`
21
21
  `)}function vh(t,e){return["set -eu",`[ -s ${l(e)} ] || { echo "no certificate archive staged"; exit 0; }`,`mkdir -p ${l(t)}`,`tar xzf ${l(e)} -C ${l(t)}`,`chmod 600 ${l(t)}/*.key 2>/dev/null || true`,`rm -f ${l(e)}`].join(`
22
- `)}async function Th(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>Mu(await e.runOnSource($u(n,r))),apply:async()=>{await e.runOnSource(Lu(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:jn(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(Fu(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:jn(n,r),to:`${i}:${s}`},satisfied:async()=>Hu(await e.runOnTarget(Qu(n,r,s))),apply:async()=>{await e.runOnTarget(Uu(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(Gu(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>ju(await e.runOnSource(Vu(n,r))),apply:async()=>{await e.runOnSource(qu(n,r))}}),{operation:"site:move",target:r,steps:p}}export{rh,nh,ih,Du,Pu,Nu,sh,ku,Bu,oh,ah,xu,ch,dh,ac,_u,lh,uh,Ou,ph,gh,mh,hh,fh,Ah,yh,jn,cc,Lu,$u,Mu,Fu,Uu,Qu,Hu,Gu,qu,Vu,ju,Ih,Sh,Ch,bh,Eh,vh,Th};
22
+ `)}async function Th(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>Mu(await e.runOnSource($u(n,r))),apply:async()=>{await e.runOnSource(Lu(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:zn(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(Fu(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:zn(n,r),to:`${i}:${s}`},satisfied:async()=>Hu(await e.runOnTarget(Qu(n,r,s))),apply:async()=>{await e.runOnTarget(Uu(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(Gu(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>ju(await e.runOnSource(Vu(n,r))),apply:async()=>{await e.runOnSource(qu(n,r))}}),{operation:"site:move",target:r,steps:p}}export{rh,nh,ih,Du,Pu,Nu,sh,ku,Bu,oh,ah,xu,ch,dh,ac,_u,lh,uh,Ou,ph,gh,mh,hh,fh,Ah,yh,zn,cc,Lu,$u,Mu,Fu,Uu,Qu,Hu,Gu,qu,Vu,ju,Ih,Sh,Ch,bh,Eh,vh,Th};
@@ -0,0 +1 @@
1
+ import{Qi,Hi,Gi,qi,ha,fa}from"./chunk-vva43vnp.js";import"./chunk-6g81m01r.js";import"./chunk-pkan6evc.js";import"./chunk-wjgnfg6q.js";import"./chunk-jb8em9ba.js";import"./chunk-3kapcdpn.js";import"./chunk-30h9rgfn.js";export{ha as deleteStaticSite,Hi as deployStaticSite,fa as deployStaticSiteFull,Qi as generateStaticSiteTemplate,qi as invalidateCache,Gi as uploadStaticFiles};