@langwatch/server 3.1.0-beta.4 → 3.1.0-beta.6

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 (328) hide show
  1. package/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
  2. package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
  3. package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
  4. package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
  5. package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
  6. package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
  7. package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
  8. package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
  9. package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
  10. package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
  11. package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
  12. package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
  13. package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
  14. package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
  15. package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
  16. package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
  17. package/langwatch/ee/admin/impersonation.service.ts +170 -0
  18. package/langwatch/ee/admin/isAdmin.ts +9 -0
  19. package/langwatch/ee/admin/routes/admin.ts +531 -0
  20. package/langwatch/ee/admin/safeSelects.ts +64 -0
  21. package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
  22. package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
  23. package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
  24. package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
  25. package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
  26. package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
  27. package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
  28. package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
  29. package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
  30. package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
  31. package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
  32. package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
  33. package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
  34. package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
  35. package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
  36. package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
  37. package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
  38. package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
  39. package/langwatch/ee/billing/currencyRouter.ts +18 -0
  40. package/langwatch/ee/billing/errors.ts +129 -0
  41. package/langwatch/ee/billing/index.ts +67 -0
  42. package/langwatch/ee/billing/middleware.ts +17 -0
  43. package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
  44. package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
  45. package/langwatch/ee/billing/notifications/types.ts +9 -0
  46. package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
  47. package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
  48. package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
  49. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
  50. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
  51. package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
  52. package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
  53. package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
  54. package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
  55. package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
  56. package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
  57. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
  58. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
  59. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
  60. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
  61. package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
  62. package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
  63. package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
  64. package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
  65. package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
  66. package/langwatch/ee/billing/nurturing/types.ts +125 -0
  67. package/langwatch/ee/billing/planLimits.ts +190 -0
  68. package/langwatch/ee/billing/planProvider.ts +119 -0
  69. package/langwatch/ee/billing/planTypes.ts +53 -0
  70. package/langwatch/ee/billing/pricing.ts +57 -0
  71. package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
  72. package/langwatch/ee/billing/services/customerService.ts +90 -0
  73. package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
  74. package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
  75. package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
  76. package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
  77. package/langwatch/ee/billing/services/subscription.service.ts +549 -0
  78. package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
  79. package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
  80. package/langwatch/ee/billing/services/webhookService.ts +858 -0
  81. package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
  82. package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
  83. package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
  84. package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
  85. package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
  86. package/langwatch/ee/billing/types.ts +102 -0
  87. package/langwatch/ee/billing/utils/currency.ts +99 -0
  88. package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
  89. package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
  90. package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
  91. package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
  92. package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
  93. package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
  94. package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
  95. package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
  96. package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
  97. package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
  98. package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
  99. package/langwatch/ee/licensing/client.ts +29 -0
  100. package/langwatch/ee/licensing/constants.ts +195 -0
  101. package/langwatch/ee/licensing/defaults.ts +55 -0
  102. package/langwatch/ee/licensing/errors.ts +11 -0
  103. package/langwatch/ee/licensing/index.ts +52 -0
  104. package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
  105. package/langwatch/ee/licensing/licenseHandler.ts +308 -0
  106. package/langwatch/ee/licensing/planInfo.ts +46 -0
  107. package/langwatch/ee/licensing/planMapping.ts +37 -0
  108. package/langwatch/ee/licensing/planTemplates.ts +109 -0
  109. package/langwatch/ee/licensing/server.ts +43 -0
  110. package/langwatch/ee/licensing/signing.ts +43 -0
  111. package/langwatch/ee/licensing/types.ts +156 -0
  112. package/langwatch/ee/licensing/validation.ts +107 -0
  113. package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
  114. package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
  115. package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
  116. package/langwatch/package.json +1 -1
  117. package/langwatch/pnpm-workspace.yaml +0 -1
  118. package/mcp-server/.env.example +2 -0
  119. package/mcp-server/.eslintrc.cjs +36 -0
  120. package/mcp-server/CHANGELOG.md +165 -0
  121. package/mcp-server/CONTRIBUTING.md +96 -0
  122. package/mcp-server/README.md +172 -0
  123. package/mcp-server/dist/archive-scenario-WJ2A7ETN.js +19 -0
  124. package/mcp-server/dist/archive-suite-4JOM4SSL.js +15 -0
  125. package/mcp-server/dist/assign-prompt-tag-GL7EAAF3.js +19 -0
  126. package/mcp-server/dist/chunk-2GT7IFWK.js +40 -0
  127. package/mcp-server/dist/chunk-2WPLXEKF.js +127 -0
  128. package/mcp-server/dist/chunk-4AUB2BIA.js +71 -0
  129. package/mcp-server/dist/chunk-BWWY5KEF.js +71 -0
  130. package/mcp-server/dist/chunk-CCWCIJJ3.js +22 -0
  131. package/mcp-server/dist/chunk-EGH5RPXM.js +25 -0
  132. package/mcp-server/dist/chunk-EUQDVOSU.js +39 -0
  133. package/mcp-server/dist/chunk-HYMIWO3U.js +44 -0
  134. package/mcp-server/dist/chunk-IE4M5OGE.js +42 -0
  135. package/mcp-server/dist/chunk-LUMEZEHL.js +48 -0
  136. package/mcp-server/dist/chunk-NUFPTHKU.js +9 -0
  137. package/mcp-server/dist/chunk-UDHJYT6P.js +1567 -0
  138. package/mcp-server/dist/chunk-WQG2DFHX.js +86 -0
  139. package/mcp-server/dist/chunk-WVI5CJ6S.js +21 -0
  140. package/mcp-server/dist/chunk-ZVS4UKN2.js +35 -0
  141. package/mcp-server/dist/chunk-ZXKLPC2E.js +27 -0
  142. package/mcp-server/dist/config.d.ts +17 -0
  143. package/mcp-server/dist/config.js +13 -0
  144. package/mcp-server/dist/create-agent-MBOOT3XK.js +23 -0
  145. package/mcp-server/dist/create-annotation-XMV6A7ED.js +24 -0
  146. package/mcp-server/dist/create-dashboard-VRKLFVZJ.js +18 -0
  147. package/mcp-server/dist/create-dataset-7HQPZCRE.js +22 -0
  148. package/mcp-server/dist/create-dataset-records-2NIVFYTV.js +22 -0
  149. package/mcp-server/dist/create-evaluator-WYFRFLRC.js +27 -0
  150. package/mcp-server/dist/create-mcp-server.d.ts +8 -0
  151. package/mcp-server/dist/create-mcp-server.js +8 -0
  152. package/mcp-server/dist/create-prompt-IEN7O6JT.js +39 -0
  153. package/mcp-server/dist/create-prompt-tag-CAEZ45VO.js +17 -0
  154. package/mcp-server/dist/create-scenario-6YHSMGLP.js +26 -0
  155. package/mcp-server/dist/create-suite-H5XOFDE5.js +38 -0
  156. package/mcp-server/dist/delete-agent-JKTNBWAA.js +18 -0
  157. package/mcp-server/dist/delete-annotation-ACMDV6QO.js +17 -0
  158. package/mcp-server/dist/delete-dashboard-VJSR7CRU.js +18 -0
  159. package/mcp-server/dist/delete-dataset-RTTTWP4D.js +20 -0
  160. package/mcp-server/dist/delete-dataset-records-KNQTIPQK.js +21 -0
  161. package/mcp-server/dist/delete-evaluator-7FVC5WM4.js +15 -0
  162. package/mcp-server/dist/delete-prompt-tag-ZMZUAGFW.js +17 -0
  163. package/mcp-server/dist/delete-workflow-EYQ3T4RQ.js +17 -0
  164. package/mcp-server/dist/discover-evaluator-schema-H23XCLNE.js +1402 -0
  165. package/mcp-server/dist/discover-scenario-schema-MEEEVND7.js +65 -0
  166. package/mcp-server/dist/discover-schema-3T52ORPB.js +446 -0
  167. package/mcp-server/dist/get-agent-E3QSTVKG.js +28 -0
  168. package/mcp-server/dist/get-analytics-2OHV763I.js +72 -0
  169. package/mcp-server/dist/get-dashboard-PC7JDHH6.js +29 -0
  170. package/mcp-server/dist/get-dataset-H5IK5FVU.js +48 -0
  171. package/mcp-server/dist/get-evaluator-UWVUPYTM.js +47 -0
  172. package/mcp-server/dist/get-prompt-WZUOLLQC.js +45 -0
  173. package/mcp-server/dist/get-scenario-Q6LCNUYN.js +33 -0
  174. package/mcp-server/dist/get-simulation-run-Z2XKO256.js +56 -0
  175. package/mcp-server/dist/get-suite-BXK5TN7P.js +44 -0
  176. package/mcp-server/dist/get-trace-4EJAYVBG.js +50 -0
  177. package/mcp-server/dist/get-workflow-O34QJLHD.js +25 -0
  178. package/mcp-server/dist/http-server-RSTXN4CN.js +224 -0
  179. package/mcp-server/dist/index.d.ts +2 -0
  180. package/mcp-server/dist/index.js +67774 -0
  181. package/mcp-server/dist/langwatch-api-annotations-ERBG27RF.js +17 -0
  182. package/mcp-server/dist/langwatch-api-dashboards-G6TR7VVO.js +17 -0
  183. package/mcp-server/dist/langwatch-api-monitors-WSXZLS2B.js +52 -0
  184. package/mcp-server/dist/langwatch-api-secrets-RR5DKG2X.js +40 -0
  185. package/mcp-server/dist/langwatch-api-triggers-2RTNSWQY.js +30 -0
  186. package/mcp-server/dist/langwatch-api-workflows-VJRIIDZ7.js +15 -0
  187. package/mcp-server/dist/list-agents-AW3P6FJV.js +32 -0
  188. package/mcp-server/dist/list-annotations-QNCGWPQ3.js +33 -0
  189. package/mcp-server/dist/list-dashboards-R7RK2IXL.js +32 -0
  190. package/mcp-server/dist/list-dataset-records-WVCSQP7P.js +39 -0
  191. package/mcp-server/dist/list-datasets-KEXRLDEU.js +60 -0
  192. package/mcp-server/dist/list-evaluators-7R2LB4JH.js +34 -0
  193. package/mcp-server/dist/list-model-providers-OBYJCKBX.js +35 -0
  194. package/mcp-server/dist/list-prompt-tags-6LY3ZPYI.js +23 -0
  195. package/mcp-server/dist/list-prompts-VWEZ4CDE.js +32 -0
  196. package/mcp-server/dist/list-scenarios-TXD4W2ZJ.js +40 -0
  197. package/mcp-server/dist/list-simulation-runs-RHPOLMFI.js +43 -0
  198. package/mcp-server/dist/list-suites-FSGBX27Z.js +42 -0
  199. package/mcp-server/dist/list-workflows-VRGEZ3EN.js +35 -0
  200. package/mcp-server/dist/rename-prompt-tag-VOJJLX4M.js +18 -0
  201. package/mcp-server/dist/run-agent-KTCC7TB7.js +36 -0
  202. package/mcp-server/dist/run-evaluation-2X3V3Q6L.js +64 -0
  203. package/mcp-server/dist/run-suite-BTMHGI2D.js +29 -0
  204. package/mcp-server/dist/run-workflow-IGAYGKJL.js +36 -0
  205. package/mcp-server/dist/search-traces-VYFUIMXH.js +72 -0
  206. package/mcp-server/dist/set-model-provider-W5IUI326.js +33 -0
  207. package/mcp-server/dist/update-agent-4BB7EYLR.js +20 -0
  208. package/mcp-server/dist/update-dataset-CXBKZ4W3.js +22 -0
  209. package/mcp-server/dist/update-dataset-record-HOHAMHXG.js +19 -0
  210. package/mcp-server/dist/update-evaluator-IVOR6FTR.js +24 -0
  211. package/mcp-server/dist/update-prompt-OWQAKE7K.js +24 -0
  212. package/mcp-server/dist/update-scenario-GDFVILPN.js +27 -0
  213. package/mcp-server/dist/update-suite-BXYUYSPT.js +39 -0
  214. package/mcp-server/package.json +79 -0
  215. package/mcp-server/pnpm-lock.yaml +6103 -0
  216. package/mcp-server/pnpm-workspace.yaml +2 -0
  217. package/mcp-server/pyproject.toml +17 -0
  218. package/mcp-server/src/__tests__/all-tools.integration.test.ts +1681 -0
  219. package/mcp-server/src/__tests__/config.unit.test.ts +169 -0
  220. package/mcp-server/src/__tests__/datasets.integration.test.ts +603 -0
  221. package/mcp-server/src/__tests__/datasets.unit.test.ts +240 -0
  222. package/mcp-server/src/__tests__/date-parsing.unit.test.ts +78 -0
  223. package/mcp-server/src/__tests__/discover-evaluator-schema.unit.test.ts +89 -0
  224. package/mcp-server/src/__tests__/discover-schema.unit.test.ts +118 -0
  225. package/mcp-server/src/__tests__/docker.integration.test.ts +234 -0
  226. package/mcp-server/src/__tests__/evaluator-tools.unit.test.ts +262 -0
  227. package/mcp-server/src/__tests__/http-transport.integration.test.ts +397 -0
  228. package/mcp-server/src/__tests__/integration.integration.test.ts +288 -0
  229. package/mcp-server/src/__tests__/langwatch-api.unit.test.ts +455 -0
  230. package/mcp-server/src/__tests__/model-provider-tools.unit.test.ts +190 -0
  231. package/mcp-server/src/__tests__/scenario-tools.integration.test.ts +286 -0
  232. package/mcp-server/src/__tests__/scenario-tools.unit.test.ts +185 -0
  233. package/mcp-server/src/__tests__/schemas.unit.test.ts +85 -0
  234. package/mcp-server/src/__tests__/tools.unit.test.ts +900 -0
  235. package/mcp-server/src/config.d.ts +15 -0
  236. package/mcp-server/src/config.ts +107 -0
  237. package/mcp-server/src/create-mcp-server.d.ts +6 -0
  238. package/mcp-server/src/create-mcp-server.ts +1799 -0
  239. package/mcp-server/src/http-server.ts +329 -0
  240. package/mcp-server/src/index.ts +46 -0
  241. package/mcp-server/src/langwatch-api-agents.ts +108 -0
  242. package/mcp-server/src/langwatch-api-annotations.ts +49 -0
  243. package/mcp-server/src/langwatch-api-dashboards.ts +48 -0
  244. package/mcp-server/src/langwatch-api-datasets.ts +191 -0
  245. package/mcp-server/src/langwatch-api-evaluators.ts +80 -0
  246. package/mcp-server/src/langwatch-api-model-providers.ts +41 -0
  247. package/mcp-server/src/langwatch-api-monitors.ts +82 -0
  248. package/mcp-server/src/langwatch-api-scenarios.ts +67 -0
  249. package/mcp-server/src/langwatch-api-secrets.ts +48 -0
  250. package/mcp-server/src/langwatch-api-simulation-runs.ts +51 -0
  251. package/mcp-server/src/langwatch-api-suites.ts +118 -0
  252. package/mcp-server/src/langwatch-api-triggers.ts +48 -0
  253. package/mcp-server/src/langwatch-api-workflows.ts +41 -0
  254. package/mcp-server/src/langwatch-api.ts +299 -0
  255. package/mcp-server/src/schemas/analytics-groups.ts +78 -0
  256. package/mcp-server/src/schemas/analytics-metrics.ts +179 -0
  257. package/mcp-server/src/schemas/create-dataset.ts +48 -0
  258. package/mcp-server/src/schemas/filter-fields.ts +119 -0
  259. package/mcp-server/src/schemas/index.ts +4 -0
  260. package/mcp-server/src/tools/archive-scenario.ts +19 -0
  261. package/mcp-server/src/tools/archive-suite.ts +12 -0
  262. package/mcp-server/src/tools/assign-prompt-tag.ts +16 -0
  263. package/mcp-server/src/tools/create-agent.ts +15 -0
  264. package/mcp-server/src/tools/create-annotation.ts +18 -0
  265. package/mcp-server/src/tools/create-dashboard.ts +7 -0
  266. package/mcp-server/src/tools/create-dataset-records.ts +23 -0
  267. package/mcp-server/src/tools/create-dataset.ts +22 -0
  268. package/mcp-server/src/tools/create-evaluator.ts +33 -0
  269. package/mcp-server/src/tools/create-prompt-tag.ts +12 -0
  270. package/mcp-server/src/tools/create-prompt.ts +58 -0
  271. package/mcp-server/src/tools/create-scenario.ts +30 -0
  272. package/mcp-server/src/tools/create-suite.ts +42 -0
  273. package/mcp-server/src/tools/delete-agent.ts +7 -0
  274. package/mcp-server/src/tools/delete-annotation.ts +7 -0
  275. package/mcp-server/src/tools/delete-dashboard.ts +7 -0
  276. package/mcp-server/src/tools/delete-dataset-records.ts +22 -0
  277. package/mcp-server/src/tools/delete-dataset.ts +20 -0
  278. package/mcp-server/src/tools/delete-evaluator.ts +12 -0
  279. package/mcp-server/src/tools/delete-prompt-tag.ts +12 -0
  280. package/mcp-server/src/tools/delete-workflow.ts +7 -0
  281. package/mcp-server/src/tools/discover-evaluator-schema.ts +143 -0
  282. package/mcp-server/src/tools/discover-scenario-schema.ts +71 -0
  283. package/mcp-server/src/tools/discover-schema.ts +106 -0
  284. package/mcp-server/src/tools/format-dataset-mutation.ts +25 -0
  285. package/mcp-server/src/tools/get-agent.ts +21 -0
  286. package/mcp-server/src/tools/get-analytics.ts +98 -0
  287. package/mcp-server/src/tools/get-dashboard.ts +22 -0
  288. package/mcp-server/src/tools/get-dataset.ts +63 -0
  289. package/mcp-server/src/tools/get-evaluator.ts +53 -0
  290. package/mcp-server/src/tools/get-prompt.ts +54 -0
  291. package/mcp-server/src/tools/get-scenario.ts +36 -0
  292. package/mcp-server/src/tools/get-simulation-run.ts +60 -0
  293. package/mcp-server/src/tools/get-suite.ts +47 -0
  294. package/mcp-server/src/tools/get-trace.ts +61 -0
  295. package/mcp-server/src/tools/get-workflow.ts +17 -0
  296. package/mcp-server/src/tools/list-agents.ts +27 -0
  297. package/mcp-server/src/tools/list-annotations.ts +33 -0
  298. package/mcp-server/src/tools/list-dashboards.ts +27 -0
  299. package/mcp-server/src/tools/list-dataset-records.ts +46 -0
  300. package/mcp-server/src/tools/list-datasets.ts +80 -0
  301. package/mcp-server/src/tools/list-evaluators.ts +37 -0
  302. package/mcp-server/src/tools/list-model-providers.ts +40 -0
  303. package/mcp-server/src/tools/list-prompt-tags.ts +21 -0
  304. package/mcp-server/src/tools/list-prompts.ts +34 -0
  305. package/mcp-server/src/tools/list-scenarios.ts +47 -0
  306. package/mcp-server/src/tools/list-simulation-runs.ts +49 -0
  307. package/mcp-server/src/tools/list-suites.ts +43 -0
  308. package/mcp-server/src/tools/list-workflows.ts +31 -0
  309. package/mcp-server/src/tools/rename-prompt-tag.ts +14 -0
  310. package/mcp-server/src/tools/run-agent.ts +36 -0
  311. package/mcp-server/src/tools/run-evaluation.ts +87 -0
  312. package/mcp-server/src/tools/run-suite.ts +28 -0
  313. package/mcp-server/src/tools/run-workflow.ts +36 -0
  314. package/mcp-server/src/tools/search-traces.ts +91 -0
  315. package/mcp-server/src/tools/set-model-provider.ts +46 -0
  316. package/mcp-server/src/tools/update-agent.ts +13 -0
  317. package/mcp-server/src/tools/update-dataset-record.ts +21 -0
  318. package/mcp-server/src/tools/update-dataset.ts +23 -0
  319. package/mcp-server/src/tools/update-evaluator.ts +30 -0
  320. package/mcp-server/src/tools/update-prompt.ts +31 -0
  321. package/mcp-server/src/tools/update-scenario.ts +32 -0
  322. package/mcp-server/src/tools/update-suite.ts +44 -0
  323. package/mcp-server/src/utils/date-parsing.ts +31 -0
  324. package/mcp-server/src/utils/escape-markdown.ts +12 -0
  325. package/mcp-server/tsconfig.json +27 -0
  326. package/mcp-server/uv.lock +2731 -0
  327. package/package.json +2 -1
  328. package/packages/server/dist/cli.cjs +1 -1
