@geekmidas/cli 10.0.0-alpha.91 → 10.0.0-alpha.93

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 (318) hide show
  1. package/dist/{EndpointGenerator-CVc6Oi1Y.mjs → EndpointGenerator-Bor2tZCm.mjs} +14 -4
  2. package/dist/EndpointGenerator-Bor2tZCm.mjs.map +1 -0
  3. package/dist/{EndpointGenerator-CwLjBCFE.cjs → EndpointGenerator-De03t1hd.cjs} +14 -4
  4. package/dist/EndpointGenerator-De03t1hd.cjs.map +1 -0
  5. package/dist/{GoDaddyProvider-DqZ1qD_F.cjs → GoDaddyProvider-BZb-V14e.cjs} +11 -10
  6. package/dist/GoDaddyProvider-BZb-V14e.cjs.map +1 -0
  7. package/dist/{GoDaddyProvider-DSStJVAv.mjs → GoDaddyProvider-Mi3vptSR.mjs} +11 -10
  8. package/dist/GoDaddyProvider-Mi3vptSR.mjs.map +1 -0
  9. package/dist/{HostingerProvider-BI6J7oJr.mjs → HostingerProvider-1mqD6aG8.mjs} +2 -2
  10. package/dist/{HostingerProvider-BI6J7oJr.mjs.map → HostingerProvider-1mqD6aG8.mjs.map} +1 -1
  11. package/dist/{HostingerProvider-CyTpG_jy.cjs → HostingerProvider-C6t-PSNe.cjs} +2 -2
  12. package/dist/{HostingerProvider-CyTpG_jy.cjs.map → HostingerProvider-C6t-PSNe.cjs.map} +1 -1
  13. package/dist/{LegacyStateStore-DXmNA7hy.cjs → LegacyStateStore-BlYXQQSE.cjs} +44 -10
  14. package/dist/LegacyStateStore-BlYXQQSE.cjs.map +1 -0
  15. package/dist/LegacyStateStore-CtwO7fwy.mjs +123 -0
  16. package/dist/LegacyStateStore-CtwO7fwy.mjs.map +1 -0
  17. package/dist/{LocalStateStore-CU-O0SBp.mjs → LocalStateStore-D40_SDmJ.mjs} +2 -2
  18. package/dist/{LocalStateStore-CU-O0SBp.mjs.map → LocalStateStore-D40_SDmJ.mjs.map} +1 -1
  19. package/dist/{LocalStateStore-BBeTlRTH.cjs → LocalStateStore-oX_zxj9V.cjs} +2 -2
  20. package/dist/{LocalStateStore-BBeTlRTH.cjs.map → LocalStateStore-oX_zxj9V.cjs.map} +1 -1
  21. package/dist/{OpenApiTsGenerator-B--HV-sW.cjs → OpenApiTsGenerator-CS_RtWOz.cjs} +2 -2
  22. package/dist/{OpenApiTsGenerator-B--HV-sW.cjs.map → OpenApiTsGenerator-CS_RtWOz.cjs.map} +1 -1
  23. package/dist/{OpenApiTsGenerator-CkvsPdgg.mjs → OpenApiTsGenerator-DWAF-7Fu.mjs} +2 -2
  24. package/dist/{OpenApiTsGenerator-CkvsPdgg.mjs.map → OpenApiTsGenerator-DWAF-7Fu.mjs.map} +1 -1
  25. package/dist/{S3StateStore-bwxcI_wQ.mjs → S3StateStore-BzS0IeSt.mjs} +2 -2
  26. package/dist/{S3StateStore-bwxcI_wQ.mjs.map → S3StateStore-BzS0IeSt.mjs.map} +1 -1
  27. package/dist/{S3StateStore-Br8VMY22.cjs → S3StateStore-DeI7jtvi.cjs} +2 -2
  28. package/dist/{S3StateStore-Br8VMY22.cjs.map → S3StateStore-DeI7jtvi.cjs.map} +1 -1
  29. package/dist/{SSMStateStore-DoZE1Wi1.cjs → SSMStateStore-CaCtrzFL.cjs} +2 -2
  30. package/dist/{SSMStateStore-DoZE1Wi1.cjs.map → SSMStateStore-CaCtrzFL.cjs.map} +1 -1
  31. package/dist/{SSMStateStore-CsOS0W1y.mjs → SSMStateStore-k_Ew7TWx.mjs} +2 -2
  32. package/dist/{SSMStateStore-CsOS0W1y.mjs.map → SSMStateStore-k_Ew7TWx.mjs.map} +1 -1
  33. package/dist/{SubscriberGenerator-BPqQf8fB.mjs → SubscriberGenerator-CyN2VF5X.mjs} +6 -5
  34. package/dist/SubscriberGenerator-CyN2VF5X.mjs.map +1 -0
  35. package/dist/{SubscriberGenerator-BVn7cQ-2.cjs → SubscriberGenerator-Dvz7EzqK.cjs} +6 -5
  36. package/dist/SubscriberGenerator-Dvz7EzqK.cjs.map +1 -0
  37. package/dist/{add-BSHk5Ngn.mjs → add-CP1podDH.mjs} +7 -7
  38. package/dist/add-CP1podDH.mjs.map +1 -0
  39. package/dist/{add-DmmBDV2e.cjs → add-VcyJnsPX.cjs} +8 -8
  40. package/dist/add-VcyJnsPX.cjs.map +1 -0
  41. package/dist/{aws-BTawF0F-.cjs → aws-BTReGjpY.cjs} +24 -6
  42. package/dist/aws-BTReGjpY.cjs.map +1 -0
  43. package/dist/{aws-B-6uEhgP.mjs → aws-Dz2bYxK1.mjs} +24 -6
  44. package/dist/aws-Dz2bYxK1.mjs.map +1 -0
  45. package/dist/awsStore-B5We7bMg.cjs +136 -0
  46. package/dist/awsStore-B5We7bMg.cjs.map +1 -0
  47. package/dist/awsStore-BWa1KNY-.mjs +119 -0
  48. package/dist/awsStore-BWa1KNY-.mjs.map +1 -0
  49. package/dist/{bundler-D6eBfVkl.mjs → bundler-BWrh-AJH.mjs} +5 -5
  50. package/dist/{bundler-D6eBfVkl.mjs.map → bundler-BWrh-AJH.mjs.map} +1 -1
  51. package/dist/{bundler-BQJiB7Ub.cjs → bundler-Dfsr6KXU.cjs} +5 -5
  52. package/dist/{bundler-BQJiB7Ub.cjs.map → bundler-Dfsr6KXU.cjs.map} +1 -1
  53. package/dist/{cli-DD-Yk-I5.mjs → cli-B8otnZfX.mjs} +6 -6
  54. package/dist/{cli-DD-Yk-I5.mjs.map → cli-B8otnZfX.mjs.map} +1 -1
  55. package/dist/{cli-BE9mqeX8.cjs → cli-DL19w4OE.cjs} +5 -5
  56. package/dist/{cli-BE9mqeX8.cjs.map → cli-DL19w4OE.cjs.map} +1 -1
  57. package/dist/compose-BHVKLluX.cjs +1523 -0
  58. package/dist/compose-BHVKLluX.cjs.map +1 -0
  59. package/dist/compose-DrEB_4F-.mjs +1476 -0
  60. package/dist/compose-DrEB_4F-.mjs.map +1 -0
  61. package/dist/{config-pST7E0CS.d.cts → config-CHX5GOo3.d.mts} +8 -8
  62. package/dist/{config-CdEcTrjG.d.mts.map → config-CHX5GOo3.d.mts.map} +1 -1
  63. package/dist/{config-CdEcTrjG.d.mts → config-DCCcrOSo.d.cts} +8 -8
  64. package/dist/{config-pST7E0CS.d.cts.map → config-DCCcrOSo.d.cts.map} +1 -1
  65. package/dist/config.cjs +8 -7
  66. package/dist/config.cjs.map +1 -1
  67. package/dist/config.d.cts +3 -3
  68. package/dist/config.d.mts +3 -3
  69. package/dist/config.mjs +8 -7
  70. package/dist/config.mjs.map +1 -1
  71. package/dist/{credentialSchemas-BJqRJNK4.mjs → credentialSchemas-BJFvfkaz.mjs} +5 -4
  72. package/dist/credentialSchemas-BJFvfkaz.mjs.map +1 -0
  73. package/dist/{credentialSchemas-DCR4Wd1W.cjs → credentialSchemas-CAPKFkrG.cjs} +5 -4
  74. package/dist/credentialSchemas-CAPKFkrG.cjs.map +1 -0
  75. package/dist/{credentials-CnVqoXMb.mjs → credentials-C4KII3PD.mjs} +3 -2
  76. package/dist/{credentials-CnVqoXMb.mjs.map → credentials-C4KII3PD.mjs.map} +1 -1
  77. package/dist/{credentials-BKfIugu2.cjs → credentials-QBu7VgaQ.cjs} +3 -2
  78. package/dist/credentials-QBu7VgaQ.cjs.map +1 -0
  79. package/dist/{databases-CzszQV0N.mjs → databases-BeGP5eDh.mjs} +11 -10
  80. package/dist/databases-BeGP5eDh.mjs.map +1 -0
  81. package/dist/{databases-BY-pEImp.cjs → databases-DGALFDG3.cjs} +11 -10
  82. package/dist/databases-DGALFDG3.cjs.map +1 -0
  83. package/dist/{define-DR8xGYfL.mjs → define-6poNqm5O.mjs} +12 -3
  84. package/dist/define-6poNqm5O.mjs.map +1 -0
  85. package/dist/{define-DzRz8FgH.cjs → define-crmMcXFS.cjs} +12 -3
  86. package/dist/define-crmMcXFS.cjs.map +1 -0
  87. package/dist/deploy/public.cjs +18 -16
  88. package/dist/deploy/public.cjs.map +1 -1
  89. package/dist/deploy/public.d.cts +31 -31
  90. package/dist/deploy/public.d.cts.map +1 -1
  91. package/dist/deploy/public.d.mts +31 -31
  92. package/dist/deploy/public.d.mts.map +1 -1
  93. package/dist/deploy/public.mjs +18 -17
  94. package/dist/deploy/public.mjs.map +1 -1
  95. package/dist/{deploy-CuHasEA4.cjs → deploy-C3Mhnmus.cjs} +15 -13
  96. package/dist/deploy-C3Mhnmus.cjs.map +1 -0
  97. package/dist/{deploy-QNtx_eWR.mjs → deploy-DYIyIUYd.mjs} +15 -13
  98. package/dist/deploy-DYIyIUYd.mjs.map +1 -0
  99. package/dist/{discover-D1It5r_h.cjs → discover-DPgu-ScS.cjs} +4 -3
  100. package/dist/discover-DPgu-ScS.cjs.map +1 -0
  101. package/dist/{discover-CU0paUyH.d.cts → discover-DqwlBVyY.d.mts} +2 -2
  102. package/dist/{discover-CU0paUyH.d.cts.map → discover-DqwlBVyY.d.mts.map} +1 -1
  103. package/dist/{discover-BPelzeGW.mjs → discover-qjFapetL.mjs} +4 -3
  104. package/dist/discover-qjFapetL.mjs.map +1 -0
  105. package/dist/{discover-DFiJxwfv.d.mts → discover-vk2r5giK.d.cts} +2 -2
  106. package/dist/{discover-DFiJxwfv.d.mts.map → discover-vk2r5giK.d.cts.map} +1 -1
  107. package/dist/{dokploy-CYcMLh9-.mjs → dokploy-o4I6vb9W.mjs} +3 -3
  108. package/dist/{dokploy-CYcMLh9-.mjs.map → dokploy-o4I6vb9W.mjs.map} +1 -1
  109. package/dist/{dokploy-DIowwyIB.cjs → dokploy-rivb1RFt.cjs} +3 -3
  110. package/dist/{dokploy-DIowwyIB.cjs.map → dokploy-rivb1RFt.cjs.map} +1 -1
  111. package/dist/{drivers-DTZzxeIl.mjs → drivers-CTaWrA_L.mjs} +2 -2
  112. package/dist/{drivers-DTZzxeIl.mjs.map → drivers-CTaWrA_L.mjs.map} +1 -1
  113. package/dist/{drivers-LYSdQDmd.cjs → drivers-DDojgzz0.cjs} +2 -2
  114. package/dist/{drivers-LYSdQDmd.cjs.map → drivers-DDojgzz0.cjs.map} +1 -1
  115. package/dist/{encryption-BrEef7Jk.mjs → encryption-B6ilrT7p.mjs} +7 -6
  116. package/dist/encryption-B6ilrT7p.mjs.map +1 -0
  117. package/dist/{encryption-CjYdUb2s.cjs → encryption-D7zmwzWz.cjs} +7 -6
  118. package/dist/encryption-D7zmwzWz.cjs.map +1 -0
  119. package/dist/{engine-BhJ7ZP9K.cjs → engine-Cfx8fEZU.cjs} +40 -28
  120. package/dist/engine-Cfx8fEZU.cjs.map +1 -0
  121. package/dist/{engine-2h4k5ICq.mjs → engine-DjEcovm-.mjs} +40 -28
  122. package/dist/engine-DjEcovm-.mjs.map +1 -0
  123. package/dist/errors-D8Gwp5kU.mjs +23 -0
  124. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  125. package/dist/errors-DMC4Umsb.cjs +34 -0
  126. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  127. package/dist/{github-BCDF6xVH.mjs → github-CzBbs43W.mjs} +31 -9
  128. package/dist/github-CzBbs43W.mjs.map +1 -0
  129. package/dist/{github-B5Bw4HIu.cjs → github-zneTMvnO.cjs} +31 -9
  130. package/dist/github-zneTMvnO.cjs.map +1 -0
  131. package/dist/{index-YFNxR5Ns.d.mts → index-BiYU7cUl.d.mts} +6 -6
  132. package/dist/{index-D-F_hTDz.d.cts.map → index-BiYU7cUl.d.mts.map} +1 -1
  133. package/dist/{index-D-F_hTDz.d.cts → index-Dm6V9bwh.d.cts} +6 -6
  134. package/dist/{index-YFNxR5Ns.d.mts.map → index-Dm6V9bwh.d.cts.map} +1 -1
  135. package/dist/index.cjs +256 -346
  136. package/dist/index.cjs.map +1 -1
  137. package/dist/index.mjs +252 -341
  138. package/dist/index.mjs.map +1 -1
  139. package/dist/{local-BjxDfPvy.cjs → local-B61kUh0w.cjs} +3 -3
  140. package/dist/{local-BjxDfPvy.cjs.map → local-B61kUh0w.cjs.map} +1 -1
  141. package/dist/{local-IuoIF3CT.mjs → local-Otp74ak0.mjs} +3 -3
  142. package/dist/{local-IuoIF3CT.mjs.map → local-Otp74ak0.mjs.map} +1 -1
  143. package/dist/{migrate-DWZz9kah.mjs → migrate-BaC4w0sb.mjs} +8 -7
  144. package/dist/migrate-BaC4w0sb.mjs.map +1 -0
  145. package/dist/{migrate-q2YYLJLE.cjs → migrate-C8wTpakT.cjs} +8 -7
  146. package/dist/migrate-C8wTpakT.cjs.map +1 -0
  147. package/dist/{migrate-DbtcuOr_.mjs → migrate-CsBZKALY.mjs} +9 -8
  148. package/dist/migrate-CsBZKALY.mjs.map +1 -0
  149. package/dist/{migrate-CGaancHY.cjs → migrate-DFjbGnSr.cjs} +8 -7
  150. package/dist/migrate-DFjbGnSr.cjs.map +1 -0
  151. package/dist/openapi.cjs +3 -3
  152. package/dist/openapi.d.cts +1 -10
  153. package/dist/openapi.d.cts.map +1 -1
  154. package/dist/openapi.d.mts +1 -10
  155. package/dist/openapi.d.mts.map +1 -1
  156. package/dist/openapi.mjs +3 -3
  157. package/dist/{provider-C9_-45d5.cjs → provider-BqpjG9QM.cjs} +4 -3
  158. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  159. package/dist/{provider-q4lsYzYG.mjs → provider-CEOKk8NS.mjs} +4 -3
  160. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  161. package/dist/{ready-BpNbORRB.cjs → ready-D3PIjx3S.cjs} +9 -8
  162. package/dist/ready-D3PIjx3S.cjs.map +1 -0
  163. package/dist/{ready-b6vm0-W-.mjs → ready-naOSJpeJ.mjs} +9 -8
  164. package/dist/ready-naOSJpeJ.mjs.map +1 -0
  165. package/dist/reconcile/public.cjs +1 -1
  166. package/dist/reconcile/public.d.cts +2 -2
  167. package/dist/reconcile/public.d.mts +2 -2
  168. package/dist/reconcile/public.mjs +1 -1
  169. package/dist/{reconcile-Dh1Jk7WE.mjs → reconcile--I7V4Klj.mjs} +2 -2
  170. package/dist/{reconcile-Dh1Jk7WE.mjs.map → reconcile--I7V4Klj.mjs.map} +1 -1
  171. package/dist/{resolve-DNg0icnh.mjs → resolve-Ccjlpnd9.mjs} +12 -11
  172. package/dist/resolve-Ccjlpnd9.mjs.map +1 -0
  173. package/dist/{resolve-Cns0v6dN.cjs → resolve-g8htuR80.cjs} +12 -11
  174. package/dist/resolve-g8htuR80.cjs.map +1 -0
  175. package/dist/{rollback-UIjS25F1.cjs → rollback--ympG9ss.cjs} +13 -11
  176. package/dist/rollback--ympG9ss.cjs.map +1 -0
  177. package/dist/{rollback-CFrNLmxs.mjs → rollback-Drbg0OeR.mjs} +13 -11
  178. package/dist/rollback-Drbg0OeR.mjs.map +1 -0
  179. package/dist/{runtime-CN_kmqxo.d.cts → runtime-D_J3ExJn.d.cts} +11 -19
  180. package/dist/runtime-D_J3ExJn.d.cts.map +1 -0
  181. package/dist/{runtime-Cjvon3oj.d.mts → runtime-_wEVtshH.d.mts} +11 -19
  182. package/dist/runtime-_wEVtshH.d.mts.map +1 -0
  183. package/dist/sandbox/credentials-worker.cjs +3 -3
  184. package/dist/sandbox/credentials-worker.mjs +3 -3
  185. package/dist/sandbox/discover-worker.cjs +1 -1
  186. package/dist/sandbox/discover-worker.mjs +1 -1
  187. package/dist/sandbox/migrate-worker.cjs +3 -3
  188. package/dist/sandbox/migrate-worker.mjs +3 -3
  189. package/dist/{sandbox-CL--ZDui.cjs → sandbox-CHv3OYXg.cjs} +4 -3
  190. package/dist/sandbox-CHv3OYXg.cjs.map +1 -0
  191. package/dist/{sandbox-M8UnLhXE.d.cts → sandbox-CPJq1Kia.d.mts} +4 -26
  192. package/dist/sandbox-CPJq1Kia.d.mts.map +1 -0
  193. package/dist/{sandbox-Dm247NGx.mjs → sandbox-CbVB7uOD.mjs} +4 -3
  194. package/dist/sandbox-CbVB7uOD.mjs.map +1 -0
  195. package/dist/{sandbox-M8UnLhXE.d.mts → sandbox-JwuPAl7I.d.cts} +4 -26
  196. package/dist/sandbox-JwuPAl7I.d.cts.map +1 -0
  197. package/dist/secrets-DJteijZo.cjs +47 -0
  198. package/dist/secrets-DJteijZo.cjs.map +1 -0
  199. package/dist/secrets-DbPmAS4k.mjs +36 -0
  200. package/dist/secrets-DbPmAS4k.mjs.map +1 -0
  201. package/dist/{secretsManager-Chs9VV2r.mjs → secretsManager-C6wm-9uZ.mjs} +24 -3
  202. package/dist/secretsManager-C6wm-9uZ.mjs.map +1 -0
  203. package/dist/{secretsManager-DcMlHnRC.cjs → secretsManager-Cwwgs81g.cjs} +24 -3
  204. package/dist/secretsManager-Cwwgs81g.cjs.map +1 -0
  205. package/dist/{seeds-odfgSCmu.mjs → seeds-BSL55F6q.mjs} +946 -107
  206. package/dist/seeds-BSL55F6q.mjs.map +1 -0
  207. package/dist/{seeds-CkIPFGNO.cjs → seeds-c-ByX9je.cjs} +1065 -130
  208. package/dist/seeds-c-ByX9je.cjs.map +1 -0
  209. package/dist/{sniffer-BTtX3NUM.mjs → sniffer-BTtGAtm3.mjs} +14 -8
  210. package/dist/sniffer-BTtGAtm3.mjs.map +1 -0
  211. package/dist/{sniffer-IAQEpsQb.cjs → sniffer-Dq5BS98f.cjs} +14 -8
  212. package/dist/{sniffer-IAQEpsQb.cjs.map → sniffer-Dq5BS98f.cjs.map} +1 -1
  213. package/dist/{sst-CJzvyrEz.mjs → sst-BaRXp2Dd.mjs} +18 -8
  214. package/dist/sst-BaRXp2Dd.mjs.map +1 -0
  215. package/dist/{sst-BgcOsaBi.cjs → sst-CnKY-CSh.cjs} +18 -8
  216. package/dist/sst-CnKY-CSh.cjs.map +1 -0
  217. package/dist/stack-1PeLJS2j.cjs +1346 -0
  218. package/dist/stack-1PeLJS2j.cjs.map +1 -0
  219. package/dist/stack-Co4uZkAo.mjs +1239 -0
  220. package/dist/stack-Co4uZkAo.mjs.map +1 -0
  221. package/dist/{stages-CUn6gvXL.cjs → stages-BI8JvPzI.cjs} +6 -5
  222. package/dist/stages-BI8JvPzI.cjs.map +1 -0
  223. package/dist/{stages-CnZRYmkI.mjs → stages-DY-fQKmo.mjs} +6 -5
  224. package/dist/stages-DY-fQKmo.mjs.map +1 -0
  225. package/dist/target/public.cjs +3 -3
  226. package/dist/target/public.d.cts +2 -2
  227. package/dist/target/public.d.mts +2 -2
  228. package/dist/target/public.mjs +3 -3
  229. package/dist/{terminal-DuapRxh6.cjs → terminal-8XngdSTo.cjs} +6 -5
  230. package/dist/terminal-8XngdSTo.cjs.map +1 -0
  231. package/dist/{terminal-D8TPK7o9.mjs → terminal-C4XRdwnU.mjs} +7 -6
  232. package/dist/terminal-C4XRdwnU.mjs.map +1 -0
  233. package/dist/{types-NqX1Hz4P.d.cts → types-B6lmD3en.d.mts} +94 -47
  234. package/dist/types-B6lmD3en.d.mts.map +1 -0
  235. package/dist/{types-ZHuZ89hv.d.mts → types-BibpiHKB.d.cts} +95 -46
  236. package/dist/types-BibpiHKB.d.cts.map +1 -0
  237. package/dist/vitest.cjs +1 -1
  238. package/dist/vitest.mjs +1 -1
  239. package/dist/workspace/index.cjs +1 -1
  240. package/dist/workspace/index.d.cts +2 -2
  241. package/dist/workspace/index.d.mts +2 -2
  242. package/dist/workspace/index.mjs +1 -1
  243. package/dist/{workspace-CJ0lKFq-.mjs → workspace-Bzw7Zs82.mjs} +34 -33
  244. package/dist/workspace-Bzw7Zs82.mjs.map +1 -0
  245. package/dist/{workspace-CwW3Gkru.cjs → workspace-CHOB2Xg3.cjs} +34 -33
  246. package/dist/workspace-CHOB2Xg3.cjs.map +1 -0
  247. package/package.json +15 -15
  248. package/dist/EndpointGenerator-CVc6Oi1Y.mjs.map +0 -1
  249. package/dist/EndpointGenerator-CwLjBCFE.cjs.map +0 -1
  250. package/dist/GoDaddyProvider-DSStJVAv.mjs.map +0 -1
  251. package/dist/GoDaddyProvider-DqZ1qD_F.cjs.map +0 -1
  252. package/dist/LegacyStateStore-DXmNA7hy.cjs.map +0 -1
  253. package/dist/LegacyStateStore-ZkdmiUFZ.mjs +0 -89
  254. package/dist/LegacyStateStore-ZkdmiUFZ.mjs.map +0 -1
  255. package/dist/SubscriberGenerator-BPqQf8fB.mjs.map +0 -1
  256. package/dist/SubscriberGenerator-BVn7cQ-2.cjs.map +0 -1
  257. package/dist/add-BSHk5Ngn.mjs.map +0 -1
  258. package/dist/add-DmmBDV2e.cjs.map +0 -1
  259. package/dist/aws-B-6uEhgP.mjs.map +0 -1
  260. package/dist/aws-BTawF0F-.cjs.map +0 -1
  261. package/dist/awsStore-7VmS_cZR.cjs +0 -54
  262. package/dist/awsStore-7VmS_cZR.cjs.map +0 -1
  263. package/dist/awsStore-B529csle.mjs +0 -43
  264. package/dist/awsStore-B529csle.mjs.map +0 -1
  265. package/dist/compose-Bhmf0n4o.mjs +0 -3140
  266. package/dist/compose-Bhmf0n4o.mjs.map +0 -1
  267. package/dist/compose-CvpU6ooi.cjs +0 -3265
  268. package/dist/compose-CvpU6ooi.cjs.map +0 -1
  269. package/dist/credentialSchemas-BJqRJNK4.mjs.map +0 -1
  270. package/dist/credentialSchemas-DCR4Wd1W.cjs.map +0 -1
  271. package/dist/credentials-BKfIugu2.cjs.map +0 -1
  272. package/dist/databases-BY-pEImp.cjs.map +0 -1
  273. package/dist/databases-CzszQV0N.mjs.map +0 -1
  274. package/dist/define-DR8xGYfL.mjs.map +0 -1
  275. package/dist/define-DzRz8FgH.cjs.map +0 -1
  276. package/dist/deploy-CuHasEA4.cjs.map +0 -1
  277. package/dist/deploy-QNtx_eWR.mjs.map +0 -1
  278. package/dist/discover-BPelzeGW.mjs.map +0 -1
  279. package/dist/discover-D1It5r_h.cjs.map +0 -1
  280. package/dist/encryption-BrEef7Jk.mjs.map +0 -1
  281. package/dist/encryption-CjYdUb2s.cjs.map +0 -1
  282. package/dist/engine-2h4k5ICq.mjs.map +0 -1
  283. package/dist/engine-BhJ7ZP9K.cjs.map +0 -1
  284. package/dist/github-B5Bw4HIu.cjs.map +0 -1
  285. package/dist/github-BCDF6xVH.mjs.map +0 -1
  286. package/dist/migrate-CGaancHY.cjs.map +0 -1
  287. package/dist/migrate-DWZz9kah.mjs.map +0 -1
  288. package/dist/migrate-DbtcuOr_.mjs.map +0 -1
  289. package/dist/migrate-q2YYLJLE.cjs.map +0 -1
  290. package/dist/provider-C9_-45d5.cjs.map +0 -1
  291. package/dist/provider-q4lsYzYG.mjs.map +0 -1
  292. package/dist/ready-BpNbORRB.cjs.map +0 -1
  293. package/dist/ready-b6vm0-W-.mjs.map +0 -1
  294. package/dist/resolve-Cns0v6dN.cjs.map +0 -1
  295. package/dist/resolve-DNg0icnh.mjs.map +0 -1
  296. package/dist/rollback-CFrNLmxs.mjs.map +0 -1
  297. package/dist/rollback-UIjS25F1.cjs.map +0 -1
  298. package/dist/runtime-CN_kmqxo.d.cts.map +0 -1
  299. package/dist/runtime-Cjvon3oj.d.mts.map +0 -1
  300. package/dist/sandbox-CL--ZDui.cjs.map +0 -1
  301. package/dist/sandbox-Dm247NGx.mjs.map +0 -1
  302. package/dist/sandbox-M8UnLhXE.d.cts.map +0 -1
  303. package/dist/sandbox-M8UnLhXE.d.mts.map +0 -1
  304. package/dist/secretsManager-Chs9VV2r.mjs.map +0 -1
  305. package/dist/secretsManager-DcMlHnRC.cjs.map +0 -1
  306. package/dist/seeds-CkIPFGNO.cjs.map +0 -1
  307. package/dist/seeds-odfgSCmu.mjs.map +0 -1
  308. package/dist/sniffer-BTtX3NUM.mjs.map +0 -1
  309. package/dist/sst-BgcOsaBi.cjs.map +0 -1
  310. package/dist/sst-CJzvyrEz.mjs.map +0 -1
  311. package/dist/stages-CUn6gvXL.cjs.map +0 -1
  312. package/dist/stages-CnZRYmkI.mjs.map +0 -1
  313. package/dist/terminal-D8TPK7o9.mjs.map +0 -1
  314. package/dist/terminal-DuapRxh6.cjs.map +0 -1
  315. package/dist/types-NqX1Hz4P.d.cts.map +0 -1
  316. package/dist/types-ZHuZ89hv.d.mts.map +0 -1
  317. package/dist/workspace-CJ0lKFq-.mjs.map +0 -1
  318. package/dist/workspace-CwW3Gkru.cjs.map +0 -1
