@stacksjs/ts-cloud 0.16.15 → 0.16.16

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 (180) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-r7k2mkn7.js → chunk-0znhykt9.js} +5 -5
  3. package/dist/bin/{chunk-23nxkj19.js → chunk-1baj8p0r.js} +1 -1
  4. package/dist/bin/{chunk-9j7qhwe0.js → chunk-2943bszc.js} +1 -1
  5. package/dist/bin/chunk-2tn43y0d.js +1 -0
  6. package/dist/bin/{chunk-b7b87gxb.js → chunk-2v91xnqx.js} +2 -2
  7. package/dist/bin/{chunk-gwpmn3a3.js → chunk-2w591cvg.js} +1 -1
  8. package/dist/bin/{chunk-5jf6veax.js → chunk-3qfd0vnc.js} +3 -3
  9. package/dist/bin/{chunk-489c9r4g.js → chunk-3x4p2s2r.js} +3 -3
  10. package/dist/bin/chunk-4v6f496n.js +1 -0
  11. package/dist/bin/chunk-64cdtvar.js +1 -0
  12. package/dist/bin/chunk-66egshmp.js +1 -0
  13. package/dist/bin/chunk-7raskz63.js +1 -0
  14. package/dist/bin/{chunk-zm95j24a.js → chunk-80295akq.js} +3 -3
  15. package/dist/bin/{chunk-fjd8tw77.js → chunk-90c3rkd8.js} +4 -4
  16. package/dist/bin/chunk-9bxyy4th.js +1 -0
  17. package/dist/bin/{chunk-pm2vz6zp.js → chunk-b3yp7bak.js} +3 -3
  18. package/dist/bin/chunk-bbt0vyzj.js +1 -0
  19. package/dist/bin/{chunk-tb4ek3s5.js → chunk-bhay1f8a.js} +1 -1
  20. package/dist/bin/chunk-cpcae7e2.js +1 -0
  21. package/dist/bin/{chunk-cb47f0pb.js → chunk-cs6a98r1.js} +2 -2
  22. package/dist/bin/{chunk-3eht1tp2.js → chunk-dczw0nxw.js} +5 -5
  23. package/dist/bin/{chunk-3z65v87m.js → chunk-dp2fsnpe.js} +6 -6
  24. package/dist/bin/chunk-dsc7ef1w.js +1 -0
  25. package/dist/bin/{chunk-21am8b1b.js → chunk-edfh9ts2.js} +1 -1
  26. package/dist/bin/chunk-f2wn46nw.js +1 -0
  27. package/dist/bin/chunk-fddwwac7.js +1 -0
  28. package/dist/bin/chunk-ffcyj2jj.js +1 -0
  29. package/dist/bin/{chunk-2cyhks5n.js → chunk-fjz07v7g.js} +1 -1
  30. package/dist/bin/chunk-gbejgj71.js +1 -0
  31. package/dist/bin/{chunk-58phgtc8.js → chunk-grs2cwm7.js} +2 -2
  32. package/dist/bin/{chunk-p0vyt3fq.js → chunk-gv9deppc.js} +2 -2
  33. package/dist/bin/{chunk-5ffj7508.js → chunk-j0wfftk1.js} +1 -1
  34. package/dist/bin/{chunk-yas09vmt.js → chunk-j76935z3.js} +3 -3
  35. package/dist/bin/{chunk-0y4a84jm.js → chunk-khta83xb.js} +12 -12
  36. package/dist/bin/chunk-kjbkwzxd.js +1 -0
  37. package/dist/bin/chunk-knthwdhz.js +1 -0
  38. package/dist/bin/{chunk-31tmm8kx.js → chunk-m2kr333s.js} +2 -2
  39. package/dist/bin/chunk-m5wc1ent.js +1 -0
  40. package/dist/bin/{chunk-s4z1knq4.js → chunk-n02421y9.js} +1 -1
  41. package/dist/bin/{chunk-8t0mrz5d.js → chunk-nm000jpj.js} +48 -48
  42. package/dist/bin/{chunk-kft7wdhy.js → chunk-pd8tk3z5.js} +1 -1
  43. package/dist/bin/chunk-pjgbnk3q.js +1 -0
  44. package/dist/bin/chunk-rn0pgnt4.js +1 -0
  45. package/dist/bin/{chunk-hdr0q89a.js → chunk-tc24txss.js} +5 -5
  46. package/dist/bin/{chunk-nazx54p5.js → chunk-tfasfg4a.js} +2 -2
  47. package/dist/bin/{chunk-r0qynqff.js → chunk-tvv6vdx6.js} +5 -5
  48. package/dist/bin/chunk-v93xyx1p.js +1 -0
  49. package/dist/bin/chunk-vx9mmpaz.js +1 -0
  50. package/dist/bin/{chunk-me81g606.js → chunk-vx9qk1g1.js} +1 -1
  51. package/dist/bin/{chunk-trdteh51.js → chunk-whww424p.js} +47 -47
  52. package/dist/bin/chunk-xtzy90zh.js +1 -0
  53. package/dist/bin/{chunk-4nbq68h4.js → chunk-xxf1vhfr.js} +1 -1
  54. package/dist/bin/{chunk-2a8twtvv.js → chunk-y4c26gaf.js} +1 -1
  55. package/dist/bin/{chunk-9gcmpcmq.js → chunk-yk4p2k8w.js} +1 -1
  56. package/dist/bin/chunk-z6mnhd0j.js +1 -0
  57. package/dist/bin/{chunk-4mpfdw94.js → chunk-zacbzz1w.js} +2 -2
  58. package/dist/bin/{chunk-3d8y4a6d.js → chunk-zzmk290g.js} +109 -109
  59. package/dist/bin/cli.js +150 -150
  60. package/dist/bin/dashboard-server.js +1 -1
  61. package/dist/chunk-051jwkd2.js +1 -0
  62. package/dist/{chunk-2rt6xbmv.js → chunk-0bbrbzf9.js} +4 -4
  63. package/dist/chunk-1gne7rkf.js +1 -0
  64. package/dist/chunk-38c310s1.js +1 -0
  65. package/dist/{chunk-80vxhxt5.js → chunk-4twnkjyq.js} +2 -2
  66. package/dist/{chunk-dns94gs7.js → chunk-4xta1s4z.js} +1 -1
  67. package/dist/{chunk-dxcwfj3h.js → chunk-6eq5xfcx.js} +1 -1
  68. package/dist/{chunk-g8tp1zj4.js → chunk-a21phhyj.js} +3 -3
  69. package/dist/{chunk-tznx5510.js → chunk-a6aw2jtz.js} +6 -6
  70. package/dist/{chunk-bd75na8x.js → chunk-acpxtkfy.js} +80 -80
  71. package/dist/chunk-dk3t3hgq.js +1 -0
  72. package/dist/{chunk-21b8nage.js → chunk-emx1j2yt.js} +1 -1
  73. package/dist/{chunk-pc0tz6be.js → chunk-fdn4wnd8.js} +7 -7
  74. package/dist/{chunk-fs78rxy1.js → chunk-fz70vxrk.js} +3 -3
  75. package/dist/{chunk-22ybphxa.js → chunk-g0yyw5k8.js} +1 -1
  76. package/dist/{chunk-pwpd6jt2.js → chunk-gn42mekr.js} +1 -1
  77. package/dist/{chunk-97a7sxpe.js → chunk-gstz8w2d.js} +2 -2
  78. package/dist/{chunk-s1bfyvmc.js → chunk-jgv0x24e.js} +1 -1
  79. package/dist/{chunk-42ngwzvc.js → chunk-jncbm332.js} +104 -104
  80. package/dist/{chunk-9be2pb0b.js → chunk-pekptc1b.js} +5 -5
  81. package/dist/chunk-qc2v4h2q.js +1 -0
  82. package/dist/{chunk-y59rkb2n.js → chunk-rgw06xbk.js} +4 -4
  83. package/dist/{chunk-8x24tv2g.js → chunk-rmn71xjb.js} +17 -17
  84. package/dist/{chunk-p0w0kwhx.js → chunk-sm5rn3db.js} +19 -19
  85. package/dist/{chunk-8a02v9gs.js → chunk-ss4q8kge.js} +2 -2
  86. package/dist/{chunk-ht8rawp1.js → chunk-v9t92ak2.js} +2 -2
  87. package/dist/{chunk-kx7zw3xn.js → chunk-wdrqt329.js} +84 -84
  88. package/dist/{chunk-9nxb5fyp.js → chunk-whwg2nzb.js} +5 -5
  89. package/dist/{chunk-sw1p9qge.js → chunk-yxn6tpbg.js} +1 -1
  90. package/dist/{chunk-3bz7xz2d.js → chunk-z87dekhm.js} +1 -1
  91. package/dist/deploy/index.js +1 -1
  92. package/dist/dns/index.js +1 -1
  93. package/dist/drivers/index.js +1 -1
  94. package/dist/drivers/shared/cloudfront-origin.d.ts +15 -26
  95. package/dist/index.js +20 -20
  96. package/dist/operations/index.js +1 -1
  97. package/dist/protection/index.js +1 -1
  98. package/dist/spend/index.js +1 -1
  99. package/dist/ui/404.html +1 -1
  100. package/dist/ui/accept-invitation.html +1 -1
  101. package/dist/ui/access-denied.html +1 -1
  102. package/dist/ui/account/automation.html +5 -5
  103. package/dist/ui/account/security.html +1 -1
  104. package/dist/ui/applications/compose.html +5 -5
  105. package/dist/ui/applications/new.html +1 -1
  106. package/dist/ui/data/backups.html +5 -5
  107. package/dist/ui/data/services.html +6 -6
  108. package/dist/ui/data/volumes.html +6 -6
  109. package/dist/ui/index.html +6 -6
  110. package/dist/ui/infrastructure/topology.html +5 -5
  111. package/dist/ui/integrations.html +2 -2
  112. package/dist/ui/operations/alerts.html +6 -6
  113. package/dist/ui/operations/configuration.html +6 -6
  114. package/dist/ui/operations/jobs.html +6 -6
  115. package/dist/ui/operations/maintenance.html +6 -6
  116. package/dist/ui/operations/observability.html +6 -6
  117. package/dist/ui/operations/previews.html +6 -6
  118. package/dist/ui/operations/queue.html +6 -6
  119. package/dist/ui/operations/regions.html +6 -6
  120. package/dist/ui/operations/releases.html +6 -6
  121. package/dist/ui/operations/spend.html +6 -6
  122. package/dist/ui/operations/workloads.html +5 -5
  123. package/dist/ui/security.html +2 -2
  124. package/dist/ui/server/actions.html +6 -6
  125. package/dist/ui/server/activity.html +2 -2
  126. package/dist/ui/server/capacity.html +6 -6
  127. package/dist/ui/server/database.html +6 -6
  128. package/dist/ui/server/deployments.html +6 -6
  129. package/dist/ui/server/diagnostics.html +2 -2
  130. package/dist/ui/server/firewall.html +6 -6
  131. package/dist/ui/server/fleet.html +6 -6
  132. package/dist/ui/server/logs.html +6 -6
  133. package/dist/ui/server/metrics.html +6 -6
  134. package/dist/ui/server/security.html +1 -1
  135. package/dist/ui/server/services.html +2 -2
  136. package/dist/ui/server/sites.html +6 -6
  137. package/dist/ui/server/ssh-keys.html +6 -6
  138. package/dist/ui/server/team.html +6 -6
  139. package/dist/ui/server/terminal.html +1 -1
  140. package/dist/ui/serverless/alarms.html +5 -5
  141. package/dist/ui/serverless/assets.html +2 -2
  142. package/dist/ui/serverless/cost.html +2 -2
  143. package/dist/ui/serverless/data.html +6 -6
  144. package/dist/ui/serverless/deployments.html +2 -2
  145. package/dist/ui/serverless/firewall.html +2 -2
  146. package/dist/ui/serverless/functions.html +6 -6
  147. package/dist/ui/serverless/logs.html +5 -5
  148. package/dist/ui/serverless/metrics.html +2 -2
  149. package/dist/ui/serverless/queues.html +5 -5
  150. package/dist/ui/serverless/secrets.html +5 -5
  151. package/dist/ui/serverless/traces.html +6 -6
  152. package/dist/ui/serverless.html +6 -6
  153. package/package.json +3 -3
  154. package/dist/bin/chunk-01tmdqe3.js +0 -1
  155. package/dist/bin/chunk-3bwy7atq.js +0 -1
  156. package/dist/bin/chunk-3rsvrp09.js +0 -1
  157. package/dist/bin/chunk-4gf4mk0b.js +0 -1
  158. package/dist/bin/chunk-5wms0mx3.js +0 -1
  159. package/dist/bin/chunk-c7sqa85j.js +0 -1
  160. package/dist/bin/chunk-cejjg0ts.js +0 -1
  161. package/dist/bin/chunk-e3hn6atg.js +0 -1
  162. package/dist/bin/chunk-fbq61aj0.js +0 -1
  163. package/dist/bin/chunk-g4dytx12.js +0 -1
  164. package/dist/bin/chunk-hssaw82j.js +0 -1
  165. package/dist/bin/chunk-k4x1pq4t.js +0 -1
  166. package/dist/bin/chunk-kcvvpvte.js +0 -1
  167. package/dist/bin/chunk-n8a76gys.js +0 -1
  168. package/dist/bin/chunk-p1k08e45.js +0 -1
  169. package/dist/bin/chunk-ps8ev3tq.js +0 -1
  170. package/dist/bin/chunk-q8s9v9hv.js +0 -1
  171. package/dist/bin/chunk-qcvmyfp7.js +0 -1
  172. package/dist/bin/chunk-qncvqmzy.js +0 -1
  173. package/dist/bin/chunk-r35q7kve.js +0 -1
  174. package/dist/bin/chunk-rt9nbrwd.js +0 -1
  175. package/dist/bin/chunk-xhwjntw1.js +0 -1
  176. package/dist/chunk-29xhksd3.js +0 -1
  177. package/dist/chunk-2vgdfywj.js +0 -1
  178. package/dist/chunk-67wrhk75.js +0 -1
  179. package/dist/chunk-7nq2rwjs.js +0 -1
  180. package/dist/chunk-gj27zyk5.js +0 -1