@@ -0,0 +1,13 @@
1
+ import Stripe from "stripe";
2
+ import { env } from "../../../src/env.mjs";
3
+
4
+ export const createStripeClient = () => {
5
+ const secretKey = env.STRIPE_SECRET_KEY;
6
+ if (!secretKey) {
7
+ throw new Error("STRIPE_SECRET_KEY is required for SaaS billing runtime");
8
+ }
9
+
10
+ return new Stripe(secretKey, {
11
+ apiVersion: "2024-04-10",
12
+ });
13
+ };
@@ -0,0 +1,70 @@
1
+ import stripeCatalogData from "./stripeCatalog.json";
2
+ import {
3
+ STRIPE_METER_NAMES,
4
+ STRIPE_PRICE_NAMES,
5
+ type StripeEnvironment,
6
+ type StripeMeterMap,
7
+ type StripePriceMap,
8
+ type StripePriceName,
9
+ type StripePricesFile,
10
+ stripePricesFileSchema,
11
+ } from "./stripePrices.types";
12
+
13
+ export const parseStripePricesFile = (value: unknown): StripePricesFile => {
14
+ return stripePricesFileSchema.parse(value);
15
+ };
16
+
17
+ export const getStripeEnvironmentFromNodeEnv = (
18
+ nodeEnv = process.env.NODE_ENV,
19
+ ): StripeEnvironment => {
20
+ return nodeEnv === "production" ? "live" : "test";
21
+ };
22
+
23
+ export const resolveStripePriceMap = (
24
+ data: StripePricesFile,
25
+ environment: StripeEnvironment,
26
+ ): StripePriceMap => {
27
+ const resolvedPrices = {} as StripePriceMap;
28
+
29
+ for (const key of STRIPE_PRICE_NAMES) {
30
+ const priceId = data.mapping[key][environment];
31
+ if (!priceId) {
32
+ throw new Error(`Missing mapped price for ${key} in ${environment} mode`);
33
+ }
34
+
35
+ resolvedPrices[key] = priceId;
36
+ }
37
+
38
+ return resolvedPrices;
39
+ };
40
+
41
+ export const stripePricesFile = parseStripePricesFile(stripeCatalogData);
42
+
43
+ export const prices = resolveStripePriceMap(
44
+ stripePricesFile,
45
+ getStripeEnvironmentFromNodeEnv(),
46
+ );
47
+
48
+ export const resolveStripeMeterMap = (
49
+ data: StripePricesFile,
50
+ environment: StripeEnvironment,
51
+ ): StripeMeterMap => {
52
+ const resolved = {} as StripeMeterMap;
53
+ for (const key of STRIPE_METER_NAMES) {
54
+ const meterId = data.meters?.[key]?.[environment];
55
+ if (!meterId) {
56
+ throw new Error(`Missing mapped meter for ${key} in ${environment} mode`);
57
+ }
58
+ resolved[key] = meterId;
59
+ }
60
+ return resolved;
61
+ };
62
+
63
+ export const meters = resolveStripeMeterMap(
64
+ stripePricesFile,
65
+ getStripeEnvironmentFromNodeEnv(),
66
+ );
67
+
68
+ export const isStripePriceName = (value: string): value is StripePriceName => {
69
+ return STRIPE_PRICE_NAMES.includes(value as StripePriceName);
70
+ };
@@ -0,0 +1,118 @@
1
+ export const STRIPE_PRICE_NAMES = [
2
+ "PRO",
3
+ "GROWTH",
4
+ "LAUNCH",
5
+ "LAUNCH_ANNUAL",
6
+ "ACCELERATE",
7
+ "ACCELERATE_ANNUAL",
8
+ "LAUNCH_USERS",
9
+ "ACCELERATE_USERS",
10
+ "LAUNCH_TRACES_10K",
11
+ "ACCELERATE_TRACES_100K",
12
+ "LAUNCH_ANNUAL_TRACES_10K",
13
+ "ACCELERATE_ANNUAL_TRACES_100K",
14
+ "LAUNCH_ANNUAL_USERS",
15
+ "ACCELERATE_ANNUAL_USERS",
16
+ "GROWTH_SEAT_EUR_MONTHLY",
17
+ "GROWTH_SEAT_EUR_ANNUAL",
18
+ "GROWTH_SEAT_USD_MONTHLY",
19
+ "GROWTH_SEAT_USD_ANNUAL",
20
+ "GROWTH_EVENTS_EUR_MONTHLY",
21
+ "GROWTH_EVENTS_EUR_ANNUAL",
22
+ "GROWTH_EVENTS_USD_MONTHLY",
23
+ "GROWTH_EVENTS_USD_ANNUAL",
24
+ "GROWTH_EVENTS_EUR_MONTHLY_UNTIL_MAR_2026",
25
+ "GROWTH_EVENTS_EUR_ANNUAL_UNTIL_MAR_2026",
26
+ "GROWTH_EVENTS_USD_MONTHLY_UNTIL_MAR_2026",
27
+ "GROWTH_EVENTS_USD_ANNUAL_UNTIL_MAR_2026",
28
+ ] as const;
29
+
30
+ export type StripePriceName = (typeof STRIPE_PRICE_NAMES)[number];
31
+
32
+ export type StripeEnvironment = "test" | "live";
33
+
34
+ export type StripePriceDetail = {
35
+ id: string;
36
+ active: boolean;
37
+ livemode: boolean;
38
+ product: string | null;
39
+ unitAmount: number | null;
40
+ currency: string;
41
+ type: "one_time" | "recurring";
42
+ recurring: {
43
+ interval: "day" | "week" | "month" | "year";
44
+ intervalCount: number;
45
+ } | null;
46
+ nickname: string | null;
47
+ lookupKey: string | null;
48
+ metadata: Record<string, string>;
49
+ };
50
+
51
+ export type StripePriceMapping = Record<
52
+ StripePriceName,
53
+ Record<StripeEnvironment, string>
54
+ >;
55
+
56
+ export const STRIPE_METER_NAMES = ["BILLABLE_EVENTS"] as const;
57
+ export type StripeMeterName = (typeof STRIPE_METER_NAMES)[number];
58
+ export type StripeMeterMapping = Record<
59
+ StripeMeterName,
60
+ Record<StripeEnvironment, string>
61
+ >;
62
+ export type StripeMeterMap = Record<StripeMeterName, string>;
63
+
64
+ export type StripePricesFile = {
65
+ schemaVersion: number;
66
+ updatedAt: string;
67
+ mapping: StripePriceMapping;
68
+ meters: StripeMeterMapping;
69
+ prices: Record<string, StripePriceDetail>;
70
+ };
71
+
72
+ export type StripePriceMap = Record<StripePriceName, string>;
73
+
74
+ import { z } from "zod";
75
+
76
+ export const stripePriceRecurringSchema = z.object({
77
+ interval: z.enum(["day", "week", "month", "year"]),
78
+ intervalCount: z.number(),
79
+ });
80
+
81
+ export const stripePriceDetailSchema = z.object({
82
+ id: z.string(),
83
+ active: z.boolean(),
84
+ livemode: z.boolean(),
85
+ product: z.string().nullable(),
86
+ unitAmount: z.number().nullable(),
87
+ currency: z.string(),
88
+ type: z.enum(["one_time", "recurring"]),
89
+ recurring: stripePriceRecurringSchema.nullable(),
90
+ nickname: z.string().nullable(),
91
+ lookupKey: z.string().nullable(),
92
+ metadata: z.record(z.string(), z.string()),
93
+ });
94
+
95
+ const stripeEnvironmentMappingSchema = z.object({
96
+ test: z.string(),
97
+ live: z.string(),
98
+ });
99
+
100
+ export const stripePriceMappingSchema = z.object(
101
+ Object.fromEntries(
102
+ STRIPE_PRICE_NAMES.map((key) => [key, stripeEnvironmentMappingSchema]),
103
+ ) as Record<StripePriceName, typeof stripeEnvironmentMappingSchema>,
104
+ );
105
+
106
+ export const stripeMeterMappingSchema = z.object(
107
+ Object.fromEntries(
108
+ STRIPE_METER_NAMES.map((key) => [key, stripeEnvironmentMappingSchema]),
109
+ ) as Record<StripeMeterName, typeof stripeEnvironmentMappingSchema>,
110
+ );
111
+
112
+ export const stripePricesFileSchema = z.object({
113
+ schemaVersion: z.number(),
114
+ updatedAt: z.string(),
115
+ mapping: stripePriceMappingSchema,
116
+ meters: stripeMeterMappingSchema,
117
+ prices: z.record(z.string(), stripePriceDetailSchema),
118
+ });
@@ -0,0 +1,202 @@
1
+ import { Currency } from "@prisma/client";
2
+ import { TRPCError } from "@trpc/server";
3
+ import { z } from "zod";
4
+ import { checkOrganizationPermission } from "../../src/server/api/rbac";
5
+ import {
6
+ createTRPCRouter,
7
+ protectedProcedure,
8
+ } from "../../src/server/api/trpc";
9
+ import {
10
+ type PlanTypes as PlanType,
11
+ SUBSCRIBABLE_PLANS,
12
+ } from "./planTypes";
13
+ import { billingErrorHandler } from "./middleware";
14
+ import type { CustomerService } from "./services/customerService";
15
+ import type { SubscriptionService } from "../../src/server/app-layer/subscription/subscription.service";
16
+
17
+ const subscriptionPlanEnum = z.enum(SUBSCRIBABLE_PLANS);
18
+
19
+ export const createSubscriptionRouterFactory = ({
20
+ customerService,
21
+ subscriptionService,
22
+ }: {
23
+ customerService: CustomerService;
24
+ subscriptionService: SubscriptionService;
25
+ }) => {
26
+ return createTRPCRouter({
27
+ addTeamMemberOrEvents: protectedProcedure
28
+ .input(
29
+ z.object({
30
+ organizationId: z.string(),
31
+ plan: subscriptionPlanEnum,
32
+ upgradeMembers: z.boolean(),
33
+ upgradeTraces: z.boolean(),
34
+ totalMembers: z.number(),
35
+ totalTraces: z.number(),
36
+ }),
37
+ )
38
+ .use(checkOrganizationPermission("organization:manage"))
39
+ .use(billingErrorHandler)
40
+ .mutation(async ({ input }) => {
41
+ return await subscriptionService.updateSubscriptionItems({
42
+ organizationId: input.organizationId,
43
+ plan: input.plan as PlanType,
44
+ upgradeMembers: input.upgradeMembers,
45
+ upgradeTraces: input.upgradeTraces,
46
+ totalMembers: input.totalMembers,
47
+ totalTraces: input.totalTraces,
48
+ });
49
+ }),
50
+
51
+ create: protectedProcedure
52
+ .input(
53
+ z.object({
54
+ organizationId: z.string(),
55
+ baseUrl: z.string(),
56
+ plan: subscriptionPlanEnum,
57
+ membersToAdd: z.number().optional(),
58
+ tracesToAdd: z.number().optional(),
59
+ currency: z.nativeEnum(Currency).optional(),
60
+ billingInterval: z.enum(["monthly", "annual"]).optional(),
61
+ }),
62
+ )
63
+ .use(checkOrganizationPermission("organization:manage"))
64
+ .use(billingErrorHandler)
65
+ .mutation(async ({ input, ctx }) => {
66
+ const customerId = await customerService.getOrCreateCustomerId({
67
+ user: ctx.session.user,
68
+ organizationId: input.organizationId,
69
+ });
70
+
71
+ return await subscriptionService.createOrUpdateSubscription({
72
+ organizationId: input.organizationId,
73
+ baseUrl: input.baseUrl,
74
+ plan: input.plan as PlanType,
75
+ membersToAdd: input.membersToAdd,
76
+ tracesToAdd: input.tracesToAdd,
77
+ customerId,
78
+ currency: input.currency,
79
+ billingInterval: input.billingInterval,
80
+ });
81
+ }),
82
+
83
+ manage: protectedProcedure
84
+ .input(z.object({ organizationId: z.string(), baseUrl: z.string() }))
85
+ .use(checkOrganizationPermission("organization:manage"))
86
+ .use(billingErrorHandler)
87
+ .mutation(async ({ input, ctx }) => {
88
+ const customerId = await customerService.getOrCreateCustomerId({
89
+ user: ctx.session.user,
90
+ organizationId: input.organizationId,
91
+ });
92
+
93
+ return await subscriptionService.createBillingPortalSession({
94
+ customerId,
95
+ baseUrl: input.baseUrl,
96
+ organizationId: input.organizationId,
97
+ });
98
+ }),
99
+
100
+ previewProration: protectedProcedure
101
+ .input(
102
+ z.object({
103
+ organizationId: z.string(),
104
+ newTotalSeats: z.number().min(1),
105
+ }),
106
+ )
107
+ .use(checkOrganizationPermission("organization:manage"))
108
+ .use(billingErrorHandler)
109
+ .query(async ({ input }) => {
110
+ return await subscriptionService.previewProration({
111
+ organizationId: input.organizationId,
112
+ newTotalSeats: input.newTotalSeats,
113
+ });
114
+ }),
115
+
116
+ getLastSubscription: protectedProcedure
117
+ .input(z.object({ organizationId: z.string() }))
118
+ .use(checkOrganizationPermission("organization:view"))
119
+ .use(billingErrorHandler)
120
+ .query(async ({ input }) => {
121
+ return await subscriptionService.getLastNonCancelledSubscription(
122
+ input.organizationId,
123
+ );
124
+ }),
125
+
126
+ upgradeWithInvites: protectedProcedure
127
+ .input(
128
+ z.object({
129
+ organizationId: z.string(),
130
+ baseUrl: z.string(),
131
+ currency: z.nativeEnum(Currency).optional(),
132
+ billingInterval: z.enum(["monthly", "annual"]).optional(),
133
+ totalSeats: z.number().min(1),
134
+ invites: z.array(
135
+ z.object({
136
+ email: z.string().email(),
137
+ role: z.enum(["ADMIN", "MEMBER", "EXTERNAL"]),
138
+ }),
139
+ ),
140
+ }),
141
+ )
142
+ .use(checkOrganizationPermission("organization:manage"))
143
+ .use(billingErrorHandler)
144
+ .mutation(async ({ input, ctx }) => {
145
+ const customerId = await customerService.getOrCreateCustomerId({
146
+ user: ctx.session.user,
147
+ organizationId: input.organizationId,
148
+ });
149
+
150
+ return await subscriptionService.createSubscriptionWithInvites({
151
+ organizationId: input.organizationId,
152
+ baseUrl: input.baseUrl,
153
+ membersToAdd: input.totalSeats,
154
+ customerId,
155
+ currency: input.currency,
156
+ billingInterval: input.billingInterval,
157
+ invites: input.invites,
158
+ });
159
+ }),
160
+
161
+ prospective: protectedProcedure
162
+ .input(
163
+ z.object({
164
+ organizationId: z.string(),
165
+ plan: subscriptionPlanEnum,
166
+ customerName: z.string().optional(),
167
+ customerEmail: z.string().email().optional(),
168
+ note: z.string().optional(),
169
+ }),
170
+ )
171
+ .use(checkOrganizationPermission("organization:manage"))
172
+ .use(billingErrorHandler)
173
+ .mutation(async ({ input, ctx }) => {
174
+ const actorEmail = ctx.session.user.email;
175
+ if (!actorEmail) {
176
+ throw new TRPCError({
177
+ code: "UNAUTHORIZED",
178
+ message: "User email is required to trigger notifications",
179
+ });
180
+ }
181
+
182
+ return await subscriptionService.notifyProspective({
183
+ organizationId: input.organizationId,
184
+ plan: input.plan as PlanType,
185
+ customerName: input.customerName,
186
+ customerEmail: input.customerEmail,
187
+ note: input.note,
188
+ actorEmail,
189
+ });
190
+ }),
191
+
192
+ listInvoices: protectedProcedure
193
+ .input(z.object({ organizationId: z.string() }))
194
+ .use(checkOrganizationPermission("organization:view"))
195
+ .use(billingErrorHandler)
196
+ .query(async ({ input }) => {
197
+ return await subscriptionService.listInvoices({
198
+ organizationId: input.organizationId,
199
+ });
200
+ }),
201
+ });
202
+ };
@@ -0,0 +1,102 @@
1
+ import type { z } from "zod";
2
+ import type { PlanInfo } from "../licensing/planInfo";
3
+ import type { LimitType } from "../../src/server/license-enforcement/types";
4
+ import type { PlanTypes } from "./planTypes";
5
+ import type { signUpDataSchema } from "../../src/server/schemas/sign-up-data.schema";
6
+
7
+ export type BillingPlanProvider = {
8
+ getActivePlan(
9
+ organizationId: string,
10
+ user?: {
11
+ id?: string;
12
+ email?: string | null;
13
+ name?: string | null;
14
+ impersonator?: {
15
+ email?: string | null;
16
+ };
17
+ },
18
+ ): Promise<PlanInfo>;
19
+ };
20
+
21
+ export type PlanLimitNotifierInput = {
22
+ organizationId: string;
23
+ planName: string;
24
+ };
25
+
26
+ export type PlanLimitNotificationContext = {
27
+ organizationId: string;
28
+ organizationName: string;
29
+ adminName?: string;
30
+ adminEmail?: string;
31
+ planName: string;
32
+ };
33
+
34
+ type SubscriptionPlan = PlanTypes | (string & {});
35
+
36
+ type SubscriptionNotificationBase = {
37
+ organizationId: string;
38
+ organizationName: string;
39
+ plan: SubscriptionPlan;
40
+ };
41
+
42
+ type ProspectiveSubscriptionNotification = SubscriptionNotificationBase & {
43
+ type: "prospective";
44
+ customerName?: string;
45
+ customerEmail?: string;
46
+ note?: string;
47
+ actorEmail?: string;
48
+ };
49
+
50
+ type ConfirmedSubscriptionNotification = SubscriptionNotificationBase & {
51
+ type: "confirmed";
52
+ subscriptionId: string;
53
+ startDate?: Date | null;
54
+ maxMembers?: number | null;
55
+ maxMessagesPerMonth?: number | null;
56
+ };
57
+
58
+ type CancelledSubscriptionNotification = SubscriptionNotificationBase & {
59
+ type: "cancelled";
60
+ subscriptionId: string;
61
+ cancellationDate?: Date | null;
62
+ };
63
+
64
+ export type SubscriptionNotificationPayload =
65
+ | ProspectiveSubscriptionNotification
66
+ | ConfirmedSubscriptionNotification
67
+ | CancelledSubscriptionNotification;
68
+
69
+ export type ResourceLimitNotificationContext = {
70
+ organizationId: string;
71
+ organizationName: string;
72
+ adminName?: string;
73
+ adminEmail?: string;
74
+ planName: string;
75
+ limitType: string;
76
+ current: number;
77
+ max: number;
78
+ };
79
+
80
+ export type ResourceLimitNotifierInput = {
81
+ organizationId: string;
82
+ limitType: LimitType;
83
+ current: number;
84
+ max: number;
85
+ };
86
+
87
+ export type LicensePurchaseNotificationPayload = {
88
+ buyerEmail: string;
89
+ planType: string;
90
+ seats: number;
91
+ amountPaid: number;
92
+ currency: string;
93
+ };
94
+
95
+ export type SignupNotificationPayload = {
96
+ userName?: string | null;
97
+ userEmail?: string | null;
98
+ organizationName?: string | null;
99
+ phoneNumber?: string | null;
100
+ utmCampaign?: string | null;
101
+ signUpData?: z.infer<typeof signUpDataSchema> | null;
102
+ };
@@ -0,0 +1,99 @@
1
+ import { Currency } from "@prisma/client";
2
+ import type { NextApiRequest } from "~/types/next-stubs";
3
+ // @ts-ignore — no type definitions for geoip-country
4
+ import geoip from "geoip-country";
5
+
6
+ const DEFAULT_CURRENCY = Currency.EUR;
7
+
8
+ export const EUR_COUNTRIES = new Set([
9
+ "AT", "BE", "CY", "EE", "FI", "FR", "DE", "GR", "IE", "IT",
10
+ "LV", "LT", "LU", "MT", "NL", "PT", "SK", "SI", "ES",
11
+ "HR", "BG", "AD", "MC", "SM", "VA", "ME", "XK",
12
+ ]);
13
+
14
+ export const getCurrencyFromCountry = (countryCode: string | null | undefined): Currency => {
15
+ if (!countryCode) return DEFAULT_CURRENCY;
16
+ return EUR_COUNTRIES.has(countryCode.toUpperCase()) ? Currency.EUR : Currency.USD;
17
+ };
18
+
19
+ /**
20
+ * Extract client IP from request headers.
21
+ * Tries CDN/proxy headers in order of preference: CF, real-ip, forwarded-for.
22
+ */
23
+ const getClientIp = (req: NextApiRequest | undefined): string | null => {
24
+ if (!req?.headers) return null;
25
+
26
+ const cfIp = req.headers["cf-connecting-ip"];
27
+ if (cfIp) return Array.isArray(cfIp) ? (cfIp[0] ?? null) : cfIp;
28
+
29
+ const realIp = req.headers["x-real-ip"];
30
+ if (realIp) return Array.isArray(realIp) ? (realIp[0] ?? null) : realIp;
31
+
32
+ const forwarded = req.headers["x-forwarded-for"];
33
+ if (forwarded) {
34
+ const first = Array.isArray(forwarded) ? (forwarded[0] ?? null) : forwarded;
35
+ if (!first) return null;
36
+ return first.split(",")[0]?.trim() ?? null;
37
+ }
38
+
39
+ return null;
40
+ };
41
+
42
+ const is172Private = (ip: string): boolean => {
43
+ const parts = ip.split(".");
44
+ if (parts[0] !== "172") return false;
45
+ const second = parseInt(parts[1] ?? "", 10);
46
+ return second >= 16 && second <= 31;
47
+ };
48
+
49
+ const isLocalIp = (ip: string): boolean =>
50
+ ip === "127.0.0.1" ||
51
+ ip === "::1" ||
52
+ ip.startsWith("192.168.") ||
53
+ ip.startsWith("10.") ||
54
+ is172Private(ip) ||
55
+ ip.includes("127.0.0.1"); // IPv6-mapped loopback (::ffff:127.0.0.1)
56
+
57
+ /**
58
+ * Detect currency from a request using: CDN headers → geoip lookup → fallback.
59
+ *
60
+ * Resolution order:
61
+ * 1. CDN-injected country headers (x-vercel-ip-country, cf-ipcountry)
62
+ * 2. geoip-country lookup from client IP
63
+ * 3. DEFAULT_CURRENCY fallback
64
+ */
65
+ export const detectCurrencyFromRequest = (
66
+ req: NextApiRequest | undefined,
67
+ ): { currency: Currency; country: string | null } => {
68
+ // 1. Try CDN-injected country headers
69
+ const vercelCountry = req?.headers?.["x-vercel-ip-country"];
70
+ const cfCountry = req?.headers?.["cf-ipcountry"];
71
+ const headerCountry = (
72
+ typeof vercelCountry === "string" ? vercelCountry :
73
+ typeof cfCountry === "string" ? cfCountry :
74
+ null
75
+ );
76
+
77
+ if (headerCountry) {
78
+ return { currency: getCurrencyFromCountry(headerCountry), country: headerCountry };
79
+ }
80
+
81
+ // 2. Try geoip lookup from client IP
82
+ const ip = getClientIp(req);
83
+
84
+ if (!ip || isLocalIp(ip)) {
85
+ return { currency: DEFAULT_CURRENCY, country: null };
86
+ }
87
+
88
+ try {
89
+ const geo = geoip.lookup(ip);
90
+ if (geo?.country) {
91
+ return { currency: getCurrencyFromCountry(geo.country), country: geo.country };
92
+ }
93
+ } catch {
94
+ // geoip lookup failed, fall through to default
95
+ }
96
+
97
+ // 3. Fallback
98
+ return { currency: DEFAULT_CURRENCY, country: null };
99
+ };