@@ -1,4 +1,5 @@
1
- import { u as ConstructGenerator } from "./discover-BPelzeGW.mjs";
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { u as ConstructGenerator } from "./discover-qjFapetL.mjs";
2
3
  import { dirname, join, relative, resolve } from "node:path";
3
4
  import { existsSync, realpathSync } from "node:fs";
4
5
  import { mkdir, writeFile } from "node:fs/promises";
@@ -64,7 +65,7 @@ function missingTelemetryPackages(appRoot) {
64
65
  * Failed at build, not at startup: a process that was given telemetry and
65
66
  * quietly ran without it is an outage nobody can see into.
66
67
  */
67
- var TelemetryPackagesMissing = class extends Error {
68
+ var TelemetryPackagesMissing = class extends GkmError {
68
69
  app;
69
70
  missing;
70
71
  dir;
@@ -287,8 +288,17 @@ async function writeTelemetryModule(outputDir, telemetry) {
287
288
  }
288
289
  //#endregion
289
290
  //#region src/generators/clientTelemetry.ts
291
+ /**
292
+ * Whether a generated client propagates trace context by default.
293
+ *
294
+ * `false` (the default) prints a client that sends no trace headers unless
295
+ * its caller passes `telemetry`. Anything else prints that default into
296
+ * `createApi`: `true`, or `{ sampleRate }` — the stage's rate, for the page
297
+ * views no OpenTelemetry SDK is tracing. A caller's own `telemetry` option
298
+ * still wins.
299
+ */
290
300
  /** A `sampleRate` outside 0–1, which no sampler can honour. */
291
- var InvalidClientTelemetrySampleRate = class extends Error {
301
+ var InvalidClientTelemetrySampleRate = class extends GkmError {
292
302
  sampleRate;
293
303
  constructor(sampleRate) {
294
304
  super(`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`);
@@ -1018,4 +1028,4 @@ await start({
1018
1028
  //#endregion
1019
1029
  export { telemetryArgs as a, startTelemetryCode as c, printTelemetryDefault as i, telemetryFor as l, runtimeFor as n, mountRequestSpansCode as o, parseTelemetryFlag as r, routeTelemetry as s, EndpointGenerator as t, writeTelemetryModule as u };
1020
1030
 
1021
- //# sourceMappingURL=EndpointGenerator-CVc6Oi1Y.mjs.map
1031
+ //# sourceMappingURL=EndpointGenerator-Bor2tZCm.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EndpointGenerator-Bor2tZCm.mjs","names":[],"sources":["../src/generators/telemetry.ts","../src/generators/clientTelemetry.ts","../src/generators/EndpointGenerator.ts"],"sourcesContent":["import { existsSync, realpathSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport type { TelemetryDeclaration } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\n\n/**\n * One route's own telemetry — an endpoint's `.telemetry({ ignore, attributes })`.\n */\nexport interface TelemetryRoute {\n\tmethod: string;\n\t/** The route as the surface serves it — `/users/:id`. */\n\tpath: string;\n\tignore?: boolean;\n\tattributes?: Readonly<Record<string, string>>;\n}\n\n/** Each endpoint's own `.telemetry({ ignore, attributes })`, as routes. */\nexport function routeTelemetry(\n\tendpoints: readonly {\n\t\tmethod: string;\n\t\troute: string;\n\t\ttelemetry?: Omit<TelemetryRoute, 'method' | 'path'>;\n\t}[],\n): TelemetryRoute[] {\n\treturn endpoints.flatMap((endpoint) =>\n\t\tendpoint.telemetry\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t\t\tpath: endpoint.route,\n\t\t\t\t\t\t...endpoint.telemetry,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: [],\n\t);\n}\n\n/**\n * What an entry starts OpenTelemetry with, decided at build time from the\n * process's edge to a `Telemetry` node.\n *\n * Only built for a process with that edge — every other process gets the\n * stub, which loads nothing — and only once the packages it needs resolve:\n * a process that uses the node and cannot load them fails the build with\n * {@link TelemetryPackagesMissing}.\n */\nexport interface TelemetryContext {\n\t/** `service.name` — the surface or worker; `OTEL_SERVICE_NAME` overrides it. */\n\tserviceName: string;\n\t/** `service.namespace` — the workspace the app is part of. */\n\tserviceNamespace?: string;\n\t/** The node's `ignorePaths`. */\n\tignorePaths: readonly string[];\n\t/** The node's `attributes`, on every span and log record. */\n\tattributes: Readonly<Record<string, string>>;\n\t/** Each route that says something of its own. */\n\troutes: readonly TelemetryRoute[];\n}\n\n/**\n * Every package `@geekmidas/telescope/instrumentation` loads at runtime.\n *\n * All of them, rather than one as a proxy: the production bundle follows each\n * import, and a single missing one fails the build rather than the telemetry.\n */\nexport const TELEMETRY_PACKAGES = [\n\t'@opentelemetry/api',\n\t'@opentelemetry/auto-instrumentations-node',\n\t'@opentelemetry/exporter-logs-otlp-http',\n\t'@opentelemetry/exporter-trace-otlp-http',\n\t'@opentelemetry/instrumentation-pino',\n\t'@opentelemetry/resources',\n\t'@opentelemetry/sdk-logs',\n\t'@opentelemetry/sdk-node',\n\t'@opentelemetry/sdk-trace-base',\n\t'@opentelemetry/sdk-trace-node',\n\t'@opentelemetry/semantic-conventions',\n] as const;\n\n/**\n * The directory of `name` as `node_modules` lookup finds it from `fromDir`,\n * symlinks resolved — or undefined.\n *\n * The directory walk alone, not `require.resolve`: that also searches\n * `NODE_PATH`, which a package manager's bin shim sets to its own store, so a\n * `gkm build` run through one would find packages the app never installed —\n * and the bundler, which does not look there, would then fail on them.\n */\nfunction packageDir(fromDir: string, name: string): string | undefined {\n\tfor (let dir = resolve(fromDir); ; dir = dirname(dir)) {\n\t\tconst candidate = join(dir, 'node_modules', name);\n\t\tif (existsSync(join(candidate, 'package.json'))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tif (dirname(dir) === dir) return undefined;\n\t}\n}\n\n/**\n * The telemetry packages that do not resolve the way the bundler will resolve\n * them — telescope from the app, and the OpenTelemetry packages from\n * telescope, where a peer is linked under pnpm, which need not be where the\n * app sees it. Empty when every one does.\n */\nexport function missingTelemetryPackages(appRoot: string): string[] {\n\tconst telescope = packageDir(appRoot, '@geekmidas/telescope');\n\tif (!telescope) return ['@geekmidas/telescope', ...TELEMETRY_PACKAGES];\n\n\treturn TELEMETRY_PACKAGES.filter((pkg) => !packageDir(telescope, pkg));\n}\n\n/**\n * An app uses a `Telemetry` construct and cannot load what it needs to.\n *\n * Failed at build, not at startup: a process that was given telemetry and\n * quietly ran without it is an outage nobody can see into.\n */\nexport class TelemetryPackagesMissing extends GkmError {\n\treadonly command: string;\n\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly missing: readonly string[],\n\t\t/** The app's directory, relative to where the command is run. */\n\t\treadonly dir: string,\n\t) {\n\t\tconst command = `pnpm --dir ${dir || '.'} add ${missing.join(' ')}`;\n\t\tsuper(\n\t\t\t`'${app}' uses a Telemetry construct, and ${missing.join(', ')} ` +\n\t\t\t\t`${missing.length === 1 ? 'does' : 'do'} not resolve from it — its ` +\n\t\t\t\t'server would start without exporting a span. Add them to the app ' +\n\t\t\t\t`and build again:\\n\\n ${command}\\n`,\n\t\t);\n\t\tthis.name = 'TelemetryPackagesMissing';\n\t\tthis.command = command;\n\t}\n}\n\n/**\n * The telemetry half of a build context: undefined for a process with no\n * edge to a `Telemetry` node, and — for one with an edge — what its entry\n * starts with, once every package it needs resolves.\n */\nexport function telemetryFor(options: {\n\t/** The node the process emits through — see `telemetryOf`. */\n\tnode: TelemetryDeclaration | undefined;\n\tappRoot: string;\n\t/** The app's name, for the error. */\n\tapp: string;\n\t/** Where `pnpm` is run from, for the error's command. */\n\tcwd?: string;\n\tserviceName: string;\n\tworkspaceName?: string;\n\troutes?: readonly TelemetryRoute[];\n}): TelemetryContext | undefined {\n\tconst { node } = options;\n\tif (!node) return undefined;\n\n\tconst missing = missingTelemetryPackages(options.appRoot);\n\tif (missing.length > 0) {\n\t\tthrow new TelemetryPackagesMissing(\n\t\t\toptions.app,\n\t\t\tmissing,\n\t\t\trelative(options.cwd ?? process.cwd(), options.appRoot),\n\t\t);\n\t}\n\n\treturn {\n\t\tserviceName: options.serviceName,\n\t\t...(options.workspaceName && { serviceNamespace: options.workspaceName }),\n\t\tignorePaths: [...(node.ignorePaths ?? [])],\n\t\tattributes: { ...node.attributes },\n\t\troutes: [...(options.routes ?? [])],\n\t};\n}\n\nconst HEADER = `/**\n * Generated by gkm, for the production entry and the \\`gkm dev\\` one alike.\n *\n * Starts OpenTelemetry when OTEL_EXPORTER_OTLP_ENDPOINT names a collector, and\n * does nothing otherwise: without it, the telemetry packages are not loaded.\n * The standard OTEL_* variables (OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG,\n * OTEL_EXPORTER_OTLP_HEADERS, OTEL_RESOURCE_ATTRIBUTES, OTEL_SERVICE_NAME)\n * configure the rest.\n */\n\nimport type { MiddlewareHandler } from 'hono';\n\nexport interface StartTelemetryOptions {\n /** Requests whose spans would only be noise: health checks, by default. */\n ignorePaths?: string[];\n /**\n * The API's own sites — the origins its CORS allows — read on each request.\n * Their \\`traceparent\\` is continued, as is an internal caller's; anyone\n * else's starts a new trace linked to the one it claimed.\n */\n trustedOrigins?: () => readonly string[];\n}\n`;\n\n/** `/users/:id` as a pattern over a request's path. */\nfunction routePattern(path: string): string {\n\tconst body = path\n\t\t.split('/')\n\t\t.map((segment) => {\n\t\t\tif (segment.startsWith(':')) return '[^/]+';\n\t\t\tif (segment === '*') return '.*';\n\t\t\treturn segment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\t\t})\n\t\t.join('/');\n\treturn `^${body}/?$`;\n}\n\n/**\n * The entry's `telemetry.ts`: a `startTelemetry()` the server awaits before it\n * imports the app, so the libraries the app loads are instrumented. It returns\n * the Hono middleware that traces each request, or undefined when telemetry is\n * off — the server mounts it ahead of every route.\n *\n * Without a context — a process with no edge to a `Telemetry` node — it is a\n * stub that loads nothing and says nothing: telemetry is not something that\n * process was given.\n *\n * Failing to start telemetry warns (a named `TelemetryUnavailable`, through\n * `process.emitWarning`) and never stops the server: an outage in observability\n * is not a reason to have an outage in the service.\n */\nexport function generateTelemetryModule(\n\ttelemetry: TelemetryContext | undefined,\n): string {\n\tif (!telemetry) {\n\t\treturn `${HEADER}\n// This process has no Telemetry construct, so there is nothing to start.\nexport async function startTelemetry(\n _options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n return undefined;\n}\n`;\n\t}\n\n\tconst options = [\n\t\t`serviceName: ${JSON.stringify(telemetry.serviceName)},`,\n\t\t...(telemetry.serviceNamespace\n\t\t\t? [`serviceNamespace: ${JSON.stringify(telemetry.serviceNamespace)},`]\n\t\t\t: []),\n\t\t// The stage the deploy set, so one service's stages stay apart.\n\t\t'deploymentEnvironment: process.env.STAGE,',\n\t\t...(Object.keys(telemetry.attributes).length\n\t\t\t? [`resourceAttributes: ${JSON.stringify(telemetry.attributes)},`]\n\t\t\t: []),\n\t\t// The exporters read OTEL_EXPORTER_OTLP_* themselves, and the SDK reads\n\t\t// OTEL_TRACES_SAMPLER — so no endpoint and no ratio are printed here.\n\t\t// The server's own shutdown decides when the process exits.\n\t\t'handleSignals: false,',\n\t\t// Neither is left to module-load hooks, which see nothing inside a\n\t\t// bundle: @geekmidas/logger emits each record through the logs API\n\t\t// itself, and the middleware returned below opens each request's span.\n\t\t// Hooked as well where they can be, every record and request would be\n\t\t// sent twice.\n\t\t'instrumentPino: false,',\n\t\t'incomingHttpSpans: false,',\n\t];\n\n\tconst routes = telemetry.routes.map((route) => ({\n\t\tmethod: route.method.toUpperCase(),\n\t\tpattern: routePattern(route.path),\n\t\t...(route.ignore ? { ignore: true } : {}),\n\t\t...(route.attributes && Object.keys(route.attributes).length\n\t\t\t? { attributes: route.attributes }\n\t\t\t: {}),\n\t}));\n\tconst withAttributes = routes.some((route) => 'attributes' in route);\n\n\treturn `${HEADER}\n/** Telemetry was asked for and cannot start. The server runs without it. */\nexport class TelemetryUnavailable extends Error {\n constructor(readonly reason: string, options?: { cause?: unknown }) {\n super(\n \\`OTEL_EXPORTER_OTLP_ENDPOINT is set, but \\${reason} This server exports no traces or logs until that is fixed.\\`,\n options,\n );\n this.name = 'TelemetryUnavailable';\n }\n}\n\n/** The Telemetry construct's own ignored paths, beside the entry's. */\nconst IGNORE_PATHS: string[] = ${JSON.stringify(telemetry.ignorePaths)};\n\n/** Each route's own .telemetry({ ignore, attributes }). */\nconst ROUTES: {\n method: string;\n pattern: string;\n ignore?: boolean;\n attributes?: Record<string, string>;\n}[] = ${JSON.stringify(routes)};\n\nconst MATCHERS = ROUTES.map((route) => ({ ...route, regex: new RegExp(route.pattern) }));\n\nfunction routeOf(method: string, path: string) {\n return MATCHERS.find(\n (route) => (route.method === method || route.method === 'ALL' || route.method === 'ANY') && route.regex.test(path),\n );\n}\n\nexport async function startTelemetry(\n options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT) return undefined;\n\n let instrumentation;\n try {\n instrumentation = await import('@geekmidas/telescope/instrumentation');\n } catch (cause) {\n process.emitWarning(\n new TelemetryUnavailable(\n '@geekmidas/telescope/instrumentation or an @opentelemetry package it needs could not be loaded. Install them in the app and rebuild.',\n { cause },\n ),\n );\n return undefined;\n }\n\n instrumentation.setupTelemetry({\n ${options.join('\\n ')}\n });\n\n // Flush what is buffered when the process is told to stop. When nothing\n // else handles the signal, re-raise it once flushed, so the process still\n // stops the way it would have without this listener.\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.once(signal, () => {\n void instrumentation.flushTelemetry().finally(() => {\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n });\n });\n }\n\n // A SERVER span per request, opened by the app itself rather than by\n // hooking node:http: \\`GET /users/:id\\`, continuing an incoming traceparent\n // from the API's own sites and internal callers (a new, linked trace from\n // anyone else), with the handler — its logs, fetches and queries — running\n // inside it.\n const spans = instrumentation.honoTelemetryMiddleware({\n ignorePaths: [...(options.ignorePaths ?? []), ...IGNORE_PATHS],\n trustedOrigins: options.trustedOrigins,\n ...(MATCHERS.some((route) => route.ignore)\n ? { shouldSkip: (c) => routeOf(c.req.method, c.req.path)?.ignore === true }\n : {}),\n });\n${\n\twithAttributes\n\t\t? `\n // A route's own attributes, on the span the middleware just opened.\n const { trace } = await import('@opentelemetry/api');\n return (c, next) =>\n spans(c, async () => {\n const attributes = routeOf(c.req.method, c.req.path)?.attributes;\n if (attributes) trace.getActiveSpan()?.setAttributes(attributes);\n await next();\n });\n`\n\t\t: ` return spans;\n`\n}}\n`;\n}\n\n/**\n * What an entry starts telemetry with, before it imports the app — shared by\n * the production server, a self-serving surface's server and the `gkm dev`\n * entry, so the three cannot start it differently. Defines `requestSpans`.\n */\nexport function startTelemetryCode(ignorePaths: readonly string[]): string {\n\treturn `// The API's own sites, known once the app has read its configuration: the\n// origins its CORS allows are the ones whose trace context is continued.\nlet trustedOrigins: readonly string[] = [];\n\n// Before the app is imported, so the libraries it loads are instrumented.\nconst { startTelemetry } = await import('./telemetry.js');\nconst requestSpans = await startTelemetry({\n ignorePaths: ${JSON.stringify(ignorePaths)},\n trustedOrigins: () => trustedOrigins,\n});\n`;\n}\n\n/** Mounts `requestSpans` on `app` ahead of every route. */\nexport function mountRequestSpansCode(app: string): string {\n\treturn `// The span middleware goes on before any route, so every request runs in it.\nif (requestSpans) ${app}.use('*', requestSpans);\n`;\n}\n\n/** Writes the entry's `telemetry.ts` beside it. */\nexport async function writeTelemetryModule(\n\toutputDir: string,\n\ttelemetry: TelemetryContext | undefined,\n): Promise<void> {\n\tawait mkdir(outputDir, { recursive: true });\n\tawait writeFile(\n\t\tjoin(outputDir, 'telemetry.ts'),\n\t\tgenerateTelemetryModule(telemetry),\n\t);\n}\n","/**\n * Whether a generated client propagates trace context by default.\n *\n * `false` (the default) prints a client that sends no trace headers unless\n * its caller passes `telemetry`. Anything else prints that default into\n * `createApi`: `true`, or `{ sampleRate }` — the stage's rate, for the page\n * views no OpenTelemetry SDK is tracing. A caller's own `telemetry` option\n * still wins.\n */\n\nimport { GkmError } from '../errors';\nexport type ClientTelemetryDefault = boolean | { sampleRate: number };\n\n/** A `sampleRate` outside 0–1, which no sampler can honour. */\nexport class InvalidClientTelemetrySampleRate extends GkmError {\n\tconstructor(readonly sampleRate: number) {\n\t\tsuper(\n\t\t\t`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`,\n\t\t);\n\t\tthis.name = 'InvalidClientTelemetrySampleRate';\n\t}\n}\n\n/** The `telemetry` default as the generated module prints it. */\nexport function printTelemetryDefault(\n\ttelemetry: ClientTelemetryDefault,\n): string {\n\tif (typeof telemetry === 'boolean') return String(telemetry);\n\tconst { sampleRate } = telemetry;\n\tif (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) {\n\t\tthrow new InvalidClientTelemetrySampleRate(sampleRate);\n\t}\n\treturn `{ sampleRate: ${sampleRate} }`;\n}\n\n/**\n * `--telemetry [rate]` for a client default, as `gkm openapi` takes it — and\n * as a site's Dockerfile passes it to the `gkm openapi --app` it runs.\n */\nexport function telemetryArgs(telemetry?: ClientTelemetryDefault): string[] {\n\tif (!telemetry) return [];\n\tif (telemetry === true) return ['--telemetry'];\n\treturn ['--telemetry', String(telemetry.sampleRate)];\n}\n\n/** What `--telemetry [rate]` parsed to: on, at a rate when one was given. */\nexport function parseTelemetryFlag(\n\tvalue: boolean | string | undefined,\n): ClientTelemetryDefault | undefined {\n\tif (value === undefined || value === false) return undefined;\n\tif (value === true) return true;\n\treturn { sampleRate: Number(value) };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { BuildContext } from '../build/types';\nimport type { RouteInfo } from '../types';\nimport type { StorageDrivers } from './drivers';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport {\n\tmountRequestSpansCode,\n\tstartTelemetryCode,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * How a generated entry gets its logger and environment parser.\n *\n * From the surface it serves, when there is one: the surface holds both as\n * *objects*, and discovery already recorded which module declares it, so the\n * entry imports that module and reads them off it.\n *\n * The alternative — the shape this replaces — was naming both in config as\n * module paths, `envParser: './config/env#envParser'`, and printing an import\n * for each. Two strings per app, checked by nothing, describing files the\n * surface was already holding the contents of.\n *\n * Falls back to the configured paths for an app that declares no surface.\n */\nexport function runtimeFor(\n\tcontext: BuildContext,\n\tfromDir: string,\n\t/**\n\t * The construct that owns the thing being generated.\n\t *\n\t * An endpoint's surface, or the worker that handed out the cron factory.\n\t * Omitted for the app entry itself, which belongs to the primary surface.\n\t */\n\towner?: string,\n): { imports: string; bindings: string } {\n\tconst module = owner\n\t\t? (context.owners?.[owner] ?? context.surface?.module)\n\t\t: context.surface?.module;\n\n\tif (module) {\n\t\tconst specifier = importSpecifier(fromDir, module.specifier);\n\n\t\t// Bound to the same names the rest of the entry already uses, so what\n\t\t// changes is where they come from and nothing else.\n\t\treturn {\n\t\t\timports: `import { ${module.exportName} as __surface } from '${specifier}';`,\n\t\t\tbindings: [\n\t\t\t\t'// What this construct was declared with. Objects, not module paths:',\n\t\t\t\t'// the entry imports the owner, so there is nothing to print.',\n\t\t\t\t'const envParser = __surface.envParser;',\n\t\t\t\t'const logger = __surface.logger;',\n\t\t\t].join('\\n'),\n\t\t};\n\t}\n\n\t// No fallback. Every runnable comes from a factory a `RestApi` or a `Worker`\n\t// handed out, and that construct holds the objects — so there is no longer a\n\t// case where the only thing we know about a logger is a module path somebody\n\t// typed into config.\n\tthrow new Error(\n\t\t`No owner to take a logger and an environment parser from${\n\t\t\towner ? ` for \"${owner}\"` : ''\n\t\t}. Build it from a \\`RestApi\\` or a \\`Worker\\`.`,\n\t);\n}\n\n/** A relative specifier ESM will accept: always prefixed, never bare. */\nfunction importSpecifier(fromDir: string, target: string): string {\n\tconst rel = relative(fromDir, target).replace(/\\.ts$/, '.js');\n\n\treturn rel.startsWith('.') ? rel : `./${rel}`;\n}\n\n/**\n * CORS for a surface, derived rather than hand-written.\n *\n * Who may call a surface is already in the graph — every construct that\n * declared an edge to it — and reaches the process as one comma-separated\n * value. An application that maintained this by hand maintained a list that was\n * wrong in two directions at once: it trusted origins nothing was serving, and\n * it could not name hosts a deploy had not chosen yet.\n *\n * Only the parts a graph cannot answer are configurable, and every one has a\n * default: a surface that says nothing about CORS still gets it.\n */\nexport function corsFor(surface: BuildContext['surface']): {\n\timports: string;\n\tsetup: string;\n} {\n\tif (!surface) return { imports: '', setup: '' };\n\n\tconst cors = surface.cors ?? {};\n\t// `traceparent` and `tracestate` always: a site's client sends them when\n\t// its telemetry is on, and a preflight that refused them would fail every\n\t// request it makes rather than only its tracing. The API decides whether\n\t// to continue the trace (it does only for these same origins), so allowing\n\t// the headers grants nothing on its own.\n\tconst allowHeaders = [\n\t\t...new Set([\n\t\t\t'content-type',\n\t\t\t'authorization',\n\t\t\t'traceparent',\n\t\t\t'tracestate',\n\t\t\t...(cors.allowHeaders ?? []),\n\t\t]),\n\t];\n\n\treturn {\n\t\timports: `import { cors } from 'hono/cors';`,\n\t\tsetup: `\n // Who may call ${surface.id}, read off the graph rather than listed here.\n {\n const { origins } = envParser\n .create((get) => ({\n origins: get('${surface.trustedOriginsKey}')\n .string()\n .default('')\n .transform((value: string) =>\n value.split(',').map((origin) => origin.trim()).filter(Boolean),\n ),\n }))\n .parse();\n\n // The same origins are the ones whose trace context the request spans\n // continue — the server reads them back from \\`createApp\\`.\n trustedOrigins.push(...origins);\n\n honoApp.use('*', cors({\n origin: origins,\n allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowHeaders: ${JSON.stringify(allowHeaders)},${\n\t\t\t\tcors.exposeHeaders\n\t\t\t\t\t? `\\n exposeHeaders: ${JSON.stringify(cors.exposeHeaders)},`\n\t\t\t\t\t: ''\n\t\t\t}\n credentials: ${cors.credentials ?? true},\n maxAge: ${cors.maxAge ?? 86400},\n }));\n }\n`,\n\t};\n}\n\nexport class EndpointGenerator extends ConstructGenerator<\n\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>,\n\tRouteInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t> {\n\t\treturn Endpoint.isEndpoint(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<RouteInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst root = options?.root ?? process.cwd();\n\t\tconst enableOpenApi = options?.enableOpenApi || false;\n\t\tconst logger = console;\n\t\tconst routes: RouteInfo[] = [];\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn routes;\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate endpoints.ts and app.ts\n\t\t\tawait this.generateEndpointsFile(outputDir, constructs);\n\t\t\tconst appFile = await this.generateAppFile(outputDir, context);\n\n\t\t\troutes.push({\n\t\t\t\tpath: '*',\n\t\t\t\tmethod: 'ALL',\n\t\t\t\thandler: relative(root, appFile),\n\t\t\t\tauthorizer: 'none',\n\t\t\t});\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n\t\t\t);\n\n\t\t\treturn routes;\n\t\t}\n\n\t\t// One Lambda per endpoint, behind an HTTP API.\n\t\tconst routesDir = join(outputDir, 'routes');\n\t\tawait mkdir(routesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateHandlerFile(\n\t\t\t\troutesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t);\n\n\t\t\tconst routeInfo: RouteInfo = {\n\t\t\t\tpath: construct._path,\n\t\t\t\tmethod: construct.method,\n\t\t\t\thandler: relative(root, handlerFile).replace(/\\.ts$/, '.handler'),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t\tauthorizer: construct.authorizer?.name ?? 'none',\n\t\t\t};\n\n\t\t\troutes.push(routeInfo);\n\t\t\tlogger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);\n\t\t}\n\n\t\treturn routes;\n\t}\n\n\tprivate async generateHandlerFile(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\tawait writeFile(\n\t\t\thandlerPath,\n\t\t\tthis.generateAWSApiGatewayV2Handler(\n\t\t\t\timportPath,\n\t\t\t\texportName,\n\t\t\t\tcontext.storageDrivers,\n\t\t\t),\n\t\t);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateEndpointsFile(\n\t\toutputDir: string,\n\t\tendpoints: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t): Promise<string> {\n\t\tconst endpointsFileName = 'endpoints.ts';\n\t\tconst endpointsPath = join(outputDir, endpointsFileName);\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\n\t\tfor (const { path, key } of endpoints) {\n\t\t\tconst relativePath = relative(dirname(endpointsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\t// Generate import statements for endpoints\n\t\tconst endpointImports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst allExportNames = endpoints.map(({ key }) => key);\n\n\t\t// One registration for every build, production included: each endpoint\n\t\t// is served by HonoEndpoint, which is what `gkm dev` and a feature test\n\t\t// serve it with. Production used to generate its own handlers per\n\t\t// \"tier\", and each was a hand-copy of the adaptor that drifted from it —\n\t\t// a session left undefined, an HttpError answered 500, an auditor\n\t\t// hard-coded to undefined, cookies a handler set never sent.\n\t\tconst content = `import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { Hono } from 'hono';\n${endpointImports}\n\nexport const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Configure OpenAPI options based on enableOpenApi flag\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n\n\t\tawait writeFile(endpointsPath, content);\n\n\t\treturn endpointsPath;\n\t}\n\n\tprivate async generateAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\t// What both entries start telemetry from — the production server and\n\t\t// `gkm dev`'s — decided by the surface's edge to a `Telemetry` node.\n\t\tawait writeTelemetryModule(outputDir, context.telemetry);\n\n\t\t// Use production generator if in production mode\n\t\tif (context.production?.enabled) {\n\t\t\treturn this.generateProductionAppFile(outputDir, context);\n\t\t}\n\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The logger and the env parser, from the surface that already holds them.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\t// Generate telescope imports and setup if enabled\n\t\tconst telescopeEnabled = context.telescope?.enabled;\n\t\tconst telescopeWebSocketEnabled = context.telescope?.websocket;\n\t\tconst usesExternalTelescope = !!context.telescope?.telescopePath;\n\n\t\t// Generate imports based on whether telescope is external or inline\n\t\tconst telescopeFromSurface =\n\t\t\t!!context.surface?.module && !usesExternalTelescope;\n\n\t\tlet telescopeImports = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface) {\n\t\t\t\t// The entry already imports the surface, which may or may not have\n\t\t\t\t// been given a Telescope — an object, so only the running entry can\n\t\t\t\t// tell. The inline one stands in when it was not.\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else if (usesExternalTelescope) {\n\t\t\t\tconst relativeTelescopePath = relative(\n\t\t\t\t\tdirname(appPath),\n\t\t\t\t\tcontext.telescope?.telescopePath!,\n\t\t\t\t);\n\t\t\t\ttelescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else {\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t}\n\t\t}\n\n\t\t// The database's read-only JSON API, from the declared database. The\n\t\t// client comes from the construct, so what it reads is by definition what\n\t\t// the handlers write to.\n\t\tconst databaseApi = context.databaseApi;\n\t\tconst databaseApiImports = databaseApi\n\t\t\t? `import { snifferContext } from '@geekmidas/constructs';\nimport { createIntrospectionHandler } from '@geekmidas/db/introspect';\nimport { ${databaseApi.database.exportName} as __introspectedDb } from '${importSpecifier(dirname(appPath), databaseApi.database.specifier)}';`\n\t\t\t: '';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\tconst telescopeWebSocketSetupCode = telescopeWebSocketEnabled\n\t\t\t? `\n // Setup WebSocket for real-time telescope updates\n try {\n const { createNodeWebSocket } = await import('@hono/node-ws');\n const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });\n // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)\n honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({\n onOpen: (_event: Event, ws: any) => {\n telescope.addWsClient(ws);\n },\n onClose: (_event: Event, ws: any) => {\n telescope.removeWsClient(ws);\n },\n onMessage: (event: MessageEvent, ws: any) => {\n try {\n const data = JSON.parse(event.data);\n if (data.type === 'ping') {\n ws.send(JSON.stringify({ type: 'pong' }));\n }\n } catch {\n // Ignore invalid messages\n }\n },\n })));\n // Store injectWebSocket for server entry to call after serve()\n (honoApp as any).__injectWebSocket = injectWebSocket;\n logger.info('Telescope WebSocket enabled');\n } catch (e) {\n logger.warn({ err: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');\n }\n`\n\t\t\t: '';\n\n\t\t// Generate telescope setup - either use external instance or create inline\n\t\tlet telescopeSetup = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface || usesExternalTelescope) {\n\t\t\t\t// Use external telescope instance - no need to create one\n\t\t\t\ttelescopeSetup = `\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t} else {\n\t\t\t\t// Create inline telescope instance\n\t\t\t\ttelescopeSetup = `\n // Setup Telescope for debugging/monitoring\n const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });\n const telescope = new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: telescopeStorage,\n });\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t}\n\t\t}\n\n\t\tconst databaseApiSetup = databaseApi\n\t\t\t? `\n // The database's structure and rows as JSON, read-only, for whatever tool\n // the developer points at it. Dev only: it answers anyone who can reach the\n // port.\n const databaseApi = createIntrospectionHandler({\n db: await __introspectedDb.service.register({ envParser, context: snifferContext }),\n basePath: '${databaseApi.path}',\n });\n honoApp.all('${databaseApi.path}/*', (c) => databaseApi(c.req.raw));\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated server application\n *\n * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY\n * The subscriber polling mechanism is not production-ready.\n * For production, use AWS Lambda with SQS/SNS event sources.\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\nimport { setupEndpoints } from './endpoints.js';\nimport { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';\n${runtime.imports}\n${telescopeImports}\n${databaseApiImports}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n${\n\ttelescopeEnabled && telescopeFromSurface\n\t\t? `// The surface's own Telescope, or the one \\`telescope\\` config describes.\nconst telescope =\n __surface.telescope ??\n new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} }),\n });`\n\t\t: ''\n}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// Which drivers exist — storage, cache, events — is the entry point's\n// decision: the scheme in each injected URL picks one, so no construct and no\n// application module names a provider.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n /** Returns the server, so a shutdown can stop it taking requests. */\n serve: (app: HonoType, port: number) => unknown;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the Hono application\n *\n * @param app - Optional Hono app instance to configure (creates new one if not provided)\n * @param enableOpenApi - Enable OpenAPI documentation (default: true)\n * @returns Server app with configured Hono app and start function\n *\n * @example\n * // With Bun\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * Bun.serve({ port, fetch: app.fetch });\n * }\n * });\n *\n * @example\n * // With Node.js (using @hono/node-server)\n * import { serve } from '@hono/node-server';\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}\n // Setup HTTP endpoints\n await setupEndpoints(honoApp, envParser, logger, enableOpenApi);\n${afterSetupCall}\n\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? 3000;\n\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background (non-blocking, local development only)\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n logger.info({ port }, 'Starting server');\n\n // Start HTTP server using provided serve function\n await options.serve(honoApp, port);\n\n logger.info({ port }, 'Server started');\n\n await subscribeForPush(port);\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * One Lambda, one endpoint — and no environment import.\n\t *\n\t * The endpoint was built from its surface, so it carries the parser the\n\t * adaptor needs. This used to read\n\t * `import { envParser } from '../../config/env'`, a line the build wrote\n\t * because a generator can print a module specifier and cannot print an\n\t * object. Nothing has to be printed now, which is also why nothing has to be\n\t * named in config.\n\t */\n\tprivate generateAWSApiGatewayV2Handler(\n\t\timportPath: string,\n\t\texportName: string,\n\t\tdrivers?: StorageDrivers,\n\t): string {\n\t\treturn `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${drivers?.imports ?? ''}\n${drivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${drivers.setup}\\n` : ''}\nconst adapter = new AmazonApiGatewayV2Endpoint(${exportName});\n\nexport const handler = adapter.handler;\n`;\n\t}\n\n\t/**\n\t * Generate a production-optimized app.ts file\n\t * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown\n\t */\n\tprivate async generateProductionAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The app entry belongs to the primary surface, so no owner is named.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\tconst production = context.production!;\n\t\tconst healthCheckPath = production.healthCheck;\n\t\tconst enableGracefulShutdown = production.gracefulShutdown;\n\t\tconst enableOpenApi = production.openapi;\n\t\tconst includeSubscribers = production.subscribers === 'include';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\t// Subscriber + queue setup code (background workers share the same flag)\n\t\tconst subscriberSetup = includeSubscribers\n\t\t\t? `\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n`\n\t\t\t: '';\n\n\t\tconst subscriberImport = includeSubscribers\n\t\t\t? `import { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';`\n\t\t\t: '';\n\n\t\t// Graceful shutdown code\n\t\tconst gracefulShutdownCode = enableGracefulShutdown\n\t\t\t? `\n // Graceful shutdown: stop taking requests, let in-flight ones finish, then\n // close what constructs opened (database pools) — so a rolling deploy does\n // not leave the old task holding connections. Bounded by\n // GKM_SHUTDOWN_TIMEOUT_MS, 8s by default: under Docker's 10s stop timeout,\n // so the process exits on its own terms rather than being killed mid-drain.\n let isShuttingDown = false;\n\n const shutdown = async () => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n await new Promise<void>((resolve) => {\n const close = (server as { close?: (done: () => void) => void } | undefined)?.close;\n if (typeof close === 'function') close.call(server, () => resolve());\n else resolve();\n });\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n process.exit(0);\n };\n\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated production server application\n *\n * This is a production-optimized build without dev tools.\n * - No Telescope debugging dashboard\n * - No Studio database browser\n * - No WebSocket updates\n * - Includes health checks and graceful shutdown\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\n${enableGracefulShutdown ? \"import { runShutdownHooks } from '@geekmidas/constructs';\\n\" : ''}import { setupEndpoints } from './endpoints.js';\n${subscriberImport}\n${runtime.imports}\n${runtime.bindings}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n serve: (app: HonoType, port: number) => void | Promise<void>;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the production Hono application\n */\nexport async function createApp(app?: HonoType): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n\n // Health check endpoint (always first)\n honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));\n honoApp.get('/ready', (c) => c.json({ ready: true }));\n\n // An HttpError a handler or a session callback throws — a 401, a 404 —\n // answers with its own status, as it does under gkm dev. The optimized\n // handlers do not catch, so without this every one of them was a 500.\n // Anything else is a 500 that says nothing about why, and is logged.\n honoApp.onError((error, c) => {\n const http = error as {\n isHttpError?: boolean;\n statusCode?: number;\n statusMessage?: string;\n code?: string;\n details?: unknown;\n };\n if (http.isHttpError === true && typeof http.statusCode === 'number') {\n return c.json(\n {\n name: error.name,\n message: error.message,\n statusCode: http.statusCode,\n statusMessage: http.statusMessage,\n code: http.code,\n details: http.details,\n },\n http.statusCode as 500,\n );\n }\n logger.error({ err: error }, 'Unhandled error');\n return c.json({ message: 'Internal Server Error' }, 500);\n });\n${cors.setup}${beforeSetupCall}\n // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})\n await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});\n${afterSetupCall}\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? Number(process.env.PORT) ?? 3000;\n let server: unknown;\n${gracefulShutdownCode}${subscriberSetup}\n logger.info({ port }, 'Starting production server');\n\n // Start HTTP server using provided serve function\n server = await options.serve(honoApp, port);\n\n logger.info({ port }, 'Production server started');\n${includeSubscribers ? '\\n await subscribeForPush(port);' : ''}\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\t// Also generate the production server entry point\n\t\tawait this.generateProductionServerEntry(outputDir, context);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * Generate production server.ts entry point\n\t */\n\tprivate async generateProductionServerEntry(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<void> {\n\t\tconst serverPath = join(outputDir, 'server.ts');\n\n\t\t// `telemetry.ts` beside it was written with `app.ts`, for this entry\n\t\t// and the `gkm dev` one alike, which start it the same way.\n\t\tconst content = `#!/usr/bin/env node\n/**\n * Production server entry point\n * Generated by 'gkm build --production'\n */\nimport { serve } from '@hono/node-server';\nimport { Hono } from 'hono';\n\n${startTelemetryCode([context.production?.healthCheck ?? '/health', '/ready'])}\nconst { createApp } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nconst app = new Hono();\n${mountRequestSpansCode('app')}\nconst created = await createApp(app);\ntrustedOrigins = created.trustedOrigins;\nconst { start } = created;\n\nawait start({\n port,\n serve: (app, port) => serve({ fetch: app.fetch, port }),\n});\n`;\n\n\t\tawait writeFile(serverPath, content);\n\t}\n}\n"],"mappings":";;;;;;;;AAkBA,SAAgB,eACf,WAKmB;CACnB,OAAO,UAAU,SAAS,aACzB,SAAS,YACN,CACA;EACC,QAAQ,SAAS;EACjB,MAAM,SAAS;EACf,GAAG,SAAS;CACb,CACD,IACC,CAAC,CACL;AACD;;;;;;;AA8BA,MAAa,qBAAqB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;AAWA,SAAS,WAAW,SAAiB,MAAkC;CACtE,KAAK,IAAI,MAAM,QAAQ,OAAO,IAAK,MAAM,QAAQ,GAAG,GAAG;EACtD,MAAM,YAAY,KAAK,KAAK,gBAAgB,IAAI;EAChD,IAAI,WAAW,KAAK,WAAW,cAAc,CAAC,GAC7C,OAAO,aAAa,SAAS;EAE9B,IAAI,QAAQ,GAAG,MAAM,KAAK,OAAO,KAAA;CAClC;AACD;;;;;;;AAQA,SAAgB,yBAAyB,SAA2B;CACnE,MAAM,YAAY,WAAW,SAAS,sBAAsB;CAC5D,IAAI,CAAC,WAAW,OAAO,CAAC,wBAAwB,GAAG,kBAAkB;CAErE,OAAO,mBAAmB,QAAQ,QAAQ,CAAC,WAAW,WAAW,GAAG,CAAC;AACtE;;;;;;;AAQA,IAAa,2BAAb,cAA8C,SAAS;CAI5C;CACA;CAEA;CANV;CAEA,YACC,KACA,SAEA,KACC;EACD,MAAM,UAAU,cAAc,OAAO,IAAI,OAAO,QAAQ,KAAK,GAAG;EAChE,MACC,IAAI,IAAI,oCAAoC,QA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E3D,OAAO;CACR;;;;CAKA,MAAc,8BACb,WACA,SACgB;EAChB,MAAM,aAAa,KAAK,WAAW,WAAW;EAI9C,MAAM,UAAU;;;;;;;;EAQhB,mBAAmB,CAAC,QAAQ,YAAY,eAAe,WAAW,QAAQ,CAAC,EAAE;;;;;;EAM7E,sBAAsB,KAAK,EAAE;;;;;;;;;;EAW7B,MAAM,UAAU,YAAY,OAAO;CACpC;AACD"}
@@ -1,4 +1,5 @@
1
- const require_discover = require("./discover-D1It5r_h.cjs");
1
+ const require_errors = require("./errors-DMC4Umsb.cjs");
2
+ const require_discover = require("./discover-DPgu-ScS.cjs");
2
3
  let node_path = require("node:path");
3
4
  let node_fs = require("node:fs");
4
5
  let node_fs_promises = require("node:fs/promises");
@@ -64,7 +65,7 @@ function missingTelemetryPackages(appRoot) {
64
65
  * Failed at build, not at startup: a process that was given telemetry and
65
66
  * quietly ran without it is an outage nobody can see into.
66
67
  */
67
- var TelemetryPackagesMissing = class extends Error {
68
+ var TelemetryPackagesMissing = class extends require_errors.GkmError {
68
69
  app;
69
70
  missing;
70
71
  dir;
@@ -287,8 +288,17 @@ async function writeTelemetryModule(outputDir, telemetry) {
287
288
  }
288
289
  //#endregion
289
290
  //#region src/generators/clientTelemetry.ts
291
+ /**
292
+ * Whether a generated client propagates trace context by default.
293
+ *
294
+ * `false` (the default) prints a client that sends no trace headers unless
295
+ * its caller passes `telemetry`. Anything else prints that default into
296
+ * `createApi`: `true`, or `{ sampleRate }` — the stage's rate, for the page
297
+ * views no OpenTelemetry SDK is tracing. A caller's own `telemetry` option
298
+ * still wins.
299
+ */
290
300
  /** A `sampleRate` outside 0–1, which no sampler can honour. */
291
- var InvalidClientTelemetrySampleRate = class extends Error {
301
+ var InvalidClientTelemetrySampleRate = class extends require_errors.GkmError {
292
302
  sampleRate;
293
303
  constructor(sampleRate) {
294
304
  super(`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`);
@@ -1077,4 +1087,4 @@ Object.defineProperty(exports, "writeTelemetryModule", {
1077
1087
  }
1078
1088
  });
1079
1089
 
1080
- //# sourceMappingURL=EndpointGenerator-CwLjBCFE.cjs.map
1090
+ //# sourceMappingURL=EndpointGenerator-De03t1hd.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EndpointGenerator-De03t1hd.cjs","names":["resolve","dirname","join","existsSync","realpathSync","GkmError","relative","mkdir","writeFile","GkmError","relative","ConstructGenerator","Endpoint","join","mkdir","dirname","writeFile"],"sources":["../src/generators/telemetry.ts","../src/generators/clientTelemetry.ts","../src/generators/EndpointGenerator.ts"],"sourcesContent":["import { existsSync, realpathSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport type { TelemetryDeclaration } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\n\n/**\n * One route's own telemetry — an endpoint's `.telemetry({ ignore, attributes })`.\n */\nexport interface TelemetryRoute {\n\tmethod: string;\n\t/** The route as the surface serves it — `/users/:id`. */\n\tpath: string;\n\tignore?: boolean;\n\tattributes?: Readonly<Record<string, string>>;\n}\n\n/** Each endpoint's own `.telemetry({ ignore, attributes })`, as routes. */\nexport function routeTelemetry(\n\tendpoints: readonly {\n\t\tmethod: string;\n\t\troute: string;\n\t\ttelemetry?: Omit<TelemetryRoute, 'method' | 'path'>;\n\t}[],\n): TelemetryRoute[] {\n\treturn endpoints.flatMap((endpoint) =>\n\t\tendpoint.telemetry\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t\t\tpath: endpoint.route,\n\t\t\t\t\t\t...endpoint.telemetry,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: [],\n\t);\n}\n\n/**\n * What an entry starts OpenTelemetry with, decided at build time from the\n * process's edge to a `Telemetry` node.\n *\n * Only built for a process with that edge — every other process gets the\n * stub, which loads nothing — and only once the packages it needs resolve:\n * a process that uses the node and cannot load them fails the build with\n * {@link TelemetryPackagesMissing}.\n */\nexport interface TelemetryContext {\n\t/** `service.name` — the surface or worker; `OTEL_SERVICE_NAME` overrides it. */\n\tserviceName: string;\n\t/** `service.namespace` — the workspace the app is part of. */\n\tserviceNamespace?: string;\n\t/** The node's `ignorePaths`. */\n\tignorePaths: readonly string[];\n\t/** The node's `attributes`, on every span and log record. */\n\tattributes: Readonly<Record<string, string>>;\n\t/** Each route that says something of its own. */\n\troutes: readonly TelemetryRoute[];\n}\n\n/**\n * Every package `@geekmidas/telescope/instrumentation` loads at runtime.\n *\n * All of them, rather than one as a proxy: the production bundle follows each\n * import, and a single missing one fails the build rather than the telemetry.\n */\nexport const TELEMETRY_PACKAGES = [\n\t'@opentelemetry/api',\n\t'@opentelemetry/auto-instrumentations-node',\n\t'@opentelemetry/exporter-logs-otlp-http',\n\t'@opentelemetry/exporter-trace-otlp-http',\n\t'@opentelemetry/instrumentation-pino',\n\t'@opentelemetry/resources',\n\t'@opentelemetry/sdk-logs',\n\t'@opentelemetry/sdk-node',\n\t'@opentelemetry/sdk-trace-base',\n\t'@opentelemetry/sdk-trace-node',\n\t'@opentelemetry/semantic-conventions',\n] as const;\n\n/**\n * The directory of `name` as `node_modules` lookup finds it from `fromDir`,\n * symlinks resolved — or undefined.\n *\n * The directory walk alone, not `require.resolve`: that also searches\n * `NODE_PATH`, which a package manager's bin shim sets to its own store, so a\n * `gkm build` run through one would find packages the app never installed —\n * and the bundler, which does not look there, would then fail on them.\n */\nfunction packageDir(fromDir: string, name: string): string | undefined {\n\tfor (let dir = resolve(fromDir); ; dir = dirname(dir)) {\n\t\tconst candidate = join(dir, 'node_modules', name);\n\t\tif (existsSync(join(candidate, 'package.json'))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tif (dirname(dir) === dir) return undefined;\n\t}\n}\n\n/**\n * The telemetry packages that do not resolve the way the bundler will resolve\n * them — telescope from the app, and the OpenTelemetry packages from\n * telescope, where a peer is linked under pnpm, which need not be where the\n * app sees it. Empty when every one does.\n */\nexport function missingTelemetryPackages(appRoot: string): string[] {\n\tconst telescope = packageDir(appRoot, '@geekmidas/telescope');\n\tif (!telescope) return ['@geekmidas/telescope', ...TELEMETRY_PACKAGES];\n\n\treturn TELEMETRY_PACKAGES.filter((pkg) => !packageDir(telescope, pkg));\n}\n\n/**\n * An app uses a `Telemetry` construct and cannot load what it needs to.\n *\n * Failed at build, not at startup: a process that was given telemetry and\n * quietly ran without it is an outage nobody can see into.\n */\nexport class TelemetryPackagesMissing extends GkmError {\n\treadonly command: string;\n\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly missing: readonly string[],\n\t\t/** The app's directory, relative to where the command is run. */\n\t\treadonly dir: string,\n\t) {\n\t\tconst command = `pnpm --dir ${dir || '.'} add ${missing.join(' ')}`;\n\t\tsuper(\n\t\t\t`'${app}' uses a Telemetry construct, and ${missing.join(', ')} ` +\n\t\t\t\t`${missing.length === 1 ? 'does' : 'do'} not resolve from it — its ` +\n\t\t\t\t'server would start without exporting a span. Add them to the app ' +\n\t\t\t\t`and build again:\\n\\n ${command}\\n`,\n\t\t);\n\t\tthis.name = 'TelemetryPackagesMissing';\n\t\tthis.command = command;\n\t}\n}\n\n/**\n * The telemetry half of a build context: undefined for a process with no\n * edge to a `Telemetry` node, and — for one with an edge — what its entry\n * starts with, once every package it needs resolves.\n */\nexport function telemetryFor(options: {\n\t/** The node the process emits through — see `telemetryOf`. */\n\tnode: TelemetryDeclaration | undefined;\n\tappRoot: string;\n\t/** The app's name, for the error. */\n\tapp: string;\n\t/** Where `pnpm` is run from, for the error's command. */\n\tcwd?: string;\n\tserviceName: string;\n\tworkspaceName?: string;\n\troutes?: readonly TelemetryRoute[];\n}): TelemetryContext | undefined {\n\tconst { node } = options;\n\tif (!node) return undefined;\n\n\tconst missing = missingTelemetryPackages(options.appRoot);\n\tif (missing.length > 0) {\n\t\tthrow new TelemetryPackagesMissing(\n\t\t\toptions.app,\n\t\t\tmissing,\n\t\t\trelative(options.cwd ?? process.cwd(), options.appRoot),\n\t\t);\n\t}\n\n\treturn {\n\t\tserviceName: options.serviceName,\n\t\t...(options.workspaceName && { serviceNamespace: options.workspaceName }),\n\t\tignorePaths: [...(node.ignorePaths ?? [])],\n\t\tattributes: { ...node.attributes },\n\t\troutes: [...(options.routes ?? [])],\n\t};\n}\n\nconst HEADER = `/**\n * Generated by gkm, for the production entry and the \\`gkm dev\\` one alike.\n *\n * Starts OpenTelemetry when OTEL_EXPORTER_OTLP_ENDPOINT names a collector, and\n * does nothing otherwise: without it, the telemetry packages are not loaded.\n * The standard OTEL_* variables (OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG,\n * OTEL_EXPORTER_OTLP_HEADERS, OTEL_RESOURCE_ATTRIBUTES, OTEL_SERVICE_NAME)\n * configure the rest.\n */\n\nimport type { MiddlewareHandler } from 'hono';\n\nexport interface StartTelemetryOptions {\n /** Requests whose spans would only be noise: health checks, by default. */\n ignorePaths?: string[];\n /**\n * The API's own sites — the origins its CORS allows — read on each request.\n * Their \\`traceparent\\` is continued, as is an internal caller's; anyone\n * else's starts a new trace linked to the one it claimed.\n */\n trustedOrigins?: () => readonly string[];\n}\n`;\n\n/** `/users/:id` as a pattern over a request's path. */\nfunction routePattern(path: string): string {\n\tconst body = path\n\t\t.split('/')\n\t\t.map((segment) => {\n\t\t\tif (segment.startsWith(':')) return '[^/]+';\n\t\t\tif (segment === '*') return '.*';\n\t\t\treturn segment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\t\t})\n\t\t.join('/');\n\treturn `^${body}/?$`;\n}\n\n/**\n * The entry's `telemetry.ts`: a `startTelemetry()` the server awaits before it\n * imports the app, so the libraries the app loads are instrumented. It returns\n * the Hono middleware that traces each request, or undefined when telemetry is\n * off — the server mounts it ahead of every route.\n *\n * Without a context — a process with no edge to a `Telemetry` node — it is a\n * stub that loads nothing and says nothing: telemetry is not something that\n * process was given.\n *\n * Failing to start telemetry warns (a named `TelemetryUnavailable`, through\n * `process.emitWarning`) and never stops the server: an outage in observability\n * is not a reason to have an outage in the service.\n */\nexport function generateTelemetryModule(\n\ttelemetry: TelemetryContext | undefined,\n): string {\n\tif (!telemetry) {\n\t\treturn `${HEADER}\n// This process has no Telemetry construct, so there is nothing to start.\nexport async function startTelemetry(\n _options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n return undefined;\n}\n`;\n\t}\n\n\tconst options = [\n\t\t`serviceName: ${JSON.stringify(telemetry.serviceName)},`,\n\t\t...(telemetry.serviceNamespace\n\t\t\t? [`serviceNamespace: ${JSON.stringify(telemetry.serviceNamespace)},`]\n\t\t\t: []),\n\t\t// The stage the deploy set, so one service's stages stay apart.\n\t\t'deploymentEnvironment: process.env.STAGE,',\n\t\t...(Object.keys(telemetry.attributes).length\n\t\t\t? [`resourceAttributes: ${JSON.stringify(telemetry.attributes)},`]\n\t\t\t: []),\n\t\t// The exporters read OTEL_EXPORTER_OTLP_* themselves, and the SDK reads\n\t\t// OTEL_TRACES_SAMPLER — so no endpoint and no ratio are printed here.\n\t\t// The server's own shutdown decides when the process exits.\n\t\t'handleSignals: false,',\n\t\t// Neither is left to module-load hooks, which see nothing inside a\n\t\t// bundle: @geekmidas/logger emits each record through the logs API\n\t\t// itself, and the middleware returned below opens each request's span.\n\t\t// Hooked as well where they can be, every record and request would be\n\t\t// sent twice.\n\t\t'instrumentPino: false,',\n\t\t'incomingHttpSpans: false,',\n\t];\n\n\tconst routes = telemetry.routes.map((route) => ({\n\t\tmethod: route.method.toUpperCase(),\n\t\tpattern: routePattern(route.path),\n\t\t...(route.ignore ? { ignore: true } : {}),\n\t\t...(route.attributes && Object.keys(route.attributes).length\n\t\t\t? { attributes: route.attributes }\n\t\t\t: {}),\n\t}));\n\tconst withAttributes = routes.some((route) => 'attributes' in route);\n\n\treturn `${HEADER}\n/** Telemetry was asked for and cannot start. The server runs without it. */\nexport class TelemetryUnavailable extends Error {\n constructor(readonly reason: string, options?: { cause?: unknown }) {\n super(\n \\`OTEL_EXPORTER_OTLP_ENDPOINT is set, but \\${reason} This server exports no traces or logs until that is fixed.\\`,\n options,\n );\n this.name = 'TelemetryUnavailable';\n }\n}\n\n/** The Telemetry construct's own ignored paths, beside the entry's. */\nconst IGNORE_PATHS: string[] = ${JSON.stringify(telemetry.ignorePaths)};\n\n/** Each route's own .telemetry({ ignore, attributes }). */\nconst ROUTES: {\n method: string;\n pattern: string;\n ignore?: boolean;\n attributes?: Record<string, string>;\n}[] = ${JSON.stringify(routes)};\n\nconst MATCHERS = ROUTES.map((route) => ({ ...route, regex: new RegExp(route.pattern) }));\n\nfunction routeOf(method: string, path: string) {\n return MATCHERS.find(\n (route) => (route.method === method || route.method === 'ALL' || route.method === 'ANY') && route.regex.test(path),\n );\n}\n\nexport async function startTelemetry(\n options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT) return undefined;\n\n let instrumentation;\n try {\n instrumentation = await import('@geekmidas/telescope/instrumentation');\n } catch (cause) {\n process.emitWarning(\n new TelemetryUnavailable(\n '@geekmidas/telescope/instrumentation or an @opentelemetry package it needs could not be loaded. Install them in the app and rebuild.',\n { cause },\n ),\n );\n return undefined;\n }\n\n instrumentation.setupTelemetry({\n ${options.join('\\n ')}\n });\n\n // Flush what is buffered when the process is told to stop. When nothing\n // else handles the signal, re-raise it once flushed, so the process still\n // stops the way it would have without this listener.\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.once(signal, () => {\n void instrumentation.flushTelemetry().finally(() => {\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n });\n });\n }\n\n // A SERVER span per request, opened by the app itself rather than by\n // hooking node:http: \\`GET /users/:id\\`, continuing an incoming traceparent\n // from the API's own sites and internal callers (a new, linked trace from\n // anyone else), with the handler — its logs, fetches and queries — running\n // inside it.\n const spans = instrumentation.honoTelemetryMiddleware({\n ignorePaths: [...(options.ignorePaths ?? []), ...IGNORE_PATHS],\n trustedOrigins: options.trustedOrigins,\n ...(MATCHERS.some((route) => route.ignore)\n ? { shouldSkip: (c) => routeOf(c.req.method, c.req.path)?.ignore === true }\n : {}),\n });\n${\n\twithAttributes\n\t\t? `\n // A route's own attributes, on the span the middleware just opened.\n const { trace } = await import('@opentelemetry/api');\n return (c, next) =>\n spans(c, async () => {\n const attributes = routeOf(c.req.method, c.req.path)?.attributes;\n if (attributes) trace.getActiveSpan()?.setAttributes(attributes);\n await next();\n });\n`\n\t\t: ` return spans;\n`\n}}\n`;\n}\n\n/**\n * What an entry starts telemetry with, before it imports the app — shared by\n * the production server, a self-serving surface's server and the `gkm dev`\n * entry, so the three cannot start it differently. Defines `requestSpans`.\n */\nexport function startTelemetryCode(ignorePaths: readonly string[]): string {\n\treturn `// The API's own sites, known once the app has read its configuration: the\n// origins its CORS allows are the ones whose trace context is continued.\nlet trustedOrigins: readonly string[] = [];\n\n// Before the app is imported, so the libraries it loads are instrumented.\nconst { startTelemetry } = await import('./telemetry.js');\nconst requestSpans = await startTelemetry({\n ignorePaths: ${JSON.stringify(ignorePaths)},\n trustedOrigins: () => trustedOrigins,\n});\n`;\n}\n\n/** Mounts `requestSpans` on `app` ahead of every route. */\nexport function mountRequestSpansCode(app: string): string {\n\treturn `// The span middleware goes on before any route, so every request runs in it.\nif (requestSpans) ${app}.use('*', requestSpans);\n`;\n}\n\n/** Writes the entry's `telemetry.ts` beside it. */\nexport async function writeTelemetryModule(\n\toutputDir: string,\n\ttelemetry: TelemetryContext | undefined,\n): Promise<void> {\n\tawait mkdir(outputDir, { recursive: true });\n\tawait writeFile(\n\t\tjoin(outputDir, 'telemetry.ts'),\n\t\tgenerateTelemetryModule(telemetry),\n\t);\n}\n","/**\n * Whether a generated client propagates trace context by default.\n *\n * `false` (the default) prints a client that sends no trace headers unless\n * its caller passes `telemetry`. Anything else prints that default into\n * `createApi`: `true`, or `{ sampleRate }` — the stage's rate, for the page\n * views no OpenTelemetry SDK is tracing. A caller's own `telemetry` option\n * still wins.\n */\n\nimport { GkmError } from '../errors';\nexport type ClientTelemetryDefault = boolean | { sampleRate: number };\n\n/** A `sampleRate` outside 0–1, which no sampler can honour. */\nexport class InvalidClientTelemetrySampleRate extends GkmError {\n\tconstructor(readonly sampleRate: number) {\n\t\tsuper(\n\t\t\t`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`,\n\t\t);\n\t\tthis.name = 'InvalidClientTelemetrySampleRate';\n\t}\n}\n\n/** The `telemetry` default as the generated module prints it. */\nexport function printTelemetryDefault(\n\ttelemetry: ClientTelemetryDefault,\n): string {\n\tif (typeof telemetry === 'boolean') return String(telemetry);\n\tconst { sampleRate } = telemetry;\n\tif (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) {\n\t\tthrow new InvalidClientTelemetrySampleRate(sampleRate);\n\t}\n\treturn `{ sampleRate: ${sampleRate} }`;\n}\n\n/**\n * `--telemetry [rate]` for a client default, as `gkm openapi` takes it — and\n * as a site's Dockerfile passes it to the `gkm openapi --app` it runs.\n */\nexport function telemetryArgs(telemetry?: ClientTelemetryDefault): string[] {\n\tif (!telemetry) return [];\n\tif (telemetry === true) return ['--telemetry'];\n\treturn ['--telemetry', String(telemetry.sampleRate)];\n}\n\n/** What `--telemetry [rate]` parsed to: on, at a rate when one was given. */\nexport function parseTelemetryFlag(\n\tvalue: boolean | string | undefined,\n): ClientTelemetryDefault | undefined {\n\tif (value === undefined || value === false) return undefined;\n\tif (value === true) return true;\n\treturn { sampleRate: Number(value) };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { BuildContext } from '../build/types';\nimport type { RouteInfo } from '../types';\nimport type { StorageDrivers } from './drivers';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport {\n\tmountRequestSpansCode,\n\tstartTelemetryCode,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * How a generated entry gets its logger and environment parser.\n *\n * From the surface it serves, when there is one: the surface holds both as\n * *objects*, and discovery already recorded which module declares it, so the\n * entry imports that module and reads them off it.\n *\n * The alternative — the shape this replaces — was naming both in config as\n * module paths, `envParser: './config/env#envParser'`, and printing an import\n * for each. Two strings per app, checked by nothing, describing files the\n * surface was already holding the contents of.\n *\n * Falls back to the configured paths for an app that declares no surface.\n */\nexport function runtimeFor(\n\tcontext: BuildContext,\n\tfromDir: string,\n\t/**\n\t * The construct that owns the thing being generated.\n\t *\n\t * An endpoint's surface, or the worker that handed out the cron factory.\n\t * Omitted for the app entry itself, which belongs to the primary surface.\n\t */\n\towner?: string,\n): { imports: string; bindings: string } {\n\tconst module = owner\n\t\t? (context.owners?.[owner] ?? context.surface?.module)\n\t\t: context.surface?.module;\n\n\tif (module) {\n\t\tconst specifier = importSpecifier(fromDir, module.specifier);\n\n\t\t// Bound to the same names the rest of the entry already uses, so what\n\t\t// changes is where they come from and nothing else.\n\t\treturn {\n\t\t\timports: `import { ${module.exportName} as __surface } from '${specifier}';`,\n\t\t\tbindings: [\n\t\t\t\t'// What this construct was declared with. Objects, not module paths:',\n\t\t\t\t'// the entry imports the owner, so there is nothing to print.',\n\t\t\t\t'const envParser = __surface.envParser;',\n\t\t\t\t'const logger = __surface.logger;',\n\t\t\t].join('\\n'),\n\t\t};\n\t}\n\n\t// No fallback. Every runnable comes from a factory a `RestApi` or a `Worker`\n\t// handed out, and that construct holds the objects — so there is no longer a\n\t// case where the only thing we know about a logger is a module path somebody\n\t// typed into config.\n\tthrow new Error(\n\t\t`No owner to take a logger and an environment parser from${\n\t\t\towner ? ` for \"${owner}\"` : ''\n\t\t}. Build it from a \\`RestApi\\` or a \\`Worker\\`.`,\n\t);\n}\n\n/** A relative specifier ESM will accept: always prefixed, never bare. */\nfunction importSpecifier(fromDir: string, target: string): string {\n\tconst rel = relative(fromDir, target).replace(/\\.ts$/, '.js');\n\n\treturn rel.startsWith('.') ? rel : `./${rel}`;\n}\n\n/**\n * CORS for a surface, derived rather than hand-written.\n *\n * Who may call a surface is already in the graph — every construct that\n * declared an edge to it — and reaches the process as one comma-separated\n * value. An application that maintained this by hand maintained a list that was\n * wrong in two directions at once: it trusted origins nothing was serving, and\n * it could not name hosts a deploy had not chosen yet.\n *\n * Only the parts a graph cannot answer are configurable, and every one has a\n * default: a surface that says nothing about CORS still gets it.\n */\nexport function corsFor(surface: BuildContext['surface']): {\n\timports: string;\n\tsetup: string;\n} {\n\tif (!surface) return { imports: '', setup: '' };\n\n\tconst cors = surface.cors ?? {};\n\t// `traceparent` and `tracestate` always: a site's client sends them when\n\t// its telemetry is on, and a preflight that refused them would fail every\n\t// request it makes rather than only its tracing. The API decides whether\n\t// to continue the trace (it does only for these same origins), so allowing\n\t// the headers grants nothing on its own.\n\tconst allowHeaders = [\n\t\t...new Set([\n\t\t\t'content-type',\n\t\t\t'authorization',\n\t\t\t'traceparent',\n\t\t\t'tracestate',\n\t\t\t...(cors.allowHeaders ?? []),\n\t\t]),\n\t];\n\n\treturn {\n\t\timports: `import { cors } from 'hono/cors';`,\n\t\tsetup: `\n // Who may call ${surface.id}, read off the graph rather than listed here.\n {\n const { origins } = envParser\n .create((get) => ({\n origins: get('${surface.trustedOriginsKey}')\n .string()\n .default('')\n .transform((value: string) =>\n value.split(',').map((origin) => origin.trim()).filter(Boolean),\n ),\n }))\n .parse();\n\n // The same origins are the ones whose trace context the request spans\n // continue — the server reads them back from \\`createApp\\`.\n trustedOrigins.push(...origins);\n\n honoApp.use('*', cors({\n origin: origins,\n allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowHeaders: ${JSON.stringify(allowHeaders)},${\n\t\t\t\tcors.exposeHeaders\n\t\t\t\t\t? `\\n exposeHeaders: ${JSON.stringify(cors.exposeHeaders)},`\n\t\t\t\t\t: ''\n\t\t\t}\n credentials: ${cors.credentials ?? true},\n maxAge: ${cors.maxAge ?? 86400},\n }));\n }\n`,\n\t};\n}\n\nexport class EndpointGenerator extends ConstructGenerator<\n\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>,\n\tRouteInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t> {\n\t\treturn Endpoint.isEndpoint(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<RouteInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst root = options?.root ?? process.cwd();\n\t\tconst enableOpenApi = options?.enableOpenApi || false;\n\t\tconst logger = console;\n\t\tconst routes: RouteInfo[] = [];\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn routes;\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate endpoints.ts and app.ts\n\t\t\tawait this.generateEndpointsFile(outputDir, constructs);\n\t\t\tconst appFile = await this.generateAppFile(outputDir, context);\n\n\t\t\troutes.push({\n\t\t\t\tpath: '*',\n\t\t\t\tmethod: 'ALL',\n\t\t\t\thandler: relative(root, appFile),\n\t\t\t\tauthorizer: 'none',\n\t\t\t});\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n\t\t\t);\n\n\t\t\treturn routes;\n\t\t}\n\n\t\t// One Lambda per endpoint, behind an HTTP API.\n\t\tconst routesDir = join(outputDir, 'routes');\n\t\tawait mkdir(routesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateHandlerFile(\n\t\t\t\troutesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t);\n\n\t\t\tconst routeInfo: RouteInfo = {\n\t\t\t\tpath: construct._path,\n\t\t\t\tmethod: construct.method,\n\t\t\t\thandler: relative(root, handlerFile).replace(/\\.ts$/, '.handler'),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t\tauthorizer: construct.authorizer?.name ?? 'none',\n\t\t\t};\n\n\t\t\troutes.push(routeInfo);\n\t\t\tlogger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);\n\t\t}\n\n\t\treturn routes;\n\t}\n\n\tprivate async generateHandlerFile(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\tawait writeFile(\n\t\t\thandlerPath,\n\t\t\tthis.generateAWSApiGatewayV2Handler(\n\t\t\t\timportPath,\n\t\t\t\texportName,\n\t\t\t\tcontext.storageDrivers,\n\t\t\t),\n\t\t);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateEndpointsFile(\n\t\toutputDir: string,\n\t\tendpoints: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t): Promise<string> {\n\t\tconst endpointsFileName = 'endpoints.ts';\n\t\tconst endpointsPath = join(outputDir, endpointsFileName);\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\n\t\tfor (const { path, key } of endpoints) {\n\t\t\tconst relativePath = relative(dirname(endpointsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\t// Generate import statements for endpoints\n\t\tconst endpointImports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst allExportNames = endpoints.map(({ key }) => key);\n\n\t\t// One registration for every build, production included: each endpoint\n\t\t// is served by HonoEndpoint, which is what `gkm dev` and a feature test\n\t\t// serve it with. Production used to generate its own handlers per\n\t\t// \"tier\", and each was a hand-copy of the adaptor that drifted from it —\n\t\t// a session left undefined, an HttpError answered 500, an auditor\n\t\t// hard-coded to undefined, cookies a handler set never sent.\n\t\tconst content = `import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { Hono } from 'hono';\n${endpointImports}\n\nexport const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Configure OpenAPI options based on enableOpenApi flag\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n\n\t\tawait writeFile(endpointsPath, content);\n\n\t\treturn endpointsPath;\n\t}\n\n\tprivate async generateAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\t// What both entries start telemetry from — the production server and\n\t\t// `gkm dev`'s — decided by the surface's edge to a `Telemetry` node.\n\t\tawait writeTelemetryModule(outputDir, context.telemetry);\n\n\t\t// Use production generator if in production mode\n\t\tif (context.production?.enabled) {\n\t\t\treturn this.generateProductionAppFile(outputDir, context);\n\t\t}\n\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The logger and the env parser, from the surface that already holds them.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\t// Generate telescope imports and setup if enabled\n\t\tconst telescopeEnabled = context.telescope?.enabled;\n\t\tconst telescopeWebSocketEnabled = context.telescope?.websocket;\n\t\tconst usesExternalTelescope = !!context.telescope?.telescopePath;\n\n\t\t// Generate imports based on whether telescope is external or inline\n\t\tconst telescopeFromSurface =\n\t\t\t!!context.surface?.module && !usesExternalTelescope;\n\n\t\tlet telescopeImports = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface) {\n\t\t\t\t// The entry already imports the surface, which may or may not have\n\t\t\t\t// been given a Telescope — an object, so only the running entry can\n\t\t\t\t// tell. The inline one stands in when it was not.\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else if (usesExternalTelescope) {\n\t\t\t\tconst relativeTelescopePath = relative(\n\t\t\t\t\tdirname(appPath),\n\t\t\t\t\tcontext.telescope?.telescopePath!,\n\t\t\t\t);\n\t\t\t\ttelescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else {\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t}\n\t\t}\n\n\t\t// The database's read-only JSON API, from the declared database. The\n\t\t// client comes from the construct, so what it reads is by definition what\n\t\t// the handlers write to.\n\t\tconst databaseApi = context.databaseApi;\n\t\tconst databaseApiImports = databaseApi\n\t\t\t? `import { snifferContext } from '@geekmidas/constructs';\nimport { createIntrospectionHandler } from '@geekmidas/db/introspect';\nimport { ${databaseApi.database.exportName} as __introspectedDb } from '${importSpecifier(dirname(appPath), databaseApi.database.specifier)}';`\n\t\t\t: '';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\tconst telescopeWebSocketSetupCode = telescopeWebSocketEnabled\n\t\t\t? `\n // Setup WebSocket for real-time telescope updates\n try {\n const { createNodeWebSocket } = await import('@hono/node-ws');\n const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });\n // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)\n honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({\n onOpen: (_event: Event, ws: any) => {\n telescope.addWsClient(ws);\n },\n onClose: (_event: Event, ws: any) => {\n telescope.removeWsClient(ws);\n },\n onMessage: (event: MessageEvent, ws: any) => {\n try {\n const data = JSON.parse(event.data);\n if (data.type === 'ping') {\n ws.send(JSON.stringify({ type: 'pong' }));\n }\n } catch {\n // Ignore invalid messages\n }\n },\n })));\n // Store injectWebSocket for server entry to call after serve()\n (honoApp as any).__injectWebSocket = injectWebSocket;\n logger.info('Telescope WebSocket enabled');\n } catch (e) {\n logger.warn({ err: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');\n }\n`\n\t\t\t: '';\n\n\t\t// Generate telescope setup - either use external instance or create inline\n\t\tlet telescopeSetup = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface || usesExternalTelescope) {\n\t\t\t\t// Use external telescope instance - no need to create one\n\t\t\t\ttelescopeSetup = `\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t} else {\n\t\t\t\t// Create inline telescope instance\n\t\t\t\ttelescopeSetup = `\n // Setup Telescope for debugging/monitoring\n const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });\n const telescope = new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: telescopeStorage,\n });\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t}\n\t\t}\n\n\t\tconst databaseApiSetup = databaseApi\n\t\t\t? `\n // The database's structure and rows as JSON, read-only, for whatever tool\n // the developer points at it. Dev only: it answers anyone who can reach the\n // port.\n const databaseApi = createIntrospectionHandler({\n db: await __introspectedDb.service.register({ envParser, context: snifferContext }),\n basePath: '${databaseApi.path}',\n });\n honoApp.all('${databaseApi.path}/*', (c) => databaseApi(c.req.raw));\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated server application\n *\n * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY\n * The subscriber polling mechanism is not production-ready.\n * For production, use AWS Lambda with SQS/SNS event sources.\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\nimport { setupEndpoints } from './endpoints.js';\nimport { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';\n${runtime.imports}\n${telescopeImports}\n${databaseApiImports}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n${\n\ttelescopeEnabled && telescopeFromSurface\n\t\t? `// The surface's own Telescope, or the one \\`telescope\\` config describes.\nconst telescope =\n __surface.telescope ??\n new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} }),\n });`\n\t\t: ''\n}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// Which drivers exist — storage, cache, events — is the entry point's\n// decision: the scheme in each injected URL picks one, so no construct and no\n// application module names a provider.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n /** Returns the server, so a shutdown can stop it taking requests. */\n serve: (app: HonoType, port: number) => unknown;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the Hono application\n *\n * @param app - Optional Hono app instance to configure (creates new one if not provided)\n * @param enableOpenApi - Enable OpenAPI documentation (default: true)\n * @returns Server app with configured Hono app and start function\n *\n * @example\n * // With Bun\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * Bun.serve({ port, fetch: app.fetch });\n * }\n * });\n *\n * @example\n * // With Node.js (using @hono/node-server)\n * import { serve } from '@hono/node-server';\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}\n // Setup HTTP endpoints\n await setupEndpoints(honoApp, envParser, logger, enableOpenApi);\n${afterSetupCall}\n\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? 3000;\n\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background (non-blocking, local development only)\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n logger.info({ port }, 'Starting server');\n\n // Start HTTP server using provided serve function\n await options.serve(honoApp, port);\n\n logger.info({ port }, 'Server started');\n\n await subscribeForPush(port);\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * One Lambda, one endpoint — and no environment import.\n\t *\n\t * The endpoint was built from its surface, so it carries the parser the\n\t * adaptor needs. This used to read\n\t * `import { envParser } from '../../config/env'`, a line the build wrote\n\t * because a generator can print a module specifier and cannot print an\n\t * object. Nothing has to be printed now, which is also why nothing has to be\n\t * named in config.\n\t */\n\tprivate generateAWSApiGatewayV2Handler(\n\t\timportPath: string,\n\t\texportName: string,\n\t\tdrivers?: StorageDrivers,\n\t): string {\n\t\treturn `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${drivers?.imports ?? ''}\n${drivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${drivers.setup}\\n` : ''}\nconst adapter = new AmazonApiGatewayV2Endpoint(${exportName});\n\nexport const handler = adapter.handler;\n`;\n\t}\n\n\t/**\n\t * Generate a production-optimized app.ts file\n\t * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown\n\t */\n\tprivate async generateProductionAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The app entry belongs to the primary surface, so no owner is named.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\tconst production = context.production!;\n\t\tconst healthCheckPath = production.healthCheck;\n\t\tconst enableGracefulShutdown = production.gracefulShutdown;\n\t\tconst enableOpenApi = production.openapi;\n\t\tconst includeSubscribers = production.subscribers === 'include';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\t// Subscriber + queue setup code (background workers share the same flag)\n\t\tconst subscriberSetup = includeSubscribers\n\t\t\t? `\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n`\n\t\t\t: '';\n\n\t\tconst subscriberImport = includeSubscribers\n\t\t\t? `import { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';`\n\t\t\t: '';\n\n\t\t// Graceful shutdown code\n\t\tconst gracefulShutdownCode = enableGracefulShutdown\n\t\t\t? `\n // Graceful shutdown: stop taking requests, let in-flight ones finish, then\n // close what constructs opened (database pools) — so a rolling deploy does\n // not leave the old task holding connections. Bounded by\n // GKM_SHUTDOWN_TIMEOUT_MS, 8s by default: under Docker's 10s stop timeout,\n // so the process exits on its own terms rather than being killed mid-drain.\n let isShuttingDown = false;\n\n const shutdown = async () => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n await new Promise<void>((resolve) => {\n const close = (server as { close?: (done: () => void) => void } | undefined)?.close;\n if (typeof close === 'function') close.call(server, () => resolve());\n else resolve();\n });\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n process.exit(0);\n };\n\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated production server application\n *\n * This is a production-optimized build without dev tools.\n * - No Telescope debugging dashboard\n * - No Studio database browser\n * - No WebSocket updates\n * - Includes health checks and graceful shutdown\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\n${enableGracefulShutdown ? \"import { runShutdownHooks } from '@geekmidas/constructs';\\n\" : ''}import { setupEndpoints } from './endpoints.js';\n${subscriberImport}\n${runtime.imports}\n${runtime.bindings}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n serve: (app: HonoType, port: number) => void | Promise<void>;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the production Hono application\n */\nexport async function createApp(app?: HonoType): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n\n // Health check endpoint (always first)\n honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));\n honoApp.get('/ready', (c) => c.json({ ready: true }));\n\n // An HttpError a handler or a session callback throws — a 401, a 404 —\n // answers with its own status, as it does under gkm dev. The optimized\n // handlers do not catch, so without this every one of them was a 500.\n // Anything else is a 500 that says nothing about why, and is logged.\n honoApp.onError((error, c) => {\n const http = error as {\n isHttpError?: boolean;\n statusCode?: number;\n statusMessage?: string;\n code?: string;\n details?: unknown;\n };\n if (http.isHttpError === true && typeof http.statusCode === 'number') {\n return c.json(\n {\n name: error.name,\n message: error.message,\n statusCode: http.statusCode,\n statusMessage: http.statusMessage,\n code: http.code,\n details: http.details,\n },\n http.statusCode as 500,\n );\n }\n logger.error({ err: error }, 'Unhandled error');\n return c.json({ message: 'Internal Server Error' }, 500);\n });\n${cors.setup}${beforeSetupCall}\n // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})\n await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});\n${afterSetupCall}\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? Number(process.env.PORT) ?? 3000;\n let server: unknown;\n${gracefulShutdownCode}${subscriberSetup}\n logger.info({ port }, 'Starting production server');\n\n // Start HTTP server using provided serve function\n server = await options.serve(honoApp, port);\n\n logger.info({ port }, 'Production server started');\n${includeSubscribers ? '\\n await subscribeForPush(port);' : ''}\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\t// Also generate the production server entry point\n\t\tawait this.generateProductionServerEntry(outputDir, context);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * Generate production server.ts entry point\n\t */\n\tprivate async generateProductionServerEntry(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<void> {\n\t\tconst serverPath = join(outputDir, 'server.ts');\n\n\t\t// `telemetry.ts` beside it was written with `app.ts`, for this entry\n\t\t// and the `gkm dev` one alike, which start it the same way.\n\t\tconst content = `#!/usr/bin/env node\n/**\n * Production server entry point\n * Generated by 'gkm build --production'\n */\nimport { serve } from '@hono/node-server';\nimport { Hono } from 'hono';\n\n${startTelemetryCode([context.production?.healthCheck ?? '/health', '/ready'])}\nconst { createApp } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nconst app = new Hono();\n${mountRequestSpansCode('app')}\nconst created = await createApp(app);\ntrustedOrigins = created.trustedOrigins;\nconst { start } = created;\n\nawait start({\n port,\n serve: (app, port) => serve({ fetch: app.fetch, port }),\n});\n`;\n\n\t\tawait writeFile(serverPath, content);\n\t}\n}\n"],"mappings":";;;;;;;;AAkBA,SAAgB,eACf,WAKmB;CACnB,OAAO,UAAU,SAAS,aACzB,SAAS,YACN,CACA;EACC,QAAQ,SAAS;EACjB,MAAM,SAAS;EACf,GAAG,SAAS;CACb,CACD,IACC,CAAC,CACL;AACD;;;;;;;AA8BA,MAAa,qBAAqB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;AAWA,SAAS,WAAW,SAAiB,MAAkC;CACtE,KAAK,IAAI,OAAA,GAAMA,UAAAA,QAAAA,CAAQ,OAAO,IAAK,OAAA,GAAMC,UAAAA,QAAAA,CAAQ,GAAG,GAAG;EACtD,MAAM,aAAA,GAAYC,UAAAA,KAAAA,CAAK,KAAK,gBAAgB,IAAI;EAChD,KAAA,GAAIC,QAAAA,WAAAA,EAAAA,GAAWD,UAAAA,KAAAA,CAAK,WAAW,cAAc,CAAC,GAC7C,QAAA,GAAOE,QAAAA,aAAAA,CAAa,SAAS;EAE9B,KAAA,GAAIH,UAAAA,QAAAA,CAAQ,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AI9C,MAAM,UAAU;;;;;;;;EAQhB,mBAAmB,CAAC,QAAQ,YAAY,eAAe,WAAW,QAAQ,CAAC,EAAE;;;;;;EAM7E,sBAAsB,KAAK,EAAE;;;;;;;;;;EAW7B,OAAA,GAAMG,iBAAAA,UAAAA,CAAU,YAAY,OAAO;CACpC;AACD"}
@@ -1,5 +1,6 @@
1
- const require_credentials = require("./credentials-BKfIugu2.cjs");
2
- const require_seeds = require("./seeds-CkIPFGNO.cjs");
1
+ const require_errors = require("./errors-DMC4Umsb.cjs");
2
+ const require_credentials = require("./credentials-QBu7VgaQ.cjs");
3
+ const require_seeds = require("./seeds-c-ByX9je.cjs");
3
4
  /** The record types gkm writes. Never MX, TXT, NS, SOA, SRV or CAA. */
4
5
  const GODADDY_MANAGED_TYPES = [
5
6
  "A",
@@ -11,7 +12,7 @@ const GODADDY_MANAGED_TYPES = [
11
12
  * Domains and DNS APIs answer only accounts with 10 or more domains, or a
12
13
  * Discount Domain Club Premier membership.
13
14
  */
14
- var GoDaddyApiAccessDenied = class extends Error {
15
+ var GoDaddyApiAccessDenied = class extends require_errors.GkmError {
15
16
  domain;
16
17
  detail;
17
18
  constructor(domain, detail) {
@@ -22,7 +23,7 @@ var GoDaddyApiAccessDenied = class extends Error {
22
23
  }
23
24
  };
24
25
  /** The token lacks the scope a records call needs. */
25
- var GoDaddyScopeMissing = class extends Error {
26
+ var GoDaddyScopeMissing = class extends require_errors.GkmError {
26
27
  method;
27
28
  domain;
28
29
  scope;
@@ -37,7 +38,7 @@ var GoDaddyScopeMissing = class extends Error {
37
38
  }
38
39
  };
39
40
  /** GoDaddy did not accept the token at all. */
40
- var GoDaddyCredentialsInvalid = class extends Error {
41
+ var GoDaddyCredentialsInvalid = class extends require_errors.GkmError {
41
42
  code;
42
43
  constructor(code) {
43
44
  super(`GoDaddy did not accept the API token (401${code ? ` ${code}` : ""}). Check GODADDY_API_TOKEN, or run \`gkm login --provider godaddy\` again with a Personal Access Token from the GoDaddy developer dashboard that has not expired or been revoked.`);
@@ -46,7 +47,7 @@ var GoDaddyCredentialsInvalid = class extends Error {
46
47
  }
47
48
  };
48
49
  /** The domain is not in the account the token belongs to. */
49
- var GoDaddyDomainNotFound = class extends Error {
50
+ var GoDaddyDomainNotFound = class extends require_errors.GkmError {
50
51
  domain;
51
52
  code;
52
53
  constructor(domain, code) {
@@ -57,7 +58,7 @@ var GoDaddyDomainNotFound = class extends Error {
57
58
  }
58
59
  };
59
60
  /** Still rate limited after waiting it out. */
60
- var GoDaddyRateLimited = class extends Error {
61
+ var GoDaddyRateLimited = class extends require_errors.GkmError {
61
62
  attempts;
62
63
  retryAfterSec;
63
64
  constructor(attempts, retryAfterSec) {
@@ -88,7 +89,7 @@ var GoDaddyRequestFailed = class extends Error {
88
89
  * A write gkm was about to make to a record type it never manages, or to a
89
90
  * name it was not asked for.
90
91
  */
91
- var GoDaddyRecordNotAllowed = class extends Error {
92
+ var GoDaddyRecordNotAllowed = class extends require_errors.GkmError {
92
93
  domain;
93
94
  type;
94
95
  recordName;
@@ -215,7 +216,7 @@ async function errorBody(response) {
215
216
  * stored. Never logged.
216
217
  */
217
218
  /** GoDaddy cannot list a zone through the records-by-name endpoints. */
218
- var GoDaddyZoneListingUnsupported = class extends Error {
219
+ var GoDaddyZoneListingUnsupported = class extends require_errors.GkmError {
219
220
  domain;
220
221
  constructor(domain) {
221
222
  super(`gkm reads GoDaddy records by name and type only — it never lists ${domain}'s whole zone, so a token scoped to DNS updates is enough. Use readRecords(domain, [{ name, type }]) instead of getRecords.`);
@@ -384,4 +385,4 @@ var GoDaddyProvider = class {
384
385
  //#endregion
385
386
  exports.GoDaddyProvider = GoDaddyProvider;
386
387
 
387
- //# sourceMappingURL=GoDaddyProvider-DqZ1qD_F.cjs.map
388
+ //# sourceMappingURL=GoDaddyProvider-BZb-V14e.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GoDaddyProvider-BZb-V14e.cjs","names":["GkmError","GkmError","storedCredentials","MissingCredential","DnsRecordsUnreadable"],"sources":["../src/target/dokploy/dns/godaddy-api.ts","../src/target/dokploy/dns/GoDaddyProvider.ts"],"sourcesContent":["/**\n * GoDaddy's v1 DNS API, as gkm uses it: one record set — a name and a type —\n * at a time.\n *\n * - read: `GET /v1/domains/{domain}/records/{type}/{name}`\n * - write: `PUT /v1/domains/{domain}/records/{type}/{name}` with `[{ data, ttl }]`,\n * which replaces that one name's records of that one type\n * - delete: `DELETE /v1/domains/{domain}/records/{type}/{name}`\n *\n * Never the zone-wide `PUT /v1/domains/{domain}/records`, which replaces every\n * record the domain has — mail, verification TXT records and all — and never\n * a domain or account endpoint (`GET /v1/domains`, `GET /v1/domains/{domain}`):\n * a token scoped to `domains.dns:update` alone is enough. A domain that is not\n * in the token's account is told apart by the records endpoint's own 404 or 422.\n *\n * Authenticated with a Personal Access Token — `Authorization: Bearer <token>`,\n * the API's one security scheme. GoDaddy allows about 60 requests a minute per\n * token; a 429 carries `retryAfterSec`, which is waited out a few times before\n * the run gives up with {@link GoDaddyRateLimited}. A 504 is retried the same\n * way. GoDaddy refuses a TTL under 600 seconds (a 422), so every write is\n * sent with at least that.\n */\n\nimport type { GoDaddyCredential } from '../../../deploy/credentials';\nimport { GkmError } from '../../../errors';\n\nexport const GODADDY_API_BASE = 'https://api.godaddy.com';\n\n/** GoDaddy refuses a TTL below this. */\nexport const GODADDY_MIN_TTL = 600;\n\n/** The record types gkm writes. Never MX, TXT, NS, SOA, SRV or CAA. */\nexport const GODADDY_MANAGED_TYPES = ['A', 'AAAA', 'CNAME'] as const;\n\nexport type GoDaddyRecordType = (typeof GODADDY_MANAGED_TYPES)[number];\n\n/** One record as GoDaddy returns it. */\nexport interface GoDaddyRecord {\n\ttype: string;\n\tname: string;\n\tdata: string;\n\tttl?: number;\n}\n\n/** GoDaddy's error body. */\ninterface GoDaddyErrorBody {\n\tcode?: string;\n\tmessage?: string;\n\tretryAfterSec?: number;\n}\n\n/**\n * The token is good, and GoDaddy will not let it use the API: since 2024 the\n * Domains and DNS APIs answer only accounts with 10 or more domains, or a\n * Discount Domain Club Premier membership.\n */\nexport class GoDaddyApiAccessDenied extends GkmError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly detail?: string,\n\t) {\n\t\tsuper(\n\t\t\t`GoDaddy refused API access for ${domain} (403 ACCESS_DENIED${detail ? `: ${detail}` : ''}). ` +\n\t\t\t\t'GoDaddy only opens its DNS API to accounts with 10 or more domains, or ' +\n\t\t\t\t'with a Discount Domain Club Premier membership, so a valid token on a ' +\n\t\t\t\t'smaller account is refused. Either qualify the account, move the ' +\n\t\t\t\t\"domain's DNS hosting to Route53 (provider: 'route53') or Cloudflare \" +\n\t\t\t\t\"by changing its nameservers at GoDaddy, or set provider: 'manual' \" +\n\t\t\t\t'and create the records gkm prints yourself. (A scoped token without ' +\n\t\t\t\t'domains.dns:update is refused the same way — check its scopes too.)',\n\t\t);\n\t\tthis.name = 'GoDaddyApiAccessDenied';\n\t}\n}\n\n/** The token lacks the scope a records call needs. */\nexport class GoDaddyScopeMissing extends GkmError {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly domain: string,\n\t\treadonly scope: string,\n\t\treadonly detail?: string,\n\t) {\n\t\tsuper(\n\t\t\t`GoDaddy refused ${method} on ${domain}'s DNS records (403${detail ? `: ${detail}` : ''}): ` +\n\t\t\t\t`the token lacks the ${scope} scope. Create a Personal Access Token ` +\n\t\t\t\t'in the GoDaddy developer dashboard with domains.dns:update — no ' +\n\t\t\t\t'domain or account scope is needed — and set GODADDY_API_TOKEN or ' +\n\t\t\t\t'run `gkm login --provider godaddy` again.',\n\t\t);\n\t\tthis.name = 'GoDaddyScopeMissing';\n\t}\n}\n\n/** GoDaddy did not accept the token at all. */\nexport class GoDaddyCredentialsInvalid extends GkmError {\n\tconstructor(readonly code?: string) {\n\t\tsuper(\n\t\t\t`GoDaddy did not accept the API token (401${code ? ` ${code}` : ''}). ` +\n\t\t\t\t'Check GODADDY_API_TOKEN, or run `gkm login --provider godaddy` ' +\n\t\t\t\t'again with a Personal Access Token from the GoDaddy developer ' +\n\t\t\t\t'dashboard that has not expired or been revoked.',\n\t\t);\n\t\tthis.name = 'GoDaddyCredentialsInvalid';\n\t}\n}\n\n/** The domain is not in the account the token belongs to. */\nexport class GoDaddyDomainNotFound extends GkmError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly code?: string,\n\t) {\n\t\tsuper(\n\t\t\t`GoDaddy has no domain ${domain} in this token's account${code ? ` (${code})` : ''}. ` +\n\t\t\t\t'Check the root domain in dns, and that the token belongs to the account the domain is registered in.',\n\t\t);\n\t\tthis.name = 'GoDaddyDomainNotFound';\n\t}\n}\n\n/** Still rate limited after waiting it out. */\nexport class GoDaddyRateLimited extends GkmError {\n\tconstructor(\n\t\treadonly attempts: number,\n\t\treadonly retryAfterSec?: number,\n\t) {\n\t\tsuper(\n\t\t\t`GoDaddy is still rate limiting this token after ${attempts} attempts ` +\n\t\t\t\t'(429 TOO_MANY_REQUESTS — about 60 requests a minute are allowed). ' +\n\t\t\t\t`Wait${retryAfterSec ? ` ${retryAfterSec} seconds` : ' a minute'} and run it again; ` +\n\t\t\t\t'records already written are left as they are.',\n\t\t);\n\t\tthis.name = 'GoDaddyRateLimited';\n\t}\n}\n\n/** Any other failure from GoDaddy. */\nexport class GoDaddyRequestFailed extends Error {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly path: string,\n\t\treadonly status: number,\n\t\treadonly code?: string,\n\t\treadonly detail?: string,\n\t) {\n\t\tsuper(\n\t\t\t`GoDaddy answered ${method} ${path} with ${status}${code ? ` ${code}` : ''}` +\n\t\t\t\t`${detail ? `: ${detail}` : ''}.` +\n\t\t\t\t(status === 422\n\t\t\t\t\t? ' A name with a CNAME cannot also have an A or AAAA record, and the reverse — remove the other one first.'\n\t\t\t\t\t: ''),\n\t\t);\n\t\tthis.name = 'GoDaddyRequestFailed';\n\t}\n}\n\n/**\n * A write gkm was about to make to a record type it never manages, or to a\n * name it was not asked for.\n */\nexport class GoDaddyRecordNotAllowed extends GkmError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly type: string,\n\t\treadonly recordName: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`Refused to change the ${type} record '${recordName}' on ${domain}: ${reason}. ` +\n\t\t\t\t'gkm only ever writes the A, AAAA and CNAME records of the hosts it serves.',\n\t\t);\n\t\tthis.name = 'GoDaddyRecordNotAllowed';\n\t}\n}\n\nexport interface GoDaddyApiOptions {\n\tcredential: GoDaddyCredential;\n\t/** The API's base URL. GoDaddy's production API by default. */\n\tbaseUrl?: string;\n\t/** How a 429 or 504 is waited out — `setTimeout` by default; tests pass their own. */\n\tsleep?: (ms: number) => Promise<void>;\n\t/** How many times one request is sent before a 429 or 504 is final. Default 4. */\n\tmaxAttempts?: number;\n}\n\n/** A record name GoDaddy's path takes: `@` for the apex, else relative. */\nfunction isRecordName(name: string): boolean {\n\treturn (\n\t\tname === '@' ||\n\t\t/^(\\*\\.)?[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?(\\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?)*$/i.test(\n\t\t\tname,\n\t\t)\n\t);\n}\n\n/** The client. Every method touches one record set, by type and name. */\nexport class GoDaddyApi {\n\tprivate readonly baseUrl: string;\n\tprivate readonly sleep: (ms: number) => Promise<void>;\n\tprivate readonly maxAttempts: number;\n\tprivate readonly authorization: string;\n\t/** Whether a read has succeeded: a later 403 is then the token's scope. */\n\tprivate readSucceeded = false;\n\n\tconstructor(options: GoDaddyApiOptions) {\n\t\tthis.baseUrl = (options.baseUrl ?? GODADDY_API_BASE).replace(/\\/$/, '');\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis.maxAttempts = options.maxAttempts ?? 4;\n\t\tthis.authorization = `Bearer ${options.credential.token}`;\n\t}\n\n\t/** The records of one name and type — empty when there are none. */\n\tasync getRecordSet(\n\t\tdomain: string,\n\t\ttype: GoDaddyRecordType,\n\t\tname: string,\n\t): Promise<GoDaddyRecord[]> {\n\t\tthis.guard(domain, type, name);\n\t\tconst records = await this.request<GoDaddyRecord[]>(\n\t\t\t'GET',\n\t\t\tdomain,\n\t\t\tthis.recordPath(domain, type, name),\n\t\t);\n\t\treturn Array.isArray(records) ? records : [];\n\t}\n\n\t/** Replace one name's records of one type with `values`. */\n\tasync replaceRecordSet(\n\t\tdomain: string,\n\t\ttype: GoDaddyRecordType,\n\t\tname: string,\n\t\tvalues: readonly string[],\n\t\tttl: number,\n\t): Promise<void> {\n\t\tthis.guard(domain, type, name);\n\t\tawait this.request(\n\t\t\t'PUT',\n\t\t\tdomain,\n\t\t\tthis.recordPath(domain, type, name),\n\t\t\tvalues.map((data) => ({\n\t\t\t\tdata,\n\t\t\t\tttl: Math.max(ttl, GODADDY_MIN_TTL),\n\t\t\t})),\n\t\t);\n\t}\n\n\t/** Delete one name's records of one type. */\n\tasync deleteRecordSet(\n\t\tdomain: string,\n\t\ttype: GoDaddyRecordType,\n\t\tname: string,\n\t): Promise<void> {\n\t\tthis.guard(domain, type, name);\n\t\tawait this.request('DELETE', domain, this.recordPath(domain, type, name));\n\t}\n\n\tprivate recordPath(domain: string, type: string, name: string): string {\n\t\treturn `/v1/domains/${encodeURIComponent(domain)}/records/${type}/${encodeURIComponent(name)}`;\n\t}\n\n\t/** Only A, AAAA and CNAME, at a real record name. */\n\tprivate guard(domain: string, type: string, name: string): void {\n\t\tif (!(GODADDY_MANAGED_TYPES as readonly string[]).includes(type)) {\n\t\t\tthrow new GoDaddyRecordNotAllowed(\n\t\t\t\tdomain,\n\t\t\t\ttype,\n\t\t\t\tname,\n\t\t\t\t'it is not a type gkm manages',\n\t\t\t);\n\t\t}\n\t\tif (!isRecordName(name)) {\n\t\t\tthrow new GoDaddyRecordNotAllowed(\n\t\t\t\tdomain,\n\t\t\t\ttype,\n\t\t\t\tname,\n\t\t\t\t'it is not a record name relative to the domain',\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async request<T = unknown>(\n\t\tmethod: 'GET' | 'PUT' | 'DELETE',\n\t\tdomain: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<T> {\n\t\tlet retryAfterSec: number | undefined;\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\t\tmethod,\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: this.authorization,\n\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n\t\t\t\t},\n\t\t\t\t...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n\t\t\t});\n\n\t\t\tif (response.ok) {\n\t\t\t\tif (method === 'GET') this.readSucceeded = true;\n\t\t\t\tif (response.status === 204) return undefined as T;\n\t\t\t\tconst text = await response.text();\n\t\t\t\treturn (text ? JSON.parse(text) : undefined) as T;\n\t\t\t}\n\n\t\t\tconst error = await errorBody(response);\n\t\t\tif (response.status === 504 && attempt < this.maxAttempts) {\n\t\t\t\tawait this.sleep(Math.min(2 ** attempt * 1000, 30_000));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (response.status === 429) {\n\t\t\t\tretryAfterSec = error.retryAfterSec;\n\t\t\t\tif (attempt === this.maxAttempts) break;\n\t\t\t\t// GoDaddy says how long; without it, back off exponentially.\n\t\t\t\tconst waitMs =\n\t\t\t\t\tretryAfterSec !== undefined\n\t\t\t\t\t\t? Math.min(retryAfterSec, 60) * 1000\n\t\t\t\t\t\t: Math.min(2 ** attempt * 1000, 60_000);\n\t\t\t\tawait this.sleep(waitMs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new GoDaddyCredentialsInvalid(error.code);\n\t\t\t}\n\t\t\tif (response.status === 403) {\n\t\t\t\t// The account restriction says ACCESS_DENIED; a scoped token that\n\t\t\t\t// may not make this call says so, or — after a read went\n\t\t\t\t// through — can only be that.\n\t\t\t\tconst scoped =\n\t\t\t\t\t/scope/i.test(`${error.code ?? ''} ${error.message ?? ''}`) ||\n\t\t\t\t\t(method !== 'GET' && this.readSucceeded);\n\t\t\t\tif (scoped) {\n\t\t\t\t\tthrow new GoDaddyScopeMissing(\n\t\t\t\t\t\tmethod,\n\t\t\t\t\t\tdomain,\n\t\t\t\t\t\tmethod === 'GET' ? 'DNS records read' : 'domains.dns:update',\n\t\t\t\t\t\terror.message ?? error.code,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new GoDaddyApiAccessDenied(domain, error.message ?? error.code);\n\t\t\t}\n\t\t\tif (response.status === 404) {\n\t\t\t\tthrow new GoDaddyDomainNotFound(domain, error.code);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tresponse.status === 422 &&\n\t\t\t\t/domain/i.test(error.code ?? '') &&\n\t\t\t\t!/record/i.test(`${error.code ?? ''} ${error.message ?? ''}`)\n\t\t\t) {\n\t\t\t\tthrow new GoDaddyDomainNotFound(domain, error.code);\n\t\t\t}\n\t\t\tthrow new GoDaddyRequestFailed(\n\t\t\t\tmethod,\n\t\t\t\tpath,\n\t\t\t\tresponse.status,\n\t\t\t\terror.code,\n\t\t\t\terror.message,\n\t\t\t);\n\t\t}\n\t\tthrow new GoDaddyRateLimited(this.maxAttempts, retryAfterSec);\n\t}\n}\n\nasync function errorBody(response: Response): Promise<GoDaddyErrorBody> {\n\ttry {\n\t\tconst parsed = (await response.json()) as GoDaddyErrorBody;\n\t\treturn parsed && typeof parsed === 'object' ? parsed : {};\n\t} catch {\n\t\treturn {};\n\t}\n}\n","/**\n * GoDaddy DNS Provider\n *\n * Implements DnsProvider against GoDaddy's v1 API, one record set — a name\n * and a type — at a time: it reads and writes only the A, AAAA and CNAME\n * records of the names it is handed, and never the zone as a whole, a domain\n * or the account. A Personal Access Token scoped to `domains.dns:update` is all it needs.\n *\n * A token that may write records and not read them puts the provider in\n * write-only mode: every record is PUT — idempotent, so one that already has\n * its value is left as it was — and nothing is compared or deleted.\n *\n * Credentials: `GODADDY_API_TOKEN`, else what `gkm login --provider godaddy`\n * stored. Never logged.\n */\n\nimport {\n\ttype GoDaddyCredential,\n\tMissingCredential,\n\tstoredCredentials,\n} from '../../../deploy/credentials';\nimport { GkmError } from '../../../errors';\nimport {\n\ttype DeleteDnsRecord,\n\ttype DeleteResult,\n\ttype DnsProvider,\n\ttype DnsRecord,\n\tDnsRecordsUnreadable,\n\ttype UpsertDnsRecord,\n\ttype UpsertResult,\n} from './DnsProvider';\nimport {\n\tGODADDY_MANAGED_TYPES,\n\tGODADDY_MIN_TTL,\n\tGoDaddyApi,\n\tGoDaddyApiAccessDenied,\n\ttype GoDaddyApiOptions,\n\tGoDaddyDomainNotFound,\n\ttype GoDaddyRecord,\n\tGoDaddyRecordNotAllowed,\n\ttype GoDaddyRecordType,\n\tGoDaddyScopeMissing,\n} from './godaddy-api';\n\nexport interface GoDaddyProviderOptions {\n\t/** The token, when the caller already has it. */\n\tcredential?: GoDaddyCredential;\n\t/** Where the variables are read — `process.env` by default. */\n\tenv?: NodeJS.ProcessEnv;\n\t/** The CLI's home, whose `credentials.json` holds a stored login. */\n\thome?: string;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: GoDaddyApiOptions['sleep'];\n\tmaxAttempts?: number;\n\t/** Where the write-only notice goes — `console.log` by default. */\n\tlog?: (line: string) => void;\n}\n\n/** GoDaddy cannot list a zone through the records-by-name endpoints. */\nexport class GoDaddyZoneListingUnsupported extends GkmError {\n\tconstructor(readonly domain: string) {\n\t\tsuper(\n\t\t\t`gkm reads GoDaddy records by name and type only — it never lists ` +\n\t\t\t\t`${domain}'s whole zone, so a token scoped to DNS updates is enough. ` +\n\t\t\t\t'Use readRecords(domain, [{ name, type }]) instead of getRecords.',\n\t\t);\n\t\tthis.name = 'GoDaddyZoneListingUnsupported';\n\t}\n}\n\n/** A value compared the way DNS does: case-insensitive, no trailing dot. */\nfunction normalize(value: string): string {\n\treturn value.trim().replace(/\\.$/, '').toLowerCase();\n}\n\nfunction managed(type: string): type is GoDaddyRecordType {\n\treturn (GODADDY_MANAGED_TYPES as readonly string[]).includes(type);\n}\n\n/** A read GoDaddy refused: write-only, rather than a failure. */\nfunction readDenied(error: unknown): boolean {\n\treturn (\n\t\terror instanceof GoDaddyScopeMissing ||\n\t\terror instanceof GoDaddyApiAccessDenied\n\t);\n}\n\nexport class GoDaddyProvider implements DnsProvider {\n\treadonly name = 'godaddy';\n\tprivate api: GoDaddyApi | null = null;\n\t/** Set once a read is refused: every write is then a blind PUT. */\n\tprivate writeOnly = false;\n\n\tconstructor(private readonly options: GoDaddyProviderOptions = {}) {}\n\n\t/** Whether the token turned out unable to read records. */\n\tget readsDenied(): boolean {\n\t\treturn this.writeOnly;\n\t}\n\n\tprivate async getApi(): Promise<GoDaddyApi> {\n\t\tif (this.api) return this.api;\n\t\tconst credential =\n\t\t\tthis.options.credential ??\n\t\t\t(await storedCredentials({\n\t\t\t\tenv: this.options.env ?? process.env,\n\t\t\t\t...(this.options.home ? { home: this.options.home } : {}),\n\t\t\t}).get({ kind: 'godaddy' }));\n\t\tif (!credential) throw new MissingCredential('godaddy', undefined);\n\t\tthis.api = new GoDaddyApi({\n\t\t\tcredential,\n\t\t\t...(this.options.baseUrl ? { baseUrl: this.options.baseUrl } : {}),\n\t\t\t...(this.options.sleep ? { sleep: this.options.sleep } : {}),\n\t\t\t...(this.options.maxAttempts\n\t\t\t\t? { maxAttempts: this.options.maxAttempts }\n\t\t\t\t: {}),\n\t\t});\n\t\treturn this.api;\n\t}\n\n\tprivate assertManaged(domain: string, type: string, name: string): void {\n\t\tif (!managed(type)) {\n\t\t\tthrow new GoDaddyRecordNotAllowed(\n\t\t\t\tdomain,\n\t\t\t\ttype,\n\t\t\t\tname,\n\t\t\t\t'it is not a type gkm manages',\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Never: the whole zone is not read. See {@link GoDaddyZoneListingUnsupported}. */\n\tasync getRecords(domain: string): Promise<DnsRecord[]> {\n\t\tthrow new GoDaddyZoneListingUnsupported(domain);\n\t}\n\n\t/**\n\t * The records of exactly these names and types, one request each.\n\t *\n\t * @throws {DnsRecordsUnreadable} when the token may not read records\n\t */\n\tasync readRecords(\n\t\tdomain: string,\n\t\twanted: readonly DeleteDnsRecord[],\n\t): Promise<DnsRecord[]> {\n\t\tfor (const { name, type } of wanted) this.assertManaged(domain, type, name);\n\t\tconst api = await this.getApi();\n\t\tconst found: DnsRecord[] = [];\n\t\tfor (const { name, type } of wanted) {\n\t\t\tlet records: GoDaddyRecord[];\n\t\t\ttry {\n\t\t\t\trecords = await api.getRecordSet(\n\t\t\t\t\tdomain,\n\t\t\t\t\ttype as GoDaddyRecordType,\n\t\t\t\t\tname,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!readDenied(error)) throw error;\n\t\t\t\tthis.writeOnly = true;\n\t\t\t\tthrow new DnsRecordsUnreadable(\n\t\t\t\t\tthis.name,\n\t\t\t\t\tdomain,\n\t\t\t\t\t(error as Error).name,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (records.length === 0) continue;\n\t\t\tfound.push({\n\t\t\t\tname,\n\t\t\t\ttype,\n\t\t\t\tttl: records[0]!.ttl ?? GODADDY_MIN_TTL,\n\t\t\t\tvalues: records.map((r) => r.data),\n\t\t\t});\n\t\t}\n\t\treturn found;\n\t}\n\n\t/**\n\t * Each record set to exactly its one value: read it, and write it only\n\t * when it differs — or, with a token that cannot read, write it. Only the\n\t * name and type of each record handed in is touched.\n\t */\n\tasync upsertRecords(\n\t\tdomain: string,\n\t\trecords: UpsertDnsRecord[],\n\t): Promise<UpsertResult[]> {\n\t\t// Every record is checked before any is written, so a refused one\n\t\t// leaves the zone as it was.\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\n\t\tconst results: UpsertResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst type = record.type as GoDaddyRecordType;\n\t\t\tlet existing: GoDaddyRecord[] | undefined;\n\t\t\tif (!this.writeOnly) {\n\t\t\t\ttry {\n\t\t\t\t\texisting = await api.getRecordSet(domain, type, record.name);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!readDenied(error)) throw error;\n\t\t\t\t\tthis.writeOnly = true;\n\t\t\t\t\t(this.options.log ?? console.log)(\n\t\t\t\t\t\t` ℹ The GoDaddy token cannot read ${domain}'s DNS records, so changes cannot be diffed: writing each record (idempotent).`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (existing) {\n\t\t\t\tconst values = existing.map((r) => normalize(r.data));\n\t\t\t\tif (values.length === 1 && values[0] === normalize(record.value)) {\n\t\t\t\t\tresults.push({ record, created: false, unchanged: true });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait api.replaceRecordSet(\n\t\t\t\tdomain,\n\t\t\t\ttype,\n\t\t\t\trecord.name,\n\t\t\t\t[record.value],\n\t\t\t\tMath.max(record.ttl, GODADDY_MIN_TTL),\n\t\t\t);\n\t\t\tresults.push({\n\t\t\t\trecord,\n\t\t\t\tcreated: existing !== undefined && existing.length === 0,\n\t\t\t\tunchanged: false,\n\t\t\t});\n\t\t}\n\t\treturn results;\n\t}\n\n\tasync deleteRecords(\n\t\tdomain: string,\n\t\trecords: DeleteDnsRecord[],\n\t): Promise<DeleteResult[]> {\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\t\tconst results: DeleteResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst type = record.type as GoDaddyRecordType;\n\t\t\tif (!this.writeOnly) {\n\t\t\t\tlet existing: GoDaddyRecord[] | undefined;\n\t\t\t\ttry {\n\t\t\t\t\texisting = await api.getRecordSet(domain, type, record.name);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!readDenied(error)) throw error;\n\t\t\t\t\tthis.writeOnly = true;\n\t\t\t\t}\n\t\t\t\tif (existing && existing.length === 0) {\n\t\t\t\t\tresults.push({ record, deleted: false, notFound: true });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait api.deleteRecordSet(domain, type, record.name);\n\t\t\t} catch (error) {\n\t\t\t\t// Write-only, nothing was read: a record that is not there is a 404.\n\t\t\t\tif (this.writeOnly && error instanceof GoDaddyDomainNotFound) {\n\t\t\t\t\tresults.push({ record, deleted: false, notFound: true });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tresults.push({ record, deleted: true, notFound: false });\n\t\t}\n\t\treturn results;\n\t}\n}\n"],"mappings":";;;;AAgCA,MAAa,wBAAwB;CAAC;CAAK;CAAQ;AAAO;;;;;;AAwB1D,IAAa,yBAAb,cAA4CA,eAAAA,SAAS;CAE1C;CACA;CAFV,YACC,QACA,QACC;EACD,MACC,kCAAkC,OAAO,qBAAqB,SAAS,KAAK,WAAW,GAAG,+dAQ3F;EAZS,KAAA,SAAA;EACA,KAAA,SAAA;EAYT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,sBAAb,cAAyCA,eAAAA,SAAS;CAEvC;CACA;CACA;CACA;CAJV,YACC,QACA,QACA,OACA,QACC;EACD,MACC,mBAAmB,OAAO,MAAM,OAAO,qBAAqB,SAAS,KAAK,WAAW,GAAG,yBAChE,MAAM,oNAI/B;EAXS,KAAA,SAAA;EACA,KAAA,SAAA;EACA,KAAA,QAAA;EACA,KAAA,SAAA;EAST,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,4BAAb,cAA+CA,eAAAA,SAAS;CAClC;CAArB,YAAY,MAAwB;EACnC,MACC,4CAA4C,OAAO,IAAI,SAAS,GAAG,kLAIpE;EANoB,KAAA,OAAA;EAOpB,KAAK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AAM,IAAI,aAAa,QAAQ,MAAM,OAAO,IAAI;IAC5D,SAAS,OAAO;KACf,IAAI,CAAC,WAAW,KAAK,GAAG,MAAM;KAC9B,KAAK,YAAY;IAClB;IACA,IAAI,YAAY,SAAS,WAAW,GAAG;KACtC,QAAQ,KAAK;MAAE;MAAQ,SAAS;MAAO,UAAU;KAAK,CAAC;KACvD;IACD;GACD;GACA,IAAI;IACH,MAAM,IAAI,gBAAgB,QAAQ,MAAM,OAAO,IAAI;GACpD,SAAS,OAAO;IAEf,IAAI,KAAK,aAAa,iBAAiB,uBAAuB;KAC7D,QAAQ,KAAK;MAAE;MAAQ,SAAS;MAAO,UAAU;KAAK,CAAC;KACvD;IACD;IACA,MAAM;GACP;GACA,QAAQ,KAAK;IAAE;IAAQ,SAAS;IAAM,UAAU;GAAM,CAAC;EACxD;EACA,OAAO;CACR;AACD"}
@@ -1,5 +1,6 @@
1
- import { r as storedCredentials, t as MissingCredential } from "./credentials-CnVqoXMb.mjs";
2
- import { P as DnsRecordsUnreadable } from "./seeds-odfgSCmu.mjs";
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { r as storedCredentials, t as MissingCredential } from "./credentials-C4KII3PD.mjs";
3
+ import { U as DnsRecordsUnreadable } from "./seeds-BSL55F6q.mjs";
3
4
  /** The record types gkm writes. Never MX, TXT, NS, SOA, SRV or CAA. */
4
5
  const GODADDY_MANAGED_TYPES = [
5
6
  "A",
@@ -11,7 +12,7 @@ const GODADDY_MANAGED_TYPES = [
11
12
  * Domains and DNS APIs answer only accounts with 10 or more domains, or a
12
13
  * Discount Domain Club Premier membership.
13
14
  */
14
- var GoDaddyApiAccessDenied = class extends Error {
15
+ var GoDaddyApiAccessDenied = class extends GkmError {
15
16
  domain;
16
17
  detail;
17
18
  constructor(domain, detail) {
@@ -22,7 +23,7 @@ var GoDaddyApiAccessDenied = class extends Error {
22
23
  }
23
24
  };
24
25
  /** The token lacks the scope a records call needs. */
25
- var GoDaddyScopeMissing = class extends Error {
26
+ var GoDaddyScopeMissing = class extends GkmError {
26
27
  method;
27
28
  domain;
28
29
  scope;
@@ -37,7 +38,7 @@ var GoDaddyScopeMissing = class extends Error {
37
38
  }
38
39
  };
39
40
  /** GoDaddy did not accept the token at all. */
40
- var GoDaddyCredentialsInvalid = class extends Error {
41
+ var GoDaddyCredentialsInvalid = class extends GkmError {
41
42
  code;
42
43
  constructor(code) {
43
44
  super(`GoDaddy did not accept the API token (401${code ? ` ${code}` : ""}). Check GODADDY_API_TOKEN, or run \`gkm login --provider godaddy\` again with a Personal Access Token from the GoDaddy developer dashboard that has not expired or been revoked.`);
@@ -46,7 +47,7 @@ var GoDaddyCredentialsInvalid = class extends Error {
46
47
  }
47
48
  };
48
49
  /** The domain is not in the account the token belongs to. */
49
- var GoDaddyDomainNotFound = class extends Error {
50
+ var GoDaddyDomainNotFound = class extends GkmError {
50
51
  domain;
51
52
  code;
52
53
  constructor(domain, code) {
@@ -57,7 +58,7 @@ var GoDaddyDomainNotFound = class extends Error {
57
58
  }
58
59
  };
59
60
  /** Still rate limited after waiting it out. */
60
- var GoDaddyRateLimited = class extends Error {
61
+ var GoDaddyRateLimited = class extends GkmError {
61
62
  attempts;
62
63
  retryAfterSec;
63
64
  constructor(attempts, retryAfterSec) {
@@ -88,7 +89,7 @@ var GoDaddyRequestFailed = class extends Error {
88
89
  * A write gkm was about to make to a record type it never manages, or to a
89
90
  * name it was not asked for.
90
91
  */
91
- var GoDaddyRecordNotAllowed = class extends Error {
92
+ var GoDaddyRecordNotAllowed = class extends GkmError {
92
93
  domain;
93
94
  type;
94
95
  recordName;
@@ -215,7 +216,7 @@ async function errorBody(response) {
215
216
  * stored. Never logged.
216
217
  */
217
218
  /** GoDaddy cannot list a zone through the records-by-name endpoints. */
218
- var GoDaddyZoneListingUnsupported = class extends Error {
219
+ var GoDaddyZoneListingUnsupported = class extends GkmError {
219
220
  domain;
220
221
  constructor(domain) {
221
222
  super(`gkm reads GoDaddy records by name and type only — it never lists ${domain}'s whole zone, so a token scoped to DNS updates is enough. Use readRecords(domain, [{ name, type }]) instead of getRecords.`);
@@ -384,4 +385,4 @@ var GoDaddyProvider = class {
384
385
  //#endregion
385
386
  export { GoDaddyProvider };
386
387
 
387
- //# sourceMappingURL=GoDaddyProvider-DSStJVAv.mjs.map
388
+ //# sourceMappingURL=GoDaddyProvider-Mi3vptSR.mjs.map