package/dist/aws/index.js CHANGED
@@ -1 +1 @@
1
- import{ge,Xt,Yi,Zi,Zl,Ra,Da,es,ts,Pa,Xe,V,Ye,ne,C,me,an,Na,ke,ka,cn,dn,ln,Mm,Fm,QA,HA,GA,qA,Ct,VA,jA,zA,KA,Et,Um,Qm,Hm,bt,Gm,qm,Vm,un,WA,JA,XA,Yt,YA,ZA,ey,Ba,_a,eu,ty,ry,ny,Zt,jm,zm,er,Ze,pn,xa,tu,iy,ru,sy,vt,oy,ay,cy,dy,ie,ly,uy,py,gy,tr,my,hy,fy,gn,Oa,La,nu,iu,$a,rr}from"../chunk-tznx5510.js";import{he,et,mn,Km}from"../chunk-g8tp1zj4.js";import{A}from"../chunk-sw1p9qge.js";import{Be}from"../chunk-dns94gs7.js";import{j}from"../chunk-dxcwfj3h.js";import{tt,se,_e,fe,Tt,fn,ns,is,nr,ir,An,sr,ss,os,as,cs,z,ds,ls,us,ps,oe,gs,ms,hs,T,Ua,yn,Qa,ae,or}from"../chunk-ht8rawp1.js";import{y}from"../chunk-21b8nage.js";import{Ar,Ee}from"../chunk-fs78rxy1.js";import{h}from"../chunk-22ybphxa.js";import{a}from"../chunk-3bz7xz2d.js";import{yr,n,l,gh}from"../chunk-8a02v9gs.js";export{ae as ACMClient,or as ACMDnsValidator,n as AWSClient,xa as ApplicationAutoScalingClient,Xt as AwsBackupClient,Fm as BedrockAgentClient,Mm as BedrockAgentRuntimeClient,ln as BedrockClient,dn as BedrockRuntimeClient,h as CloudFormationClient,A as CloudFrontClient,me as CloudWatchLogsClient,fe as CloudflareProvider,Ct as ComprehendClient,an as ConnectClient,ts as CostExplorerClient,yn as DnsProviderFactory,ke as DynamoDBClient,Ar as EC2Client,Be as ECRClient,Xe as ECSClient,rr as EFSClient,Na as ELBv2Client,Ze as ElastiCacheClient,mn as EmailClient,er as EventBridgeClient,_e as GoDaddyProvider,he as IAMClient,tu as ImapServer,Zt as KendraClient,C as LambdaClient,ka as OpenSearchClient,tt as PROXIABLE_RECORD_TYPES,Ba as PersonalizeClient,eu as PersonalizeEventsClient,_a as PersonalizeRuntimeClient,un as PollyClient,se as PorkbunProvider,j as RDSClient,Et as RekognitionClient,y as Route53Client,Pa as Route53DomainsClient,z as Route53Provider,a as S3Client,et as SESClient,Ye as SNSClient,ne as SQSClient,Ee as SSMClient,ge as STSClient,pn as SchedulerClient,V as SecretsManagerClient,vt as SmsClient,$a as SmsVoiceClient,ru as SmtpServer,gn as SupportClient,Oa as SupportTemplates,bt as TextractClient,cn as TranscribeClient,Yt as TranslateClient,oe as UnifiedDnsValidator,tr as VoiceClient,VA as analyzeSentiment,as as applyDeclaredZoneSettings,us as applyZoneMigration,l as buildQueryParams,GA as completeWithClaude,KA as containsPii,Qm as countFacesInS3Image,dy as createDeliveryReceiptHandler,T as createDnsProvider,ms as createGoDaddyValidator,es as createObjectStorageClient,gs as createPorkbunValidator,hy as createRecordingHandler,hs as createRoute53Validator,XA as createSSML,ay as createScheduledSmsHandler,cy as createSmsClient,oy as createSmsInboxHandler,iu as createSmsInfrastructure,fy as createVoiceClient,my as createVoicemailHandler,sr as delegateZone,ss as delegateZoneFromConfig,os as describeDelegation,cs as describeZoneSettings,gh as detectCredentialSource,Ua as detectDnsProvider,Um as detectLabelsFromS3,zA as detectLanguage,Qa as dnsProviders,Km as email,ds as exportRoute53Zone,jA as extractEntities,qm as extractFormsFromS3,Vm as extractTablesFromS3,Gm as extractTextFromS3,ly as formatPhoneNumber,qA as generateEmbeddings,py as getCountryCode,ty as getRecommendations,ry as getSimilarItems,nu as getSmsInfrastructureStatus,Hm as isContentSafe,nr as isNameserverRegistrar,gy as isSamePhoneNumber,uy as isValidPhoneNumber,ir as isZoneHost,Zi as keyMatchesFilters,HA as listClaudeModels,ey as listLanguages,JA as listVoices,Zl as migrateObjectStorage,ie as normalizePhoneNumber,ls as planZoneMigration,Tt as policyTag,Ra as providerEndpoint,fn as qualifyName,is as reconcileDeclaredRecords,Yi as remapKey,QA as requestModelAccess,ns as resolveDeclaredRecords,Da as resolveObjectStorage,yr as resolveS3Endpoint,zm as retrieveForRag,An as sameNameservers,jm as search,La as setupSmsInfrastructure,iy as startImapServer,sy as startSmtpServer,WA as textToSpeech,ny as trackEvent,YA as translate,ZA as translateToMultiple,ps as verifyZoneParity};
1
+ import{me,Xt,es,ts,nu,Pa,Na,rs,ns,ka,Xe,V,Ye,ne,C,he,cn,Ba,ke,_a,dn,ln,un,Km,Wm,WA,JA,XA,YA,Ct,ZA,ey,ty,ry,Et,Jm,Xm,Ym,bt,Zm,eh,th,pn,ny,iy,sy,Yt,oy,ay,cy,xa,Oa,iu,dy,ly,uy,Zt,rh,nh,er,Ze,gn,La,su,py,ou,gy,vt,my,hy,fy,Ay,ie,yy,Iy,Sy,Cy,tr,Ey,by,vy,mn,$a,Ma,au,cu,Fa,rr}from"../chunk-a6aw2jtz.js";import{fe,et,hn,ih}from"../chunk-a21phhyj.js";import{A}from"../chunk-yxn6tpbg.js";import{Be}from"../chunk-4xta1s4z.js";import{j}from"../chunk-6eq5xfcx.js";import{tt,se,_e,Ae,Tt,An,ss,os,nr,ir,yn,sr,as,cs,ds,ls,z,us,ps,gs,ms,oe,hs,fs,As,T,Ha,In,Ga,ae,or}from"../chunk-v9t92ak2.js";import{y}from"../chunk-emx1j2yt.js";import{Ar,be}from"../chunk-fz70vxrk.js";import{h}from"../chunk-g0yyw5k8.js";import{a}from"../chunk-z87dekhm.js";import{yr,n,l,Sh}from"../chunk-ss4q8kge.js";export{ae as ACMClient,or as ACMDnsValidator,n as AWSClient,La as ApplicationAutoScalingClient,Xt as AwsBackupClient,Wm as BedrockAgentClient,Km as BedrockAgentRuntimeClient,un as BedrockClient,ln as BedrockRuntimeClient,h as CloudFormationClient,A as CloudFrontClient,he as CloudWatchLogsClient,Ae as CloudflareProvider,Ct as ComprehendClient,cn as ConnectClient,ns as CostExplorerClient,In as DnsProviderFactory,ke as DynamoDBClient,Ar as EC2Client,Be as ECRClient,Xe as ECSClient,rr as EFSClient,Ba as ELBv2Client,Ze as ElastiCacheClient,hn as EmailClient,er as EventBridgeClient,_e as GoDaddyProvider,fe as IAMClient,su as ImapServer,Zt as KendraClient,C as LambdaClient,_a as OpenSearchClient,tt as PROXIABLE_RECORD_TYPES,xa as PersonalizeClient,iu as PersonalizeEventsClient,Oa as PersonalizeRuntimeClient,pn as PollyClient,se as PorkbunProvider,j as RDSClient,Et as RekognitionClient,y as Route53Client,ka as Route53DomainsClient,z as Route53Provider,a as S3Client,et as SESClient,Ye as SNSClient,ne as SQSClient,be as SSMClient,me as STSClient,gn as SchedulerClient,V as SecretsManagerClient,vt as SmsClient,Fa as SmsVoiceClient,ou as SmtpServer,mn as SupportClient,$a as SupportTemplates,bt as TextractClient,dn as TranscribeClient,Yt as TranslateClient,oe as UnifiedDnsValidator,tr as VoiceClient,ZA as analyzeSentiment,ds as applyDeclaredZoneSettings,gs as applyZoneMigration,l as buildQueryParams,XA as completeWithClaude,ry as containsPii,Xm as countFacesInS3Image,Ay as createDeliveryReceiptHandler,T as createDnsProvider,fs as createGoDaddyValidator,rs as createObjectStorageClient,hs as createPorkbunValidator,by as createRecordingHandler,As as createRoute53Validator,sy as createSSML,hy as createScheduledSmsHandler,fy as createSmsClient,my as createSmsInboxHandler,cu as createSmsInfrastructure,vy as createVoiceClient,Ey as createVoicemailHandler,sr as delegateZone,as as delegateZoneFromConfig,cs as describeDelegation,ls as describeZoneSettings,Sh as detectCredentialSource,Ha as detectDnsProvider,Jm as detectLabelsFromS3,ty as detectLanguage,Ga as dnsProviders,ih as email,us as exportRoute53Zone,ey as extractEntities,eh as extractFormsFromS3,th as extractTablesFromS3,Zm as extractTextFromS3,yy as formatPhoneNumber,YA as generateEmbeddings,Sy as getCountryCode,dy as getRecommendations,ly as getSimilarItems,au as getSmsInfrastructureStatus,Ym as isContentSafe,nr as isNameserverRegistrar,Cy as isSamePhoneNumber,Iy as isValidPhoneNumber,ir as isZoneHost,ts as keyMatchesFilters,JA as listClaudeModels,cy as listLanguages,iy as listVoices,nu as migrateObjectStorage,ie as normalizePhoneNumber,ps as planZoneMigration,Tt as policyTag,Pa as providerEndpoint,An as qualifyName,os as reconcileDeclaredRecords,es as remapKey,WA as requestModelAccess,ss as resolveDeclaredRecords,Na as resolveObjectStorage,yr as resolveS3Endpoint,nh as retrieveForRag,yn as sameNameservers,rh as search,Ma as setupSmsInfrastructure,py as startImapServer,gy as startSmtpServer,ny as textToSpeech,uy as trackEvent,oy as translate,ay as translateToMultiple,ms as verifyZoneParity};
@@ -1,8 +1,8 @@
1
- var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function We(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function ss(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?La(n.path):".*";if(!ss(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${We(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${We(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${We(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${We(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${We(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function La(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function ei(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
1
+ var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function Ge(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function cs(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?Fa(n.path):".*";if(!cs(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${Ge(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Ge(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Ge(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${Ge(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${Ge(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function Fa(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function ei(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
2
2
  `)}
3
- `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${We(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=La(a);if(!ss(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${We(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${We(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${We(a.reason)}`),a.pathPattern){if(!ss(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${We(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
3
+ `,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${Ge(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=Fa(a);if(!cs(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${Ge(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${Ge(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${Ge(a.reason)}`),a.pathPattern){if(!cs(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${Ge(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
4
4
  `)}
5
- `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function as(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=ei(e,r);return`#!/usr/bin/env bash
5
+ `,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function ls(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=ei(e,r);return`#!/usr/bin/env bash
6
6
  # Managed by ts-cloud. Installs the zig-waf ruleset.
7
7
  set -euo pipefail
8
8
 
@@ -33,5 +33,5 @@ fi
33
33
 
34
34
  mv "${s}.new" "${s}"
35
35
  echo "ts-cloud: WAF config installed (mode: ${n.mode})"
36
- `}function Du(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
- export{We,ss,La,ei,as,Du};
36
+ `}function Uu(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
37
+ export{Ge,cs,Fa,ei,ls,Uu};
@@ -1,4 +1,4 @@
1
- import{U}from"./chunk-3d8y4a6d.js";function g(t){let e=t.sites||{};for(let r of Object.values(e))if(r?.repository?.url)return{provider:r.repository.provider,branch:r.repository.branch};return}function m(t){let e=t.trim().toLowerCase();if(e.includes("github.com"))return"github";if(e.includes("gitlab.com"))return"gitlab";if(e.includes("bitbucket.org"))return"bitbucket";return}function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function E(t){return t.replace(/'/g,"''")}function _(t,e){let r=["bunx --bun @stacksjs/ts-cloud deploy","--env",a(t)];if(e.site)r.push("--site",a(e.site));if(e.skipDnsVerification)r.push("--skip-dns-verification");return r.push("--yes"),r.join(" ")}function v(t,e="production",r={}){let l=g(t),n=r.provider||l?.provider;if(n!=="github"&&n!=="gitlab"&&n!=="bitbucket")return null;let i=t.environments?.[e],s=i?.deployBranch||l?.branch||"main",u=_(e,r),c=JSON.stringify(s),d=JSON.stringify(e),p=i?.domain?i.domain.startsWith("http")?i.domain:`https://${i.domain}`:void 0,f=p?`
1
+ import{U}from"./chunk-zzmk290g.js";function g(t){let e=t.sites||{};for(let r of Object.values(e))if(r?.repository?.url)return{provider:r.repository.provider,branch:r.repository.branch};return}function m(t){let e=t.trim().toLowerCase();if(e.includes("github.com"))return"github";if(e.includes("gitlab.com"))return"gitlab";if(e.includes("bitbucket.org"))return"bitbucket";return}function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function E(t){return t.replace(/'/g,"''")}function _(t,e){let r=["bunx --bun @stacksjs/ts-cloud deploy","--env",a(t)];if(e.site)r.push("--site",a(e.site));if(e.skipDnsVerification)r.push("--skip-dns-verification");return r.push("--yes"),r.join(" ")}function v(t,e="production",r={}){let l=g(t),n=r.provider||l?.provider;if(n!=="github"&&n!=="gitlab"&&n!=="bitbucket")return null;let i=t.environments?.[e],s=i?.deployBranch||l?.branch||"main",u=_(e,r),c=JSON.stringify(s),d=JSON.stringify(e),p=i?.domain?i.domain.startsWith("http")?i.domain:`https://${i.domain}`:void 0,f=p?`
2
2
  url: ${JSON.stringify(p)}`:"",h=r.setup==="pantry"?` - name: Setup Pantry
3
3
  uses: home-lang/pantry/packages/action@main`:` - uses: oven-sh/setup-bun@v2
4
4
  - run: bun install --frozen-lockfile`,y=U(t)==="hetzner"&&!!t.infrastructure?.compute,o=r.sshPrivateKeySecret||"SSH_PRIVATE_KEY";if(!/^[A-Z_][A-Z0-9_]*$/i.test(o))throw Error(`Invalid SSH private key secret name '${o}'`);let b=y?`
@@ -1,4 +1,4 @@
1
- import{di,u}from"./chunk-cb47f0pb.js";import{li}from"./chunk-31tmm8kx.js";import*as c from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as U}from"node:fs/promises";import{join as L}from"node:path";function St(e){if(e){let r=R(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return R(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function R(e){let{existsSync:t,readFileSync:s}=li("node:fs"),{homedir:r}=li("node:os"),{join:n}=li("node:path"),i=process.env.AWS_SHARED_CREDENTIALS_FILE||n(r(),".aws","credentials");if(!t(i))return null;let o=s(i,"utf-8"),a=null,g,l,h;for(let d of o.split(`
1
+ import{di,u}from"./chunk-cs6a98r1.js";import{li}from"./chunk-m2kr333s.js";import*as c from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as U}from"node:fs/promises";import{join as L}from"node:path";function St(e){if(e){let r=R(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return R(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function R(e){let{existsSync:t,readFileSync:s}=li("node:fs"),{homedir:r}=li("node:os"),{join:n}=li("node:path"),i=process.env.AWS_SHARED_CREDENTIALS_FILE||n(r(),".aws","credentials");if(!t(i))return null;let o=s(i,"utf-8"),a=null,g,l,h;for(let d of o.split(`
2
2
  `)){let p=d.trim();if(!p||p.startsWith("#")||p.startsWith(";"))continue;let y=p.match(/^\[([^\]]+)\]$/);if(y){if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:h};a=y[1],g=void 0,l=void 0,h=void 0;continue}if(a===e){let[b,...S]=p.split("="),m=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":g=m;break;case"aws_secret_access_key":l=m;break;case"aws_session_token":h=m;break}}}if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:h};return null}function B(e){let{buffer:t,byteOffset:s,byteLength:r}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+r);let n=new ArrayBuffer(r);return new Uint8Array(n).set(new Uint8Array(e)),n}class f{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let r=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",i=typeof e==="string"?t:e.profile,o=r?.endpoint?di({region:n,path:"/",endpoint:r.endpoint}):void 0;this.region=n,this.explicitProfile=i,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=r?.forcePathStyle,this.explicitCredentials=r?.credentials,this.client=new u(r?.credentials,{profile:i,endpoint:r?.endpoint,forcePathStyle:r?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=St(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],r=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(r){let n=Array.isArray(r)?r:[r];for(let i of n)t.push({Name:i.Name,CreationDate:i.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let r;if(this.region!=="us-east-1"&&!this.endpoint)r=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
4
4
  <LocationConstraint>${this.region}</LocationConstraint>
@@ -0,0 +1 @@
1
+ import{ue}from"./chunk-fjz07v7g.js";import"./chunk-cs6a98r1.js";export{ue as RDSClient};
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-cb47f0pb.js";import{M}from"./chunk-kft7wdhy.js";var S=new Set(["A","AAAA","CNAME"]);function E(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function P(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((s)=>setTimeout(s,o))}class Ge{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let n=1;n<=8;n+=1){let o,s=new AbortController,i=setTimeout(()=>{s.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:s.signal})}catch(c){if(r=c,n===8)throw c;await P(n);continue}finally{clearTimeout(i)}if(!o.ok){let c=await o.clone().json().then((d)=>d?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${c?`: ${c}`:""}`),!E(o.status)||n===8)throw r;await P(n,o);continue}let a=await o.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!E(0,a.message)||n===8)throw r;await P(n,o);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!Ge.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let s=[];for(let i of o.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)s.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return s}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((s)=>s.type===t.type&&this.getSubdomain(s.name,r)===n&&s.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)o.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let s=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,o);if(Ge.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${s.length>0?` (${s.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(s?.id&&s.content===t.content&&(t.ttl===void 0||s.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||s.priority===t.priority))return{success:!0,id:s.id,message:"Record already up to date"};if(s?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${s.id}`,i),{success:!0,id:s.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!s?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${s.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class _t{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let n=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let i=await fetch(n,s);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),o={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),s=o.filter((i)=>i.data!==t.content);if(s.length===o.length)return{success:!1,message:"Record not found"};if(s.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,s);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((s)=>this.fromGoDaddyRecord(s,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var j=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],H=[{name:"x-stx-router",value:"true"}];function y(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function x(e){return`{${e.map(y).join(" ")}}`}function F(e){let t=`http.request.headers[${y(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${y(e.value)})`}function D(e){if(e.length===1)return`http.host eq ${y(e[0])}`;return`http.host in ${x(e)}`}function cs(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=D(e),n=[],s=(t.bypassPaths??[]).map((U)=>`starts_with(http.request.uri.path, ${y(U)})`),a=(t.negotiatedRequestHeaders??H).map(F),c=[...s,...a],d=c.length>0?`(${c.join(" or ")})`:void 0;if(d)n.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${d})`,enabled:!0,action_parameters:{cache:!1}});let g=d?`${r} and not ${d}`:r,p=t.assetExtensions??j,l=p.length>0?`lower(http.request.uri.path.extension) in ${x([...p])}`:void 0;if(l)n.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${l})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let R=l?`(${g} and not ${l})`:`(${g})`;if(t.documentEdgeTtl===0)return n.push({action:"set_cache_settings",description:"bypass documents",expression:R,enabled:!0,action_parameters:{cache:!1}}),n;return n.push({action:"set_cache_settings",description:"cache documents",expression:R,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),n}function ls(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${D(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var G="https://api.cloudflare.com/client/v4",T="[ts-cloud]";class Ke{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let n=`${G}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let a=await(await fetch(n,s)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let s=o.result[0].id;return this.zoneCache.set(r,s),{id:s,name:o.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&S.has(e.type)){if(n.proxied=o,o)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let s=W(e);if(s)n.data=s,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),n=this.getFullRecordName(t.name,r.name),s=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??s?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(s)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${s.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!s.result||s.result.length===0)return{success:!1,message:"Record not found"};let i=s.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let o=[],s=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${s}`);if(o.push(...a.result||[]),a.result_info)i=s<a.result_info.total_pages,s++;else i=!1}return{success:!0,records:o.map((a)=>this.fromCloudflareRecord(a))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(s){let i=s instanceof Error?s.message:String(s);if(!/already exists|1061/i.test(i))throw s;let a=await this.getZoneDetails(r);if(!a)throw s;return{...a,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),n=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let s of o.hosts||[])n.add(s.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(s.result&&s.result.length>0)return s.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),o=n.id,s=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${a.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),n={};for(let o of r.result||[])n[o.id]=o.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),o=[],s=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&b(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),o.push({id:i,from:c,to:a})}catch(d){s.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:o,failed:s}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),n={};for(let o of r.result?.managed_request_headers||[])n[o.id]=o.enabled===!0;return n}async applyManagedRequestHeaders(e,t){let r=[],n=[],o=Object.entries(t).filter(([,c])=>c!==void 0);if(o.length===0)return{changed:r,failed:n};let s=await this.getZoneId(e),i;try{i=await this.getManagedRequestHeaders(e)}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of o)n.push({id:g,error:`could not read managed headers — ${d}`});return{changed:r,failed:n}}let a=[];for(let[c,d]of o){if(!(c in i)){n.push({id:c,error:"not a managed request header transform on this zone"});continue}if(i[c]!==d)a.push([c,d])}if(a.length===0)return{changed:r,failed:n};try{await this.request("PATCH",`/zones/${s}/managed_headers`,{managed_request_headers:a.map(([c,d])=>({id:c,enabled:d})),managed_response_headers:[]});for(let[c,d]of a)r.push({id:c,from:i[c],to:d})}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of a)n.push({id:g,error:d})}return{changed:r,failed:n}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let n=await this.getZoneId(e),o=await this.getPhaseRules(e,t),s=r.map((c)=>({...c,description:c.description?.startsWith(T)?c.description:`${T} ${c.description||t}`})),a=B(o,s).map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}var N=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function _(e){return N.test(e)?e.replace(N,"\x00hosts\x00"):null}function k(e,t){return e.replace(N,D(t))}function w(e){if(Array.isArray(e))return`[${e.map(w).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${w(n)}`).join(",")}}`;return JSON.stringify(e)}function K(e,t){let r=_(e.expression);return r!==null&&r===_(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&w(e.action_parameters)===w(t.action_parameters)}function B(e,t){let r=new Set(t.flatMap((s)=>v(s.expression))),n=(s)=>(s.description||"").startsWith(T),o=[];for(let s of e){if(!n(s)){o.push(s);continue}let i=v(s.expression);if(i.length===0){if(r.size>0)o.push(s);continue}let a=i.filter((c)=>!r.has(c));if(a.length===i.length)o.push(s);else if(a.length>0)o.push({...s,expression:k(s.expression,a)})}for(let s of t){let i=v(s.expression),a=i.length>0?o.findIndex((g)=>n(g)&&K(g,s)):-1;if(a===-1){o.push(s);continue}let c=o[a],d=[...new Set([...v(c.expression),...i])];o[a]={...c,expression:k(c.expression,d)}}return o}function v(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let n of r[1].matchAll(/"([^"]+)"/g))t.push(n[1]);return t}function b(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((o,s)=>b(o,t[s]))}let r=e,n=t;return Object.keys(n).every((o)=>b(r[o],n[o]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:V(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,o,s]=r.slice(0,3).map(Number);if(![n,o,s].every(Number.isFinite))return null;return{priority:n,weight:o,port:s,target:V(r.slice(3).join(" "))}}function V(e){return e.replace(/\.$/,"")}var X=new Set(["A","AAAA","CNAME","ALIAS"]);function A(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function Z(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let o=h(n);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function Ki(e,t){return e.map((r)=>({...r,name:Z(r.name,t),proxied:r.proxied??!1}))}function Y(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(X.has(t.type))return!0;if(t.type==="TXT"){let r=A(t.content);if(r)return A(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function J(e,t){if(f(e.content)!==f(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Ji(e){let{provider:t,zone:r,records:n}=e,o={outcomes:[],warnings:[]};if(n.length===0)return o;let s=await t.listRecords(r);if(!s.success)return o.warnings.push(`could not list ${r}: ${s.message||"unknown provider error"} — records not reconciled`),o;let i=s.records;for(let a of n){let c=i.filter((l)=>Y(l,a));if(c.length>0&&c.every((l)=>J(l,a))){o.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},g=a.type==="TXT"&&A(a.content)!==void 0;if(g)for(let l of c){let R=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!R.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${R.message||"unknown error"}`)}let p=g||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)o.outcomes.push({record:a,action:c.length>0?"updated":"created"});else o.outcomes.push({record:a,action:"failed",message:p.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let g=new Set(n.filter((l)=>l.type===a&&h(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&h(l.name)===d&&!g.has(f(l.content).toLowerCase()));for(let l of p)o.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class Gr{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new M(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let n=await this.client.findHostedZoneForDomain(e);if(n){let o=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=re(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?I(t)===I(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((s)=>s.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(s?.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already present"};let i=[...s?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:s?"UPSERT":"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s?.ttl??t.ttl??300,ResourceRecords:i.map((c)=>({Value:c}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),o=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(!s||!s.values.some((a)=>this.sameValue(t.type,a,o)))return{success:!0,message:"Record already absent"};let i=s.values.filter((a)=>!this.sameValue(t.type,a,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:i.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s.ttl,ResourceRecords:(i.length>0?i:s.values).map((a)=>({Value:a}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let s of n.ResourceRecordSets){if(t&&s.Type!==t)continue;if(s.AliasTarget)continue;for(let i of s.ResourceRecords||[]){let a=i.Value,c;if(s.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(s.Type==="TXT"&&a.startsWith('"'))a=I(a);o.push({name:s.Name.replace(/\.$/,""),type:s.Type,content:a,ttl:s.TTL,priority:c})}}return{success:!0,records:o}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:M.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=M.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var z=255;function re(e){let t=[];for(let r=0;r<e.length;r+=z)t.push(e.slice(r,r+z));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function I(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&n+1<e.length){t+=e[++n];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function Xi(e,t){let r=[],n,o;for(;;){let s=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:o,MaxItems:"100"});if(r.push(...s.ResourceRecordSets),!s.IsTruncated)break;if(n=s.NextRecordName,o=s.NextRecordType,!n)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function C(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function ne(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Qi(e,t){let r=m(t),n=[],o=[],s=[],i=new Set;for(let a of e){let c=m(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){o.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){o.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),s.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let g=m(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:g,ttl:300,translatedFrom:`${d} ALIAS → ${g}`}),a.AliasTarget.EvaluateTargetHealth)s.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of a.ResourceRecords||[]){let p=se(c,d,g.Value,a.TTL);if("reason"in p){o.push({name:c,type:d,reason:p.reason}),s.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:o,warnings:s}}function se(e,t,r,n){let o={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:ne(r)};case"MX":{let[s,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(i.join(" ")),priority:Number(s)}}case"SRV":{let s=r.trim().split(/\s+/);if(s.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=s.slice(0,3).map(Number);return{...o,type:"SRV",content:m(s.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var oe=new Set(["TXT","MX","SRV","NS","CAA"]);async function Yi(e,t){let r=[],n=[],o=new Set;try{let s=await e.listRecords(t.zone);for(let i of s.records||[])o.add(`${m(i.name)}|${i.type}|${C(i)}`)}catch{}for(let s of t.records){let i={...s,proxied:!1},a=`${m(s.name)}|${s.type}|${C(s)}`;if(!oe.has(s.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(s);else n.push({record:s,message:d.message||"unknown provider error"});continue}if(o.has(a)){r.push(s);continue}let c=await e.createRecord(t.zone,i);if(c.success)o.add(a),r.push(s);else n.push({record:s,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Zi(e,t){let r=await e.listRecords(t.zone),n=[],o=[],s=new Map;for(let i of r.records||[]){let a=`${m(i.name)}|${i.type}`,c=s.get(a)??[];c.push(C(i)),s.set(a,c)}for(let i of t.records){let a=s.get(`${m(i.name)}|${i.type}`),c=C(i);if(a?.some((d)=>d===c))n.push(i);else o.push({record:i,found:a?.join(", ")})}return{matched:n,missing:o,ok:o.length===0}}class $t{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new q(t),"provider"in e)this.dnsProvider=O(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:o=30}=e,{CertificateArn:s}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(s);let i=await this.acm.getDnsValidationRecords(s);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(s,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:s,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.upsertRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,records:o.map((s)=>({domainName:s.domainName,recordName:s.recordName,recordType:s.recordType,recordValue:s.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.deleteRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue});if(!i.success)n.push(`Failed to delete record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:o}=e,s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED"){let i=s.SubjectAlternativeNames||[s.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:s.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:n,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:o=[],waitForValidation:s=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:s})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function O(e){switch(e.provider){case"route53":return new Gr(e.region,e.hostedZoneId);case"porkbun":return new Ge(e.apiKey,e.secretKey);case"godaddy":return new _t(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new Ke(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class ti{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,n=process.env.GODADDY_API_SECRET;if(r&&n){let s=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,s)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((o)=>o.provider===e);if(!r)return null;let n=O(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=O(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>O(e))}}var ze=new ti;class q{client;region;constructor(e="us-east-1"){this.client=new u,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((n)=>({CertificateArn:n.CertificateArn,DomainName:n.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((n)=>n.DomainName===e||n.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let n=0;n<t;n++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((s)=>setTimeout(s,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let n=r.DomainName.slice(2),o=t.split("."),s=n.split(".");if(o.slice(-s.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let o=n.slice(2),s=t.split("."),i=o.split(".");if(s.slice(-i.length).join(".")===o)return!0}}return!1}}class eo{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new q(e),this.route53=new M,t&&t.provider!=="route53")this.dnsProvider=O(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:o=!1,maxWaitMinutes:s=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(i,s*2,30000))throw Error(`Certificate validation timed out after ${s} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),s=[];if(this.dnsProvider){let i=n||o[0]?.domainName;for(let a of o){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});s.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of o){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});s.push({...i,changeId:a.ChangeInfo?.Id})}return s}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let s=n||o[0]?.domainName;for(let i of o)try{await this.dnsProvider.deleteRecord(s,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let s of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${s.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s.recordName,Type:s.recordType,TTL:300,ResourceRecords:[{Value:s.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED")return{certificateArn:s.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
- export{Ge,_t,cs,ls,Ke,Ki,Ji,Gr,Xi,Qi,Yi,Zi,q,eo,$t,O,ti};
1
+ import{u}from"./chunk-cs6a98r1.js";import{M}from"./chunk-pd8tk3z5.js";var S=new Set(["A","AAAA","CNAME"]);function E(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function P(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((s)=>setTimeout(s,o))}class Ke{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let n=1;n<=8;n+=1){let o,s=new AbortController,i=setTimeout(()=>{s.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:s.signal})}catch(c){if(r=c,n===8)throw c;await P(n);continue}finally{clearTimeout(i)}if(!o.ok){let c=await o.clone().json().then((d)=>d?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${c?`: ${c}`:""}`),!E(o.status)||n===8)throw r;await P(n,o);continue}let a=await o.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!E(0,a.message)||n===8)throw r;await P(n,o);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!Ke.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let s=[];for(let i of o.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)s.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return s}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((s)=>s.type===t.type&&this.getSubdomain(s.name,r)===n&&s.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)o.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let s=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,o);if(Ke.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${s.length>0?` (${s.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(s?.id&&s.content===t.content&&(t.ttl===void 0||s.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||s.priority===t.priority))return{success:!0,id:s.id,message:"Record already up to date"};if(s?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${s.id}`,i),{success:!0,id:s.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!s?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${s.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class _t{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let n=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let i=await fetch(n,s);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=this.getSubdomain(e.name,r),o={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),s=o.filter((i)=>i.data!==t.content);if(s.length===o.length)return{success:!1,message:"Record not found"};if(s.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,s);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((s)=>this.fromGoDaddyRecord(s,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var j=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],H=[{name:"x-stx-router",value:"true"}];function y(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function x(e){return`{${e.map(y).join(" ")}}`}function F(e){let t=`http.request.headers[${y(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${y(e.value)})`}function D(e){if(e.length===1)return`http.host eq ${y(e[0])}`;return`http.host in ${x(e)}`}function ds(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=D(e),n=[],s=(t.bypassPaths??[]).map((U)=>`starts_with(http.request.uri.path, ${y(U)})`),a=(t.negotiatedRequestHeaders??H).map(F),c=[...s,...a],d=c.length>0?`(${c.join(" or ")})`:void 0;if(d)n.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${d})`,enabled:!0,action_parameters:{cache:!1}});let g=d?`${r} and not ${d}`:r,p=t.assetExtensions??j,l=p.length>0?`lower(http.request.uri.path.extension) in ${x([...p])}`:void 0;if(l)n.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${l})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let R=l?`(${g} and not ${l})`:`(${g})`;if(t.documentEdgeTtl===0)return n.push({action:"set_cache_settings",description:"bypass documents",expression:R,enabled:!0,action_parameters:{cache:!1}}),n;return n.push({action:"set_cache_settings",description:"cache documents",expression:R,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),n}function us(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${D(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var G="https://api.cloudflare.com/client/v4",T="[ts-cloud]";class Je{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let n=`${G}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let a=await(await fetch(n,s)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let s=o.result[0].id;return this.zoneCache.set(r,s),{id:s,name:o.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&S.has(e.type)){if(n.proxied=o,o)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let s=W(e);if(s)n.data=s,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),n=this.getFullRecordName(t.name,r.name),s=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??s?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(s)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${s.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!s.result||s.result.length===0)return{success:!1,message:"Record not found"};let i=s.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let o=[],s=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${s}`);if(o.push(...a.result||[]),a.result_info)i=s<a.result_info.total_pages,s++;else i=!1}return{success:!0,records:o.map((a)=>this.fromCloudflareRecord(a))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(s){let i=s instanceof Error?s.message:String(s);if(!/already exists|1061/i.test(i))throw s;let a=await this.getZoneDetails(r);if(!a)throw s;return{...a,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),n=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let s of o.hosts||[])n.add(s.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(s.result&&s.result.length>0)return s.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),o=n.id,s=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${a.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),n={};for(let o of r.result||[])n[o.id]=o.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),o=[],s=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&b(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),o.push({id:i,from:c,to:a})}catch(d){s.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:o,failed:s}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),n={};for(let o of r.result?.managed_request_headers||[])n[o.id]=o.enabled===!0;return n}async applyManagedRequestHeaders(e,t){let r=[],n=[],o=Object.entries(t).filter(([,c])=>c!==void 0);if(o.length===0)return{changed:r,failed:n};let s=await this.getZoneId(e),i;try{i=await this.getManagedRequestHeaders(e)}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of o)n.push({id:g,error:`could not read managed headers — ${d}`});return{changed:r,failed:n}}let a=[];for(let[c,d]of o){if(!(c in i)){n.push({id:c,error:"not a managed request header transform on this zone"});continue}if(i[c]!==d)a.push([c,d])}if(a.length===0)return{changed:r,failed:n};try{await this.request("PATCH",`/zones/${s}/managed_headers`,{managed_request_headers:a.map(([c,d])=>({id:c,enabled:d})),managed_response_headers:[]});for(let[c,d]of a)r.push({id:c,from:i[c],to:d})}catch(c){let d=c instanceof Error?c.message:String(c);for(let[g]of a)n.push({id:g,error:d})}return{changed:r,failed:n}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let n=await this.getZoneId(e),o=await this.getPhaseRules(e,t),s=r.map((c)=>({...c,description:c.description?.startsWith(T)?c.description:`${T} ${c.description||t}`})),a=B(o,s).map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}var N=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function _(e){return N.test(e)?e.replace(N,"\x00hosts\x00"):null}function k(e,t){return e.replace(N,D(t))}function w(e){if(Array.isArray(e))return`[${e.map(w).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${w(n)}`).join(",")}}`;return JSON.stringify(e)}function K(e,t){let r=_(e.expression);return r!==null&&r===_(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&w(e.action_parameters)===w(t.action_parameters)}function B(e,t){let r=new Set(t.flatMap((s)=>v(s.expression))),n=(s)=>(s.description||"").startsWith(T),o=[];for(let s of e){if(!n(s)){o.push(s);continue}let i=v(s.expression);if(i.length===0){if(r.size>0)o.push(s);continue}let a=i.filter((c)=>!r.has(c));if(a.length===i.length)o.push(s);else if(a.length>0)o.push({...s,expression:k(s.expression,a)})}for(let s of t){let i=v(s.expression),a=i.length>0?o.findIndex((g)=>n(g)&&K(g,s)):-1;if(a===-1){o.push(s);continue}let c=o[a],d=[...new Set([...v(c.expression),...i])];o[a]={...c,expression:k(c.expression,d)}}return o}function v(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let n of r[1].matchAll(/"([^"]+)"/g))t.push(n[1]);return t}function b(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((o,s)=>b(o,t[s]))}let r=e,n=t;return Object.keys(n).every((o)=>b(r[o],n[o]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:V(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,o,s]=r.slice(0,3).map(Number);if(![n,o,s].every(Number.isFinite))return null;return{priority:n,weight:o,port:s,target:V(r.slice(3).join(" "))}}function V(e){return e.replace(/\.$/,"")}var X=new Set(["A","AAAA","CNAME","ALIAS"]);function A(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function Z(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let o=h(n);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function Ki(e,t){return e.map((r)=>({...r,name:Z(r.name,t),proxied:r.proxied??!1}))}function Y(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(X.has(t.type))return!0;if(t.type==="TXT"){let r=A(t.content);if(r)return A(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function J(e,t){if(f(e.content)!==f(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Ji(e){let{provider:t,zone:r,records:n}=e,o={outcomes:[],warnings:[]};if(n.length===0)return o;let s=await t.listRecords(r);if(!s.success)return o.warnings.push(`could not list ${r}: ${s.message||"unknown provider error"} — records not reconciled`),o;let i=s.records;for(let a of n){let c=i.filter((l)=>Y(l,a));if(c.length>0&&c.every((l)=>J(l,a))){o.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},g=a.type==="TXT"&&A(a.content)!==void 0;if(g)for(let l of c){let R=await t.deleteRecord(r,{name:l.name,type:l.type,content:l.content});if(!R.success)o.warnings.push(`could not remove superseded ${l.type} at ${l.name}: ${R.message||"unknown error"}`)}let p=g||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(p.success)o.outcomes.push({record:a,action:c.length>0?"updated":"created"});else o.outcomes.push({record:a,action:"failed",message:p.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let g=new Set(n.filter((l)=>l.type===a&&h(l.name)===d).map((l)=>f(l.content).toLowerCase())),p=i.filter((l)=>l.type===a&&h(l.name)===d&&!g.has(f(l.content).toLowerCase()));for(let l of p)o.warnings.push(`${d} has an undeclared ${a} record (${l.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class Gr{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new M(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let n=await this.client.findHostedZoneForDomain(e);if(n){let o=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=re(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?I(t)===I(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((s)=>s.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(s?.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already present"};let i=[...s?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:s?"UPSERT":"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s?.ttl??t.ttl??300,ResourceRecords:i.map((c)=>({Value:c}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),o=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(!s||!s.values.some((a)=>this.sameValue(t.type,a,o)))return{success:!0,message:"Record already absent"};let i=s.values.filter((a)=>!this.sameValue(t.type,a,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:i.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s.ttl,ResourceRecords:(i.length>0?i:s.values).map((a)=>({Value:a}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let s of n.ResourceRecordSets){if(t&&s.Type!==t)continue;if(s.AliasTarget)continue;for(let i of s.ResourceRecords||[]){let a=i.Value,c;if(s.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(s.Type==="TXT"&&a.startsWith('"'))a=I(a);o.push({name:s.Name.replace(/\.$/,""),type:s.Type,content:a,ttl:s.TTL,priority:c})}}return{success:!0,records:o}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:M.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=M.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var z=255;function re(e){let t=[];for(let r=0;r<e.length;r+=z)t.push(e.slice(r,r+z));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function I(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&n+1<e.length){t+=e[++n];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function Xi(e,t){let r=[],n,o;for(;;){let s=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:o,MaxItems:"100"});if(r.push(...s.ResourceRecordSets),!s.IsTruncated)break;if(n=s.NextRecordName,o=s.NextRecordType,!n)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function C(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function ne(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Qi(e,t){let r=m(t),n=[],o=[],s=[],i=new Set;for(let a of e){let c=m(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){o.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){o.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),s.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let g=m(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:g,ttl:300,translatedFrom:`${d} ALIAS → ${g}`}),a.AliasTarget.EvaluateTargetHealth)s.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of a.ResourceRecords||[]){let p=se(c,d,g.Value,a.TTL);if("reason"in p){o.push({name:c,type:d,reason:p.reason}),s.push(`${d} ${c}: ${p.reason}`);continue}n.push(p)}}return{zone:r,records:n,skipped:o,warnings:s}}function se(e,t,r,n){let o={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:ne(r)};case"MX":{let[s,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(i.join(" ")),priority:Number(s)}}case"SRV":{let s=r.trim().split(/\s+/);if(s.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=s.slice(0,3).map(Number);return{...o,type:"SRV",content:m(s.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var oe=new Set(["TXT","MX","SRV","NS","CAA"]);async function Yi(e,t){let r=[],n=[],o=new Set;try{let s=await e.listRecords(t.zone);for(let i of s.records||[])o.add(`${m(i.name)}|${i.type}|${C(i)}`)}catch{}for(let s of t.records){let i={...s,proxied:!1},a=`${m(s.name)}|${s.type}|${C(s)}`;if(!oe.has(s.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(s);else n.push({record:s,message:d.message||"unknown provider error"});continue}if(o.has(a)){r.push(s);continue}let c=await e.createRecord(t.zone,i);if(c.success)o.add(a),r.push(s);else n.push({record:s,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Zi(e,t){let r=await e.listRecords(t.zone),n=[],o=[],s=new Map;for(let i of r.records||[]){let a=`${m(i.name)}|${i.type}`,c=s.get(a)??[];c.push(C(i)),s.set(a,c)}for(let i of t.records){let a=s.get(`${m(i.name)}|${i.type}`),c=C(i);if(a?.some((d)=>d===c))n.push(i);else o.push({record:i,found:a?.join(", ")})}return{matched:n,missing:o,ok:o.length===0}}class $t{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new q(t),"provider"in e)this.dnsProvider=O(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:o=30}=e,{CertificateArn:s}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(s);let i=await this.acm.getDnsValidationRecords(s);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(s,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:s,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.upsertRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,records:o.map((s)=>({domainName:s.domainName,recordName:s.recordName,recordType:s.recordType,recordValue:s.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.deleteRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue});if(!i.success)n.push(`Failed to delete record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:o}=e,s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED"){let i=s.SubjectAlternativeNames||[s.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:s.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:n,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:o=[],waitForValidation:s=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:s})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function O(e){switch(e.provider){case"route53":return new Gr(e.region,e.hostedZoneId);case"porkbun":return new Ke(e.apiKey,e.secretKey);case"godaddy":return new _t(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new Je(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class ti{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,n=process.env.GODADDY_API_SECRET;if(r&&n){let s=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,s)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((o)=>o.provider===e);if(!r)return null;let n=O(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=O(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>O(e))}}var ze=new ti;class q{client;region;constructor(e="us-east-1"){this.client=new u,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((n)=>({CertificateArn:n.CertificateArn,DomainName:n.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((n)=>n.DomainName===e||n.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let n=0;n<t;n++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((s)=>setTimeout(s,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let n=r.DomainName.slice(2),o=t.split("."),s=n.split(".");if(o.slice(-s.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let o=n.slice(2),s=t.split("."),i=o.split(".");if(s.slice(-i.length).join(".")===o)return!0}}return!1}}class eo{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new q(e),this.route53=new M,t&&t.provider!=="route53")this.dnsProvider=O(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:o=!1,maxWaitMinutes:s=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(i,s*2,30000))throw Error(`Certificate validation timed out after ${s} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),s=[];if(this.dnsProvider){let i=n||o[0]?.domainName;for(let a of o){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});s.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of o){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});s.push({...i,changeId:a.ChangeInfo?.Id})}return s}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let s=n||o[0]?.domainName;for(let i of o)try{await this.dnsProvider.deleteRecord(s,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let s of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${s.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s.recordName,Type:s.recordType,TTL:300,ResourceRecords:[{Value:s.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED")return{certificateArn:s.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
+ export{Ke,_t,ds,us,Je,Ki,Ji,Gr,Xi,Qi,Yi,Zi,q,eo,$t,O,ti};
@@ -1 +1 @@
1
- import{yr,Ga,Ka,bt,Sr,br,vr,Tr,Zr}from"./chunk-hdr0q89a.js";import"./chunk-nazx54p5.js";import"./chunk-3d8y4a6d.js";export{Sr as AwsSecretsManagerConfigurationBackend,br as AwsSsmConfigurationBackend,Tr as ConfigurationService,yr as ConfigurationStore,vr as ExternalConfigurationBackend,bt as LocalEncryptedConfigurationBackend,Ga as parseDotenv,Ka as serializeDotenv,Zr as synchronizeConfiguredConfiguration};
1
+ import{yr,Qa,Ya,bt,Sr,br,vr,Tr,Zr}from"./chunk-tc24txss.js";import"./chunk-tfasfg4a.js";import"./chunk-zzmk290g.js";export{Sr as AwsSecretsManagerConfigurationBackend,br as AwsSsmConfigurationBackend,Tr as ConfigurationService,yr as ConfigurationStore,vr as ExternalConfigurationBackend,bt as LocalEncryptedConfigurationBackend,Qa as parseDotenv,Ya as serializeDotenv,Zr as synchronizeConfiguredConfiguration};
@@ -1,6 +1,6 @@
1
- import{ed}from"./chunk-31tmm8kx.js";var g={};ed(g,{ProgressBar:()=>v,Spinner:()=>o,box:()=>he,checkAwsCli:()=>Rs,checkAwsCredentials:()=>Ps,colorize:()=>Mt,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>Yr,formatDuration:()=>b,getAwsAccountId:()=>Ns,getAwsRegions:()=>Ds,header:()=>i,info:()=>e,prompt:()=>I,select:()=>ho,step:()=>m,success:()=>n,table:()=>c,warn:()=>a,warning:()=>hr});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Mt(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var hr=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function m(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
1
+ import{ad}from"./chunk-m2kr333s.js";var g={};ad(g,{ProgressBar:()=>v,Spinner:()=>o,box:()=>he,checkAwsCli:()=>Ns,checkAwsCredentials:()=>Ds,colorize:()=>Mt,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>Yr,formatDuration:()=>b,getAwsAccountId:()=>ks,getAwsRegions:()=>xs,header:()=>i,info:()=>e,prompt:()=>I,select:()=>ho,step:()=>m,success:()=>n,table:()=>c,warn:()=>a,warning:()=>hr});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Mt(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var hr=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function m(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
2
2
  ${T.bright}${T.cyan}${t}${T.reset}
3
3
  `)}var x=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class o{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor(t){this.message=t}get text(){return this.message}set text(t){if(this.message=t,x&&this.interval)console.log(` ${t}`)}start(){if(x){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${T.cyan}${this.frames[this.currentFrame]}${T.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(t){this.stop(),n(t||this.message)}fail(t){this.stop(),r(t||this.message)}warn(t){this.stop(),hr(t||this.message)}stop(){if(this.interval){if(!x)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class v{total;current=0;width=40;constructor(t){this.total=t}update(t){this.current=t,this.render()}increment(){this.current++,this.render()}render(){let t=Math.floor(this.current/this.total*100),s=Math.floor(this.current/this.total*this.width),l=this.width-s,u=`${"█".repeat(s)}${"░".repeat(l)}`;if(process.stdout.write(`\r${T.cyan}${u}${T.reset} ${t}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
4
4
  `)}}async function I(t,s){let l=await import("node:readline"),u=l.createInterface({input:process.stdin,output:process.stdout});return new Promise((p)=>{let h=s?`${T.cyan}?${T.reset} ${t} ${T.gray}(${s})${T.reset}: `:`${T.cyan}?${T.reset} ${t}: `;u.question(h,(f)=>{u.close(),p(f||s||"")})})}async function d(t,s=!1){let l=await I(`${t} (y/n)`,s?"y":"n");return l.toLowerCase()==="y"||l.toLowerCase()==="yes"}async function ho(t,s){console.log(`${T.cyan}?${T.reset} ${t}`),s.forEach((p,h)=>{console.log(` ${T.gray}${h+1}.${T.reset} ${p}`)});let l=await I("Select","1"),u=Number.parseInt(l)-1;if(u>=0&&u<s.length)return s[u];return s[0]}function c(t,s){let l=t.map((p,h)=>{let f=Math.max(...s.map((w)=>(w[h]||"").length));return Math.max(p.length,f)}),u=t.map((p,h)=>p.padEnd(l[h])).join(" ");console.log(Mt(u,"bright")),console.log(Mt("─".repeat(u.length),"gray")),s.forEach((p)=>{let h=p.map((f,w)=>(f||"").padEnd(l[w])).join(" ");console.log(h)})}function Yr(t){if(t===0)return"0 B";let s=1024,l=["B","KB","MB","GB","TB"],u=Math.floor(Math.log(t)/Math.log(s));return`${Number.parseFloat((t/s**u).toFixed(2))} ${l[u]}`}function b(t){if(t<1000)return`${t}ms`;let s=Math.floor(t/1000);if(s<60)return`${s}s`;let l=Math.floor(s/60),u=s%60;if(l<60)return`${l}m ${u}s`;let p=Math.floor(l/60),h=l%60;return`${p}h ${h}m`}function he(t,s="cyan"){let l=t.split(`
5
- `),u=Math.max(...l.map((h)=>h.length)),p="─".repeat(u+2);console.log(Mt(`┌${p}┐`,s)),l.forEach((h)=>{console.log(Mt(`│ ${h.padEnd(u)} │`,s))}),console.log(Mt(`└${p}┘`,s))}async function Rs(){return!0}async function Ps(){try{let{AWSClient:t}=await import("./chunk-fbq61aj0.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function Ns(){try{let{AWSClient:t}=await import("./chunk-fbq61aj0.js"),l=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return l.Account||l.GetCallerIdentityResult?.Account||null}catch{return null}}async function Ds(){try{let{AWSClient:t}=await import("./chunk-fbq61aj0.js"),l=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),u=[];if(l.regionInfo){let p=Array.isArray(l.regionInfo)?l.regionInfo:[l.regionInfo];u.push(...p.map((h)=>h.regionName))}return u.length>0?u:y()}catch{return y()}}function y(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
6
- export{T,Mt,n,r,a,hr,e,m,i,o,I,d,ho,c,Yr,he,Rs,Ps,Ns,Ds,g};
5
+ `),u=Math.max(...l.map((h)=>h.length)),p="─".repeat(u+2);console.log(Mt(`┌${p}┐`,s)),l.forEach((h)=>{console.log(Mt(`│ ${h.padEnd(u)} │`,s))}),console.log(Mt(`└${p}┘`,s))}async function Ns(){return!0}async function Ds(){try{let{AWSClient:t}=await import("./chunk-66egshmp.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function ks(){try{let{AWSClient:t}=await import("./chunk-66egshmp.js"),l=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return l.Account||l.GetCallerIdentityResult?.Account||null}catch{return null}}async function xs(){try{let{AWSClient:t}=await import("./chunk-66egshmp.js"),l=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),u=[];if(l.regionInfo){let p=Array.isArray(l.regionInfo)?l.regionInfo:[l.regionInfo];u.push(...p.map((h)=>h.regionName))}return u.length>0?u:y()}catch{return y()}}function y(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
6
+ export{T,Mt,n,r,a,hr,e,m,i,o,I,d,ho,c,Yr,he,Ns,Ds,ks,xs,g};
@@ -1,3 +1,3 @@
1
- import{Pe,Vt}from"./chunk-3d8y4a6d.js";import{u,N}from"./chunk-cb47f0pb.js";import{v}from"./chunk-me81g606.js";import{St,f}from"./chunk-9j7qhwe0.js";import{P}from"./chunk-9gcmpcmq.js";import{F}from"./chunk-tb4ek3s5.js";import{Lt,j}from"./chunk-yas09vmt.js";import{Ha}from"./chunk-58phgtc8.js";class Q{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(St(t))}async query(e){let t=new URLSearchParams(N({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,y)=>{t[`Statistics.member.${y+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,y)=>{t[`ExtendedStatistics.member.${y+1}`]=o}),(e.Dimensions??[]).forEach((o,y)=>{t[`Dimensions.member.${y+1}.Name`]=o.Name,t[`Dimensions.member.${y+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let y={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let g of m)if(g?.key!=null)y[g.key]=Number(g.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(y).length?y:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}class ne{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}import{createHash as le}from"node:crypto";import{existsSync as se,mkdirSync as de,readdirSync as ge,readFileSync as pe,rmSync as he,writeFileSync as ye}from"node:fs";import{homedir as fe}from"node:os";import{join as G}from"node:path";var ie=1,ae=3600000,Se=24*ae,Ce=ae,Te=30*Se;function X(){let e=process.env.XDG_CACHE_HOME;return G(e&&e.trim()?e:G(fe(),".cache"),"ts-cloud","cost-explorer")}function J(e){return G(X(),e??"__default__")}function oe(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return le("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function be(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Ne(e){return be(e.start,e.end)?Te:Ce}function me(e,t){let r=G(J(e),`${oe(t)}.json`);if(!se(r))return null;let a;try{a=JSON.parse(pe(r,"utf-8"))}catch{return null}if(a.schema!==ie)return null;let s=Date.now()-a.savedAt;if(s<0||s>Ne(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function ce(e,t,r){let a=J(e);de(a,{recursive:!0});let s={schema:ie,savedAt:Date.now(),key:t,response:r};ye(G(a,`${oe(t)}.json`),JSON.stringify(s))}function za(e){let t=e===void 0?X():J(e);if(!se(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of ge(s,{withFileTypes:!0})){let y=G(s,o.name);if(o.isDirectory())a(y);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),he(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function qa(e){return e===void 0?X():J(e)}class Xe{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new u(St(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,y=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],g={start:t,end:r,granularity:s,metrics:y,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,g);if(b)return this.lastCacheAgeSeconds=b.ageSeconds,b.response}this.lastCacheAgeSeconds=null;let h=new Map,i;do{let b={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:y,GroupBy:m};if(o)b.Filter=o;if(i)b.NextPageToken=i;let O=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(b)});for(let B of O?.ResultsByTime??[])for(let A of B?.Groups??[]){let U=A.Keys?.[0]??"Unknown",K=Number.parseFloat(A.Metrics?.UnblendedCost?.Amount??"0"),H=A.Metrics?.UnblendedCost?.Unit??"USD",R=h.get(U);h.set(U,{key:U,amount:(R?.amount??0)+K,unit:H})}i=O?.NextPageToken||void 0}while(i);let I=[...h.values()].filter((b)=>b.amount>0).sort((b,O)=>O.amount-b.amount);if(this.useCache)ce(this.profile,g,I);return I}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class Z{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class ee{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function ue(e){return String(e).padStart(2,"0")}function _(e){return`${e.getUTCFullYear()}-${ue(e.getUTCMonth()+1)}-${ue(e.getUTCDate())}`}function Ae(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function z(e,t,r,a,s,o){let y=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!y.length)return 0;if(a==="Sum")return y.reduce((m,g)=>m+(g.Sum??0),0);if(a==="Maximum")return Math.max(...y.map((m)=>m.Maximum??0));return y.reduce((m,g)=>m+(g.Average??0),0)/y.length}async function V(e,t,r,a,s,o,y){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:y,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((g,h)=>g+(h.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((g)=>g.Maximum??0));return m.reduce((g,h)=>g+(h.Average??0),0)/m.length}async function te(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((y,m)=>y+(m.Percentiles?.[r]??0),0))}async function ci(e,t){let r=await j(e,t),a=r.region,s=new Q(a),o=new P(a),y=new ne(a),m=new Date,g=new Date(m.getTime()-86400000),h=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:h?.kind==="php"?`php-${h?.phpVersion??"8.3"} (fpm)`:h?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let I=0,b=0,O=0,B=[],A=[],U=[];for(let n of r.functions){let[l,d,c,C,p,T,M,x,L]=await Promise.all([z(s,n.name,"Invocations","Sum",g,m),z(s,n.name,"Errors","Sum",g,m),z(s,n.name,"Throttles","Sum",g,m),z(s,n.name,"Duration","Average",g,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",g,m),te(s,n.name,"p95",g,m),te(s,n.name,"p99",g,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);I+=l,b+=d,O=Math.max(O,C);let k=p?.Configuration?.MemorySize??0,D=Object.keys(p?.Configuration?.Environment?.Variables??{}),q=[],S=0;try{let{events:Y=[]}=await y.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:g.getTime(),limit:120});for(let E of Y){let W=(E.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(W);if(re)S=Math.max(S,Number(re[1]));if(W&&!/^(?:START|END|REPORT|INIT_START)/.test(W))U.push({source:n.mode||n.name,timestamp:new Date(E.timestamp??0).toISOString(),when:Ae(E.timestamp??0),message:W.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(W)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(W)?"warn":"info"})}q=Y.filter((E)=>!/^(?:START|END|REPORT|INIT_START)/.test((E.message??"").trim())).slice(-6).map((E)=>({ts:new Date(E.timestamp??0).toISOString().slice(11,19),msg:(E.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(E.message??"")}))}catch{}let w=Math.max(1,...L);B.push({key:n.mode,name:n.name,version:n.version,memory:k,timeout:p?.Configuration?.Timeout??0,runtime:p?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(l),errors:Math.round(d),p95:M||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),A.push({key:n.mode,name:n.name,runtime:p?.Configuration?.Runtime??"provided.al2023",arch:p?.Configuration?.Architectures?.[0]??"x86_64",memory:k,timeout:p?.Configuration?.Timeout??0,ephemeral:p?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:h?.concurrency??"—",invocations:Math.round(l),errors:Math.round(d),throttles:Math.round(c),p50:T||Math.round(C),p95:M||Math.round(C),p99:x||Math.round(C),maxMem:S,spark:L.length?L.map((Y)=>Math.round(Y/w*100)):[0],env:D.length?D:["(none)"],recent:q.length?q:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=B,i.functionsDetail=A,i.serverlessLogs=U.sort((n,l)=>String(l.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=U.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let K=I?Number((b/I*100).toFixed(2)):0,H=Math.round(await z(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",g,m));i.metrics={invocations:Math.round(I),errorRatePct:K,p95Ms:Math.round(O),coldStartPct:void 0,concurrency:H,estCostUsd:void 0};try{let n=new F(a),l=[],d=[],c=0;try{let{QueueUrl:p}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:T}=await n.getQueueAttributes(p);c=Number(T.ApproximateNumberOfMessages??0)}catch{}let C=h?Vt(h,r.slug,t):[];for(let p of C){let T=p.name.replace(`${r.slug}-${t}-`,""),M=0,x=0;try{let{QueueUrl:k}=await n.getQueueUrl(p.name),{Attributes:D}=await n.getQueueAttributes(k);M=Number(D.ApproximateNumberOfMessages??0),x=Number(D.ApproximateNumberOfMessagesNotVisible??0)}catch{}let L=Math.round(await V(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:p.name}],"Sum",g,m));l.push({name:T,visible:M,inFlight:x,processed:L,dlq:c}),d.push({name:p.name,short:T,visible:M,inFlight:x,delayed:0,processed:L,oldestSec:0,concurrency:p.concurrency??h?.queueConcurrency??"—",tries:h?.queueTries??3,visTimeout:(h?.queueTimeout??120)*6,dlq:c})}if(l.length)i.queues=l;if(d.length)i.queuesDetail=d;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:l}=await n.describeStacks({stackName:Pe(e,t)}),d={};for(let c of l?.[0]?.Outputs??[])if(c.OutputKey)d[c.OutputKey]=c.OutputValue??"";if(h?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,C=[{Name:"DBClusterIdentifier",Value:c}],[p,T]=await Promise.all([V(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",g,m),V(s,"AWS/RDS","DatabaseConnections",C,"Maximum",g,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:h?.database?.minCapacity??0.5,maxAcu:h?.database?.maxCapacity??4,currentAcu:p?Number(p.toFixed(1)):h?.database?.minCapacity??0.5,database:"app",connections:Math.round(T),status:d.DbEndpoint?"available":"creating"},h?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:d.DbProxyEndpoint??"—",pooledConns:Math.round(T),status:"available"}}if(h?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,C=[{Name:"CacheClusterId",Value:`${c}-001`}],[p,T]=await Promise.all([V(s,"AWS/ElastiCache","CacheHits",C,"Sum",g,m),V(s,"AWS/ElastiCache","CacheMisses",C,"Sum",g,m)]),M=p+T>0?Number((p/(p+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:M,status:d.CacheEndpoint?"available":"creating"}}if(h?.efs){let c=0;try{if(d.EfsFileSystemId){let C=new Z(a),{FileSystems:p}=await C.describeFileSystems({FileSystemId:d.EfsFileSystemId});c=Number(((p?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:d.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=d.AssetsCdnDomain?{bucket:d.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:d.AssetsCdnDomain,customDomain:h?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let l=await new f(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=l.length,i.assetsInfo.sizeMb=Number((l.reduce((d,c)=>d+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=l.slice(0,8).map((d)=>({path:`/${d.Key}`,size:`${Math.max(1,Math.round((d.Size??0)/1024))} KB`,type:d.Key.split(".").pop()??""}))}catch{}try{if(h?.secrets){let n=Array.isArray(h.secrets)?h.secrets.map((l)=>({key:l.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:l})):Object.entries(h.secrets).map(([l,d])=>({key:l,source:String(d)}));i.secretsList=n.map((l)=>({...l,updated:"—"}))}}catch{}try{let n=new f(a),l=`${r.slug}-${t}-deployments`,d=await n.getObjectJson(l,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(d?.records?.length)i.deploymentsDetail=d.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(b),errorRatePct:K,p95Ms:i.metrics.p95Ms,throttles:A.reduce((n,l)=>n+l.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:H},i.metricsPerFn=A.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new Xe,l=m,d=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),1)),c=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()-1,1)),[C,p]=await Promise.all([n.getCostByService({start:_(d),end:_(l),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:_(c),end:_(d),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,w)=>S+w.amount,0),M=p.reduce((S,w)=>S+w.amount,0),x=l.getUTCDate(),L=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/x*L).toFixed(2)),lastMonthUsd:Number(M.toFixed(2)),dailyAvgUsd:Number((T/x).toFixed(2))},i.costServices=C.filter((S)=>S.amount>0).sort((S,w)=>w.amount-S.amount).slice(0,12).map((S)=>({name:S.service,usd:Number(S.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((T/x).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:_(d),end:_(l)}).catch(()=>[]);let k=C.find((S)=>/lambda/i.test(S.service))?.amount??0,D=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),q=A.reduce((S,w)=>S+D(w),0)||1;i.costPerFn=A.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(D(S)),usd:Number((k*(D(S)/q)).toFixed(2))}))}}catch{}if(h?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:g,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),l=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:g,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(l.reduce((d,c)=>d+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((d,c)=>d+(c.Sum??0),0))};try{let d=new ee(a),c=await d.listWebACLs("REGIONAL"),C=c.find((p)=>p.Name?.includes(`${r.slug}-${t}`))??c[0];if(C?.Name&&C.Id){i.waf.acl=C.Name;let p=await d.getWebACLRules(C.Name,C.Id,"REGIONAL");if(p.length)i.wafRules=p.map((T)=>({name:T.Name??"—",detail:`priority ${T.Priority??0}`,action:T.Action??"count",blocked24h:0}))}}catch{}}catch{}let R=[];if(i.aurora)R.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)R.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)R.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)R.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(R.length)i.dataServices=R;if(r.scheduler!=="off"&&h?.kind==="php")try{let n=await Lt(e,t,"schedule:list"),l=[];for(let d of(n||"").split(`
2
- `)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(d);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)l.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(l.length)i.schedulerTasks=l}catch{}return i.topology=Ha(i,{project:e.project.name,environment:t}),i}
3
- export{ne,Q,za,qa,Xe,ci};
1
+ import{Pe,Vt}from"./chunk-zzmk290g.js";import{u,N}from"./chunk-cs6a98r1.js";import{v}from"./chunk-vx9qk1g1.js";import{St,f}from"./chunk-2943bszc.js";import{P}from"./chunk-yk4p2k8w.js";import{F}from"./chunk-bhay1f8a.js";import{Lt,j}from"./chunk-j76935z3.js";import{Ja}from"./chunk-grs2cwm7.js";class Q{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(St(t))}async query(e){let t=new URLSearchParams(N({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,y)=>{t[`Statistics.member.${y+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,y)=>{t[`ExtendedStatistics.member.${y+1}`]=o}),(e.Dimensions??[]).forEach((o,y)=>{t[`Dimensions.member.${y+1}.Name`]=o.Name,t[`Dimensions.member.${y+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let y={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let g of m)if(g?.key!=null)y[g.key]=Number(g.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(y).length?y:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}class ne{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}import{createHash as le}from"node:crypto";import{existsSync as se,mkdirSync as de,readdirSync as ge,readFileSync as pe,rmSync as he,writeFileSync as ye}from"node:fs";import{homedir as fe}from"node:os";import{join as G}from"node:path";var ie=1,ae=3600000,Se=24*ae,Ce=ae,Te=30*Se;function X(){let e=process.env.XDG_CACHE_HOME;return G(e&&e.trim()?e:G(fe(),".cache"),"ts-cloud","cost-explorer")}function J(e){return G(X(),e??"__default__")}function oe(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return le("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function be(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Ne(e){return be(e.start,e.end)?Te:Ce}function me(e,t){let r=G(J(e),`${oe(t)}.json`);if(!se(r))return null;let a;try{a=JSON.parse(pe(r,"utf-8"))}catch{return null}if(a.schema!==ie)return null;let s=Date.now()-a.savedAt;if(s<0||s>Ne(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function ce(e,t,r){let a=J(e);de(a,{recursive:!0});let s={schema:ie,savedAt:Date.now(),key:t,response:r};ye(G(a,`${oe(t)}.json`),JSON.stringify(s))}function Ga(e){let t=e===void 0?X():J(e);if(!se(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of ge(s,{withFileTypes:!0})){let y=G(s,o.name);if(o.isDirectory())a(y);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),he(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function Ka(e){return e===void 0?X():J(e)}class Qe{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new u(St(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,y=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],g={start:t,end:r,granularity:s,metrics:y,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,g);if(b)return this.lastCacheAgeSeconds=b.ageSeconds,b.response}this.lastCacheAgeSeconds=null;let h=new Map,i;do{let b={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:y,GroupBy:m};if(o)b.Filter=o;if(i)b.NextPageToken=i;let O=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(b)});for(let B of O?.ResultsByTime??[])for(let A of B?.Groups??[]){let U=A.Keys?.[0]??"Unknown",K=Number.parseFloat(A.Metrics?.UnblendedCost?.Amount??"0"),H=A.Metrics?.UnblendedCost?.Unit??"USD",R=h.get(U);h.set(U,{key:U,amount:(R?.amount??0)+K,unit:H})}i=O?.NextPageToken||void 0}while(i);let I=[...h.values()].filter((b)=>b.amount>0).sort((b,O)=>O.amount-b.amount);if(this.useCache)ce(this.profile,g,I);return I}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class Z{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class ee{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function ue(e){return String(e).padStart(2,"0")}function _(e){return`${e.getUTCFullYear()}-${ue(e.getUTCMonth()+1)}-${ue(e.getUTCDate())}`}function Ae(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function z(e,t,r,a,s,o){let y=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!y.length)return 0;if(a==="Sum")return y.reduce((m,g)=>m+(g.Sum??0),0);if(a==="Maximum")return Math.max(...y.map((m)=>m.Maximum??0));return y.reduce((m,g)=>m+(g.Average??0),0)/y.length}async function V(e,t,r,a,s,o,y){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:y,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((g,h)=>g+(h.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((g)=>g.Maximum??0));return m.reduce((g,h)=>g+(h.Average??0),0)/m.length}async function te(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((y,m)=>y+(m.Percentiles?.[r]??0),0))}async function ci(e,t){let r=await j(e,t),a=r.region,s=new Q(a),o=new P(a),y=new ne(a),m=new Date,g=new Date(m.getTime()-86400000),h=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:h?.kind==="php"?`php-${h?.phpVersion??"8.3"} (fpm)`:h?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let I=0,b=0,O=0,B=[],A=[],U=[];for(let n of r.functions){let[l,d,c,C,p,T,M,x,L]=await Promise.all([z(s,n.name,"Invocations","Sum",g,m),z(s,n.name,"Errors","Sum",g,m),z(s,n.name,"Throttles","Sum",g,m),z(s,n.name,"Duration","Average",g,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",g,m),te(s,n.name,"p95",g,m),te(s,n.name,"p99",g,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);I+=l,b+=d,O=Math.max(O,C);let k=p?.Configuration?.MemorySize??0,D=Object.keys(p?.Configuration?.Environment?.Variables??{}),q=[],S=0;try{let{events:Y=[]}=await y.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:g.getTime(),limit:120});for(let E of Y){let W=(E.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(W);if(re)S=Math.max(S,Number(re[1]));if(W&&!/^(?:START|END|REPORT|INIT_START)/.test(W))U.push({source:n.mode||n.name,timestamp:new Date(E.timestamp??0).toISOString(),when:Ae(E.timestamp??0),message:W.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(W)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(W)?"warn":"info"})}q=Y.filter((E)=>!/^(?:START|END|REPORT|INIT_START)/.test((E.message??"").trim())).slice(-6).map((E)=>({ts:new Date(E.timestamp??0).toISOString().slice(11,19),msg:(E.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(E.message??"")}))}catch{}let w=Math.max(1,...L);B.push({key:n.mode,name:n.name,version:n.version,memory:k,timeout:p?.Configuration?.Timeout??0,runtime:p?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(l),errors:Math.round(d),p95:M||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),A.push({key:n.mode,name:n.name,runtime:p?.Configuration?.Runtime??"provided.al2023",arch:p?.Configuration?.Architectures?.[0]??"x86_64",memory:k,timeout:p?.Configuration?.Timeout??0,ephemeral:p?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:h?.concurrency??"—",invocations:Math.round(l),errors:Math.round(d),throttles:Math.round(c),p50:T||Math.round(C),p95:M||Math.round(C),p99:x||Math.round(C),maxMem:S,spark:L.length?L.map((Y)=>Math.round(Y/w*100)):[0],env:D.length?D:["(none)"],recent:q.length?q:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=B,i.functionsDetail=A,i.serverlessLogs=U.sort((n,l)=>String(l.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=U.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let K=I?Number((b/I*100).toFixed(2)):0,H=Math.round(await z(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",g,m));i.metrics={invocations:Math.round(I),errorRatePct:K,p95Ms:Math.round(O),coldStartPct:void 0,concurrency:H,estCostUsd:void 0};try{let n=new F(a),l=[],d=[],c=0;try{let{QueueUrl:p}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:T}=await n.getQueueAttributes(p);c=Number(T.ApproximateNumberOfMessages??0)}catch{}let C=h?Vt(h,r.slug,t):[];for(let p of C){let T=p.name.replace(`${r.slug}-${t}-`,""),M=0,x=0;try{let{QueueUrl:k}=await n.getQueueUrl(p.name),{Attributes:D}=await n.getQueueAttributes(k);M=Number(D.ApproximateNumberOfMessages??0),x=Number(D.ApproximateNumberOfMessagesNotVisible??0)}catch{}let L=Math.round(await V(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:p.name}],"Sum",g,m));l.push({name:T,visible:M,inFlight:x,processed:L,dlq:c}),d.push({name:p.name,short:T,visible:M,inFlight:x,delayed:0,processed:L,oldestSec:0,concurrency:p.concurrency??h?.queueConcurrency??"—",tries:h?.queueTries??3,visTimeout:(h?.queueTimeout??120)*6,dlq:c})}if(l.length)i.queues=l;if(d.length)i.queuesDetail=d;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:l}=await n.describeStacks({stackName:Pe(e,t)}),d={};for(let c of l?.[0]?.Outputs??[])if(c.OutputKey)d[c.OutputKey]=c.OutputValue??"";if(h?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,C=[{Name:"DBClusterIdentifier",Value:c}],[p,T]=await Promise.all([V(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",g,m),V(s,"AWS/RDS","DatabaseConnections",C,"Maximum",g,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:h?.database?.minCapacity??0.5,maxAcu:h?.database?.maxCapacity??4,currentAcu:p?Number(p.toFixed(1)):h?.database?.minCapacity??0.5,database:"app",connections:Math.round(T),status:d.DbEndpoint?"available":"creating"},h?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:d.DbProxyEndpoint??"—",pooledConns:Math.round(T),status:"available"}}if(h?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,C=[{Name:"CacheClusterId",Value:`${c}-001`}],[p,T]=await Promise.all([V(s,"AWS/ElastiCache","CacheHits",C,"Sum",g,m),V(s,"AWS/ElastiCache","CacheMisses",C,"Sum",g,m)]),M=p+T>0?Number((p/(p+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:M,status:d.CacheEndpoint?"available":"creating"}}if(h?.efs){let c=0;try{if(d.EfsFileSystemId){let C=new Z(a),{FileSystems:p}=await C.describeFileSystems({FileSystemId:d.EfsFileSystemId});c=Number(((p?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:d.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=d.AssetsCdnDomain?{bucket:d.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:d.AssetsCdnDomain,customDomain:h?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let l=await new f(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=l.length,i.assetsInfo.sizeMb=Number((l.reduce((d,c)=>d+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=l.slice(0,8).map((d)=>({path:`/${d.Key}`,size:`${Math.max(1,Math.round((d.Size??0)/1024))} KB`,type:d.Key.split(".").pop()??""}))}catch{}try{if(h?.secrets){let n=Array.isArray(h.secrets)?h.secrets.map((l)=>({key:l.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:l})):Object.entries(h.secrets).map(([l,d])=>({key:l,source:String(d)}));i.secretsList=n.map((l)=>({...l,updated:"—"}))}}catch{}try{let n=new f(a),l=`${r.slug}-${t}-deployments`,d=await n.getObjectJson(l,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(d?.records?.length)i.deploymentsDetail=d.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(b),errorRatePct:K,p95Ms:i.metrics.p95Ms,throttles:A.reduce((n,l)=>n+l.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:H},i.metricsPerFn=A.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new Qe,l=m,d=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),1)),c=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()-1,1)),[C,p]=await Promise.all([n.getCostByService({start:_(d),end:_(l),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:_(c),end:_(d),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,w)=>S+w.amount,0),M=p.reduce((S,w)=>S+w.amount,0),x=l.getUTCDate(),L=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/x*L).toFixed(2)),lastMonthUsd:Number(M.toFixed(2)),dailyAvgUsd:Number((T/x).toFixed(2))},i.costServices=C.filter((S)=>S.amount>0).sort((S,w)=>w.amount-S.amount).slice(0,12).map((S)=>({name:S.service,usd:Number(S.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((T/x).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:_(d),end:_(l)}).catch(()=>[]);let k=C.find((S)=>/lambda/i.test(S.service))?.amount??0,D=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),q=A.reduce((S,w)=>S+D(w),0)||1;i.costPerFn=A.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(D(S)),usd:Number((k*(D(S)/q)).toFixed(2))}))}}catch{}if(h?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:g,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),l=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:g,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(l.reduce((d,c)=>d+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((d,c)=>d+(c.Sum??0),0))};try{let d=new ee(a),c=await d.listWebACLs("REGIONAL"),C=c.find((p)=>p.Name?.includes(`${r.slug}-${t}`))??c[0];if(C?.Name&&C.Id){i.waf.acl=C.Name;let p=await d.getWebACLRules(C.Name,C.Id,"REGIONAL");if(p.length)i.wafRules=p.map((T)=>({name:T.Name??"—",detail:`priority ${T.Priority??0}`,action:T.Action??"count",blocked24h:0}))}}catch{}}catch{}let R=[];if(i.aurora)R.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)R.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)R.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)R.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(R.length)i.dataServices=R;if(r.scheduler!=="off"&&h?.kind==="php")try{let n=await Lt(e,t,"schedule:list"),l=[];for(let d of(n||"").split(`
2
+ `)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(d);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)l.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(l.length)i.schedulerTasks=l}catch{}return i.topology=Ja(i,{project:e.project.name,environment:t}),i}
3
+ export{ne,Q,Ga,Ka,Qe,ci};
@@ -0,0 +1 @@
1
+ import{f}from"./chunk-2943bszc.js";import"./chunk-cs6a98r1.js";export{f as S3Client};
@@ -0,0 +1 @@
1
+ import{Ho}from"./chunk-gv9deppc.js";export{Ho as encodeDashboardPayload};
@@ -0,0 +1 @@
1
+ import{di,u,N,_s}from"./chunk-cs6a98r1.js";export{u as AWSClient,N as buildQueryParams,_s as detectCredentialSource,di as resolveS3Endpoint};
@@ -0,0 +1 @@
1
+ import{Tu}from"./chunk-zacbzz1w.js";import"./chunk-xxf1vhfr.js";import"./chunk-3qfd0vnc.js";import"./chunk-cs6a98r1.js";import"./chunk-zzmk290g.js";export{Tu as buildAndPushServerlessImage};
@@ -1,3 +1,3 @@
1
- import{H,L,oi,hs,Ot,Va}from"./chunk-3eht1tp2.js";function c(e){return`'${e.split("'").join("'\\''")}'`}function m(e){let r=e.user||"root",s=e.script.join(`
2
- `),t=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${c(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,s,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',t,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var l={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function i(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function us(e,r){let s=e.logger||l,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let n=H(e.slug,r.siteName),u=Ot(n,r.to||"unused"),o=["set -uo pipefail",...Va(u,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`}),`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${u.current} && eval "$(cd ${L} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];s.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${t.length} server(s)...`);let a=await e.driver.runRemoteDeploy({targets:t,commands:o,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!a.success)s.error(`Rollback failed: ${a.error||"unknown error"}`);else s.success(`Rolled back ${r.siteName}.`);return{success:a.success,error:a.error,perInstance:a.perInstance}}async function xu(e,r){let s=await i(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let t=hs(H(e.slug,r.siteName)),n=Math.max(1,r.limit??20),u=[`[ -f ${t} ] && tail -n ${n} ${t} || echo "no deploy history for ${r.siteName}"`],o=await e.driver.runRemoteDeploy({targets:s,commands:u,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:o.success,error:o.error,perInstance:o.perInstance}}async function _u(e,r){let s=e.logger||l,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:m({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Recipe '${r.name}' failed: ${n.error||"unknown error"}`);else s.success(`Recipe '${r.name}' completed.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}async function ps(e,r){let s=e.logger||l;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:oi(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Restore failed: ${n.error||"unknown error"}`);else s.success(`Restored ${r.database.name}.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}
3
- export{us,xu,_u,ps};
1
+ import{H,L,oi,Ss,Ot,Wa}from"./chunk-dczw0nxw.js";function c(e){return`'${e.split("'").join("'\\''")}'`}function m(e){let r=e.user||"root",s=e.script.join(`
2
+ `),t=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${c(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,s,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',t,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var l={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function i(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function ms(e,r){let s=e.logger||l,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let n=H(e.slug,r.siteName),u=Ot(n,r.to||"unused"),o=["set -uo pipefail",...Wa(u,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`}),`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${u.current} && eval "$(cd ${L} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];s.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${t.length} server(s)...`);let a=await e.driver.runRemoteDeploy({targets:t,commands:o,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!a.success)s.error(`Rollback failed: ${a.error||"unknown error"}`);else s.success(`Rolled back ${r.siteName}.`);return{success:a.success,error:a.error,perInstance:a.perInstance}}async function Fu(e,r){let s=await i(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let t=Ss(H(e.slug,r.siteName)),n=Math.max(1,r.limit??20),u=[`[ -f ${t} ] && tail -n ${n} ${t} || echo "no deploy history for ${r.siteName}"`],o=await e.driver.runRemoteDeploy({targets:s,commands:u,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:o.success,error:o.error,perInstance:o.perInstance}}async function ju(e,r){let s=e.logger||l,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:m({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Recipe '${r.name}' failed: ${n.error||"unknown error"}`);else s.success(`Recipe '${r.name}' completed.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}async function gs(e,r){let s=e.logger||l;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:oi(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Restore failed: ${n.error||"unknown error"}`);else s.success(`Restored ${r.database.name}.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}
3
+ export{ms,Fu,ju,gs};