raiton 6.8.9-beta.25 → 6.11.0-beta.29

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 (439) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +65 -1
  3. package/benchmarks/README.md +31 -0
  4. package/benchmarks/ai-debug.json +145 -0
  5. package/benchmarks/ai-debug.md +64 -0
  6. package/benchmarks/latest.json +172 -0
  7. package/benchmarks/latest.md +66 -0
  8. package/build/bin/index.mjs +37621 -21866
  9. package/build/types/bin/bootstrapper.d.ts +2 -0
  10. package/build/types/bin/cli-output.d.ts +46 -0
  11. package/build/types/bin/cli-tools.d.ts +13 -0
  12. package/build/types/bin/cli.d.ts +3 -0
  13. package/build/types/bin/commands.registry.d.ts +4 -0
  14. package/build/types/bin/constants.d.ts +3 -0
  15. package/build/types/bin/file-utils.d.ts +21 -0
  16. package/build/types/bin/index.d.ts +2 -0
  17. package/build/types/bin/name-utils.d.ts +4 -0
  18. package/build/types/bin/project-utils.d.ts +12 -0
  19. package/build/types/commands/artifact.command.d.ts +7 -0
  20. package/build/types/commands/build.command.d.ts +8 -0
  21. package/build/types/commands/call.command.d.ts +10 -0
  22. package/build/types/commands/client.command.d.ts +7 -0
  23. package/build/types/commands/contract.command.d.ts +8 -0
  24. package/build/types/commands/debug.shared.d.ts +16 -0
  25. package/build/types/commands/develop.command.d.ts +9 -0
  26. package/build/types/commands/docs.command.d.ts +8 -0
  27. package/build/types/commands/doctor.command.d.ts +9 -0
  28. package/build/types/commands/explain.command.d.ts +8 -0
  29. package/build/types/commands/generate.command.d.ts +7 -0
  30. package/build/types/commands/inspect.command.d.ts +7 -0
  31. package/build/types/commands/mcp.command.d.ts +12 -0
  32. package/build/types/commands/new.command.d.ts +7 -0
  33. package/build/types/commands/openapi.command.d.ts +7 -0
  34. package/build/types/commands/requests.command.d.ts +8 -0
  35. package/build/types/commands/routes.command.d.ts +7 -0
  36. package/build/types/commands/start.command.d.ts +9 -0
  37. package/build/types/commands/verify.command.d.ts +8 -0
  38. package/build/types/commands/why.command.d.ts +7 -0
  39. package/build/types/contracts/decorators.d.ts +59 -0
  40. package/build/types/contracts/errors.d.ts +68 -0
  41. package/build/types/contracts/index.d.ts +4 -0
  42. package/build/types/contracts/schema.d.ts +83 -0
  43. package/build/types/contracts/typebox.d.ts +81 -0
  44. package/build/types/core/application.d.ts +45 -0
  45. package/build/types/core/artifacts/artifact.d.ts +3 -0
  46. package/build/types/core/artifacts/index.d.ts +1 -0
  47. package/build/types/core/artifacts/runner.d.ts +1 -0
  48. package/build/types/core/builder.d.ts +42 -0
  49. package/build/types/core/bytes.util.d.ts +3 -0
  50. package/build/types/core/command.d.ts +13 -0
  51. package/build/types/core/commands.d.ts +10 -0
  52. package/build/types/core/config/config.d.ts +27 -0
  53. package/build/types/core/config/define.d.ts +8 -0
  54. package/build/types/core/config/index.d.ts +3 -0
  55. package/build/types/core/config/schema.d.ts +24 -0
  56. package/build/types/core/context.d.ts +11 -0
  57. package/build/types/core/controller/builder.d.ts +26 -0
  58. package/build/types/core/controller/compiler.d.ts +2 -0
  59. package/build/types/core/controller/index.d.ts +4 -0
  60. package/build/types/core/controller/metadata.d.ts +3 -0
  61. package/build/types/core/controller/tracker.d.ts +9 -0
  62. package/build/types/core/directories.d.ts +10 -0
  63. package/build/types/core/guards.d.ts +11 -0
  64. package/build/types/core/helpers/index.d.ts +1 -0
  65. package/build/types/core/helpers/raiton.d.ts +1 -0
  66. package/build/types/core/hooks.d.ts +14 -0
  67. package/build/types/core/index.d.ts +17 -0
  68. package/build/types/core/injection/index.d.ts +1 -0
  69. package/build/types/core/injection/injection.d.ts +37 -0
  70. package/build/types/core/mcp/builder.d.ts +2 -0
  71. package/build/types/core/mcp/index.d.ts +3 -0
  72. package/build/types/core/mcp/metadata.d.ts +9 -0
  73. package/build/types/core/mcp/tracker.d.ts +9 -0
  74. package/build/types/core/middleware/compose.d.ts +8 -0
  75. package/build/types/core/middleware/index.d.ts +2 -0
  76. package/build/types/core/middleware/pipeline.d.ts +12 -0
  77. package/build/types/core/plugins/index.d.ts +2 -0
  78. package/build/types/core/plugins/plugin.d.ts +2 -0
  79. package/build/types/core/plugins/scope.d.ts +15 -0
  80. package/build/types/core/process.util.d.ts +1 -0
  81. package/build/types/core/raiton.d.ts +15 -0
  82. package/build/types/core/router/handler.d.ts +2 -0
  83. package/build/types/core/router/handler.utils.d.ts +37 -0
  84. package/build/types/core/router/index.d.ts +4 -0
  85. package/build/types/core/router/matcher.d.ts +50 -0
  86. package/build/types/core/router/route.d.ts +52 -0
  87. package/build/types/core/router/router.d.ts +23 -0
  88. package/build/types/core/scheduler/builder.d.ts +2 -0
  89. package/build/types/core/scheduler/cron.d.ts +32 -0
  90. package/build/types/core/scheduler/duration.d.ts +7 -0
  91. package/build/types/core/scheduler/index.d.ts +6 -0
  92. package/build/types/core/scheduler/manager.d.ts +47 -0
  93. package/build/types/core/scheduler/metadata.d.ts +8 -0
  94. package/build/types/core/scheduler/queue/backend.d.ts +42 -0
  95. package/build/types/core/scheduler/queue/index.d.ts +3 -0
  96. package/build/types/core/scheduler/queue/rabbitmq.backend.d.ts +37 -0
  97. package/build/types/core/scheduler/queue/redis.backend.d.ts +38 -0
  98. package/build/types/core/server.d.ts +9 -0
  99. package/build/types/core/socket/builder.d.ts +1 -0
  100. package/build/types/core/socket/index.d.ts +2 -0
  101. package/build/types/core/socket/metadata.d.ts +14 -0
  102. package/build/types/core/thread.d.ts +21 -0
  103. package/build/types/debug/cli.d.ts +33 -0
  104. package/build/types/debug/collector.d.ts +41 -0
  105. package/build/types/debug/collector.internal.d.ts +27 -0
  106. package/build/types/debug/config.d.ts +19 -0
  107. package/build/types/debug/examples.d.ts +43 -0
  108. package/build/types/debug/explain.d.ts +9 -0
  109. package/build/types/debug/index.d.ts +15 -0
  110. package/build/types/debug/invocation.d.ts +53 -0
  111. package/build/types/debug/journal.d.ts +49 -0
  112. package/build/types/debug/mcp-http.d.ts +17 -0
  113. package/build/types/debug/mcp.d.ts +14 -0
  114. package/build/types/debug/redaction.d.ts +48 -0
  115. package/build/types/debug/requests.d.ts +37 -0
  116. package/build/types/debug/runtime.d.ts +52 -0
  117. package/build/types/debug/session.d.ts +21 -0
  118. package/build/types/debug/source.d.ts +17 -0
  119. package/build/types/debug/surface.d.ts +10 -0
  120. package/build/types/debug/types.d.ts +271 -0
  121. package/build/types/debug/verify.d.ts +23 -0
  122. package/build/types/framework/artifacts.d.ts +20 -0
  123. package/build/types/framework/cache/cache.d.ts +84 -0
  124. package/build/types/framework/cache/cache.decorator.d.ts +21 -0
  125. package/build/types/framework/cache/etag.d.ts +62 -0
  126. package/build/types/framework/cache/index.d.ts +4 -0
  127. package/build/types/framework/cache/types.d.ts +89 -0
  128. package/build/types/framework/constants/decorators.constant.d.ts +28 -0
  129. package/build/types/framework/constants/index.d.ts +2 -0
  130. package/build/types/framework/constants/microservices.constant.d.ts +3 -0
  131. package/build/types/framework/controllers.d.ts +2 -0
  132. package/build/types/framework/data-transfer-object.d.ts +5 -0
  133. package/build/types/framework/decorators/access-guard.decorator.d.ts +1 -0
  134. package/build/types/framework/decorators/api-response.decorator.d.ts +66 -0
  135. package/build/types/framework/decorators/api.decorator.d.ts +160 -0
  136. package/build/types/framework/decorators/controllable.decorator.d.ts +3 -0
  137. package/build/types/framework/decorators/csrf-guard.decorator.d.ts +2 -0
  138. package/build/types/framework/decorators/csrf-token.decorator.d.ts +1 -0
  139. package/build/types/framework/decorators/guard.decorator.d.ts +2 -0
  140. package/build/types/framework/decorators/health-check.decorator.d.ts +17 -0
  141. package/build/types/framework/decorators/index.d.ts +15 -0
  142. package/build/types/framework/decorators/injection.decorator.d.ts +5 -0
  143. package/build/types/framework/decorators/mcp.decorator.d.ts +68 -0
  144. package/build/types/framework/decorators/middleware.decorator.d.ts +3 -0
  145. package/build/types/framework/decorators/parametrable.decorator.d.ts +9 -0
  146. package/build/types/framework/decorators/routable.decorator.d.ts +12 -0
  147. package/build/types/framework/decorators/route-interaction.decorator.d.ts +81 -0
  148. package/build/types/framework/decorators/scheduler.decorator.d.ts +54 -0
  149. package/build/types/framework/decorators/socket.decorator.d.ts +5 -0
  150. package/build/types/framework/encryption.d.ts +25 -0
  151. package/build/types/framework/enums/csrf.enum.d.ts +4 -0
  152. package/build/types/framework/enums/encrypted.enum.d.ts +20 -0
  153. package/build/types/framework/enums/event.message.enum.d.ts +4 -0
  154. package/build/types/framework/enums/http-method.enum.d.ts +10 -0
  155. package/build/types/framework/enums/http-parameters.enum.d.ts +11 -0
  156. package/build/types/framework/enums/http-status.enum.d.ts +64 -0
  157. package/build/types/framework/enums/index.d.ts +9 -0
  158. package/build/types/framework/enums/runtime.enum.d.ts +5 -0
  159. package/build/types/framework/enums/scheduler.enum.d.ts +21 -0
  160. package/build/types/framework/enums/timestamp.enum.d.ts +6 -0
  161. package/build/types/framework/env.d.ts +3 -0
  162. package/build/types/framework/errors/catalog.d.ts +57 -0
  163. package/build/types/framework/exceptions/http-exception.d.ts +18 -0
  164. package/build/types/framework/exceptions/index.d.ts +2 -0
  165. package/build/types/framework/exceptions/throwable.d.ts +76 -0
  166. package/build/types/framework/health-check.d.ts +42 -0
  167. package/build/types/framework/index.d.ts +20 -0
  168. package/build/types/framework/mcp/audit.d.ts +12 -0
  169. package/build/types/framework/mcp/conformance.d.ts +31 -0
  170. package/build/types/framework/mcp/handler.d.ts +11 -0
  171. package/build/types/framework/mcp/index.d.ts +5 -0
  172. package/build/types/framework/mcp/protocol.d.ts +17 -0
  173. package/build/types/framework/mcp/rate-limit.d.ts +10 -0
  174. package/build/types/framework/mcp/stdio.d.ts +40 -0
  175. package/build/types/framework/mcp/streamable-http.d.ts +17 -0
  176. package/build/types/framework/observability/index.d.ts +6 -0
  177. package/build/types/framework/observability/metrics.d.ts +23 -0
  178. package/build/types/framework/observability/plugin.d.ts +20 -0
  179. package/build/types/framework/observability/readiness.d.ts +9 -0
  180. package/build/types/framework/observability/request.d.ts +7 -0
  181. package/build/types/framework/observability/shutdown.d.ts +21 -0
  182. package/build/types/framework/observability/trace.d.ts +96 -0
  183. package/build/types/framework/parameter-bag.d.ts +14 -0
  184. package/build/types/framework/plugins/body-parser.plugin.d.ts +3 -0
  185. package/build/types/framework/plugins/dev.plugin.d.ts +12 -0
  186. package/build/types/framework/plugins/index.d.ts +5 -0
  187. package/build/types/framework/plugins/mcp.plugin.d.ts +15 -0
  188. package/build/types/framework/plugins/openapi.plugin.d.ts +58 -0
  189. package/build/types/framework/plugins/security/body-limit.d.ts +1 -0
  190. package/build/types/framework/plugins/security/cors.d.ts +10 -0
  191. package/build/types/framework/plugins/security/csrf.d.ts +2 -0
  192. package/build/types/framework/plugins/security/headers.d.ts +1 -0
  193. package/build/types/framework/plugins/security/index.d.ts +13 -0
  194. package/build/types/framework/plugins/security/method-guard.d.ts +1 -0
  195. package/build/types/framework/plugins/security/rate-limit.d.ts +5 -0
  196. package/build/types/framework/repositories.d.ts +5 -0
  197. package/build/types/framework/responses/error.d.ts +13 -0
  198. package/build/types/framework/responses/helpers.d.ts +7 -0
  199. package/build/types/framework/responses/http-throwable.d.ts +14 -0
  200. package/build/types/framework/responses/http.d.ts +13 -0
  201. package/build/types/framework/responses/index.d.ts +4 -0
  202. package/build/types/framework/runtime/bun/server.d.ts +2 -0
  203. package/build/types/framework/runtime/deno/server.d.ts +2 -0
  204. package/build/types/framework/runtime/index.d.ts +17 -0
  205. package/build/types/framework/runtime/node/reply.d.ts +12 -0
  206. package/build/types/framework/runtime/node/request.d.ts +33 -0
  207. package/build/types/framework/runtime/node/server.d.ts +2 -0
  208. package/build/types/framework/runtime/web/server.d.ts +1 -0
  209. package/build/types/framework/services.d.ts +5 -0
  210. package/build/types/framework/utilities/alias-path.util.d.ts +1 -0
  211. package/build/types/framework/utilities/artifact.util.d.ts +7 -0
  212. package/build/types/framework/utilities/callable.util.d.ts +1 -0
  213. package/build/types/framework/utilities/cookie.util.d.ts +1 -0
  214. package/build/types/framework/utilities/csrf.util.d.ts +26 -0
  215. package/build/types/framework/utilities/https.util.d.ts +49 -0
  216. package/build/types/framework/utilities/index.d.ts +12 -0
  217. package/build/types/framework/utilities/ip.util.d.ts +15 -0
  218. package/build/types/framework/utilities/json.util.d.ts +10 -0
  219. package/build/types/framework/utilities/openapi.utils.d.ts +7 -0
  220. package/build/types/framework/utilities/openapi.utils.impl.d.ts +18 -0
  221. package/build/types/framework/utilities/path.util.d.ts +3 -0
  222. package/build/types/framework/utilities/route-suggestion.util.d.ts +10 -0
  223. package/build/types/framework/utilities/url.util.d.ts +1 -0
  224. package/build/types/framework/utilities/utilities.util.d.ts +3 -0
  225. package/build/types/framework/utilities/validation.util.d.ts +8 -0
  226. package/build/types/framework/view-model.d.ts +4 -0
  227. package/build/types/generators/artifact.templates.d.ts +7 -0
  228. package/build/types/generators/index.d.ts +2 -0
  229. package/build/types/generators/project.templates.d.ts +21 -0
  230. package/build/types/manifest/client.d.ts +12 -0
  231. package/build/types/manifest/contract.d.ts +25 -0
  232. package/build/types/manifest/index.d.ts +5 -0
  233. package/build/types/manifest/introspect.d.ts +18 -0
  234. package/build/types/manifest/manifest.d.ts +18 -0
  235. package/build/types/manifest/schema.d.ts +241 -0
  236. package/build/types/requirements.d.ts +1 -0
  237. package/build/types/types/access-guards.d.ts +4 -0
  238. package/build/types/types/application.d.ts +32 -0
  239. package/build/types/types/artifact.d.ts +8 -0
  240. package/build/types/types/builder.d.ts +37 -0
  241. package/build/types/types/config.d.ts +112 -0
  242. package/build/types/types/controller.d.ts +27 -0
  243. package/build/types/types/contruct.d.ts +1 -0
  244. package/build/types/types/core.d.ts +11 -0
  245. package/build/types/types/csrf.d.ts +33 -0
  246. package/build/types/types/directory.d.ts +6 -0
  247. package/build/types/types/encryption.d.ts +14 -0
  248. package/build/types/types/generic.d.ts +2 -0
  249. package/build/types/types/guard.d.ts +9 -0
  250. package/build/types/types/http-responses.d.ts +7 -0
  251. package/build/types/types/index.d.ts +27 -0
  252. package/build/types/types/injection.d.ts +11 -0
  253. package/build/types/types/lifecycle.d.ts +9 -0
  254. package/build/types/types/mcp.d.ts +148 -0
  255. package/build/types/types/middleware.d.ts +12 -0
  256. package/build/types/types/parseable.d.ts +3 -0
  257. package/build/types/types/plugin.d.ts +6 -0
  258. package/build/types/types/raiton.d.ts +13 -0
  259. package/build/types/types/responses.d.ts +20 -0
  260. package/build/types/types/router.d.ts +13 -0
  261. package/build/types/types/runtime.d.ts +48 -0
  262. package/build/types/types/scheduler.d.ts +140 -0
  263. package/build/types/types/scheme.d.ts +125 -0
  264. package/build/types/types/server.d.ts +10 -0
  265. package/build/types/types/socket.d.ts +11 -0
  266. package/build/types/types/thread.d.ts +25 -0
  267. package/build/types/types/utilities.d.ts +4 -0
  268. package/build/types/types/values.d.ts +2 -0
  269. package/docs/AGENTS.md +55 -0
  270. package/docs/CLAUDE.md +55 -0
  271. package/docs/README.md +5 -0
  272. package/docs/contributors/cli/README.md +17 -3
  273. package/docs/contributors/cli/commands.md +28 -17
  274. package/docs/contributors/framework/plugins/openapi.md +12 -3
  275. package/docs/generated/cli/commands.md +31 -0
  276. package/docs/generated/config-schema.json +243 -0
  277. package/docs/generated/manifest-schema.json +312 -0
  278. package/docs/generated/manifest.json +118 -0
  279. package/docs/llms-full.txt +1450 -0
  280. package/docs/llms.txt +51 -0
  281. package/docs/user-guide/README.md +19 -12
  282. package/docs/user-guide/cli.md +26 -0
  283. package/docs/user-guide/config.md +32 -0
  284. package/docs/user-guide/contracts.md +67 -0
  285. package/docs/user-guide/debug.md +130 -0
  286. package/docs/user-guide/en/README.md +83 -0
  287. package/docs/user-guide/getting-started.md +13 -1
  288. package/docs/user-guide/mcp.md +45 -2
  289. package/docs/user-guide/observability.md +74 -0
  290. package/docs/user-guide/openapi/plugin.md +10 -0
  291. package/docs/user-guide/recipes/README.md +32 -0
  292. package/docs/user-guide/recipes/contracts.md +52 -0
  293. package/docs/user-guide/recipes/doctor.md +16 -0
  294. package/docs/user-guide/recipes/generate.md +28 -0
  295. package/docs/user-guide/recipes/manifest.md +17 -0
  296. package/docs/user-guide/recipes/mcp-stdio.md +35 -0
  297. package/docs/user-guide/recipes/new-project.md +34 -0
  298. package/docs/user-guide/recipes/observability.md +17 -0
  299. package/package.json +42 -7
  300. package/scripts/bench-ai-debug.ts +572 -0
  301. package/scripts/bench.ts +586 -0
  302. package/scripts/postinstall.mjs +15 -0
  303. package/source/bin/cli-output.ts +139 -0
  304. package/source/bin/commands.registry.ts +31 -3
  305. package/source/bin/file-utils.ts +95 -0
  306. package/source/bin/name-utils.ts +26 -0
  307. package/source/bin/project-utils.ts +78 -0
  308. package/source/commands/artifact.command.ts +30 -15
  309. package/source/commands/call.command.ts +247 -0
  310. package/source/commands/client.command.ts +64 -0
  311. package/source/commands/contract.command.ts +104 -0
  312. package/source/commands/debug.shared.ts +90 -0
  313. package/source/commands/docs.command.ts +269 -0
  314. package/source/commands/doctor.command.ts +226 -0
  315. package/source/commands/explain.command.ts +119 -0
  316. package/source/commands/generate.command.ts +58 -0
  317. package/source/commands/inspect.command.ts +108 -0
  318. package/source/commands/mcp.command.ts +322 -0
  319. package/source/commands/new.command.ts +135 -0
  320. package/source/commands/openapi.command.ts +95 -0
  321. package/source/commands/requests.command.ts +137 -0
  322. package/source/commands/routes.command.ts +39 -0
  323. package/source/commands/verify.command.ts +173 -0
  324. package/source/commands/why.command.ts +61 -0
  325. package/source/contracts/decorators.ts +216 -0
  326. package/source/contracts/errors.ts +135 -0
  327. package/source/contracts/index.ts +4 -0
  328. package/source/contracts/schema.ts +438 -0
  329. package/source/contracts/typebox.ts +193 -0
  330. package/source/core/application.ts +322 -72
  331. package/source/core/builder.ts +10 -2
  332. package/source/core/config/config.ts +155 -26
  333. package/source/core/config/define.ts +35 -8
  334. package/source/core/config/index.ts +2 -1
  335. package/source/core/config/schema.ts +406 -0
  336. package/source/core/controller/builder.ts +38 -13
  337. package/source/core/controller/compiler.ts +14 -7
  338. package/source/core/controller/metadata.ts +1 -1
  339. package/source/core/hooks.ts +13 -1
  340. package/source/core/injection/injection.ts +47 -9
  341. package/source/core/mcp/builder.ts +13 -2
  342. package/source/core/mcp/metadata.ts +2 -1
  343. package/source/core/middleware/compose.ts +48 -0
  344. package/source/core/middleware/pipeline.ts +69 -46
  345. package/source/core/raiton.ts +8 -0
  346. package/source/core/router/handler.ts +246 -37
  347. package/source/core/router/handler.utils.ts +107 -51
  348. package/source/core/router/matcher.ts +195 -24
  349. package/source/core/router/route.ts +100 -31
  350. package/source/core/router/router.ts +27 -2
  351. package/source/core/scheduler/metadata.ts +1 -1
  352. package/source/core/socket/metadata.ts +1 -1
  353. package/source/core/thread.ts +37 -2
  354. package/source/debug/cli.ts +206 -0
  355. package/source/debug/collector.internal.ts +27 -0
  356. package/source/debug/collector.ts +294 -0
  357. package/source/debug/config.ts +142 -0
  358. package/source/debug/examples.ts +188 -0
  359. package/source/debug/explain.ts +187 -0
  360. package/source/debug/index.ts +15 -0
  361. package/source/debug/invocation.ts +695 -0
  362. package/source/debug/journal.ts +249 -0
  363. package/source/debug/mcp-http.ts +145 -0
  364. package/source/debug/mcp.ts +410 -0
  365. package/source/debug/redaction.ts +225 -0
  366. package/source/debug/requests.ts +136 -0
  367. package/source/debug/runtime.ts +181 -0
  368. package/source/debug/session.ts +107 -0
  369. package/source/debug/source.ts +95 -0
  370. package/source/debug/surface.ts +375 -0
  371. package/source/debug/types.ts +311 -0
  372. package/source/debug/verify.ts +186 -0
  373. package/source/framework/artifacts.ts +47 -15
  374. package/source/framework/cache/cache.ts +48 -3
  375. package/source/framework/constants/decorators.constant.ts +5 -0
  376. package/source/framework/data-transfer-object.ts +4 -3
  377. package/source/framework/decorators/controllable.decorator.ts +3 -3
  378. package/source/framework/decorators/csrf-guard.decorator.ts +3 -2
  379. package/source/framework/decorators/csrf-token.decorator.ts +1 -1
  380. package/source/framework/decorators/guard.decorator.ts +3 -2
  381. package/source/framework/decorators/health-check.decorator.ts +1 -1
  382. package/source/framework/decorators/mcp.decorator.ts +38 -7
  383. package/source/framework/decorators/middleware.decorator.ts +2 -2
  384. package/source/framework/decorators/parametrable.decorator.ts +2 -1
  385. package/source/framework/decorators/routable.decorator.ts +3 -3
  386. package/source/framework/decorators/route-interaction.decorator.ts +2 -2
  387. package/source/framework/decorators/scheduler.decorator.ts +3 -3
  388. package/source/framework/decorators/socket.decorator.ts +3 -3
  389. package/source/framework/encryption.ts +46 -7
  390. package/source/framework/errors/catalog.ts +205 -0
  391. package/source/framework/exceptions/http-exception.ts +1 -1
  392. package/source/framework/health-check.ts +18 -0
  393. package/source/framework/index.ts +2 -0
  394. package/source/framework/mcp/audit.ts +57 -0
  395. package/source/framework/mcp/conformance.ts +195 -0
  396. package/source/framework/mcp/handler.ts +139 -9
  397. package/source/framework/mcp/index.ts +6 -1
  398. package/source/framework/mcp/protocol.ts +6 -0
  399. package/source/framework/mcp/rate-limit.ts +33 -0
  400. package/source/framework/mcp/stdio.ts +150 -0
  401. package/source/framework/mcp/streamable-http.ts +36 -5
  402. package/source/framework/observability/index.ts +6 -0
  403. package/source/framework/observability/metrics.ts +162 -0
  404. package/source/framework/observability/plugin.ts +151 -0
  405. package/source/framework/observability/readiness.ts +22 -0
  406. package/source/framework/observability/request.ts +31 -0
  407. package/source/framework/observability/shutdown.ts +68 -0
  408. package/source/framework/observability/trace.ts +241 -0
  409. package/source/framework/plugins/body-parser.plugin.ts +88 -85
  410. package/source/framework/plugins/dev.plugin.ts +227 -0
  411. package/source/framework/plugins/index.ts +2 -1
  412. package/source/framework/plugins/mcp.plugin.ts +14 -3
  413. package/source/framework/plugins/openapi.plugin.ts +56 -13
  414. package/source/framework/responses/helpers.ts +4 -4
  415. package/source/framework/responses/http-throwable.ts +1 -1
  416. package/source/framework/runtime/bun/server.ts +2 -1
  417. package/source/framework/runtime/deno/server.ts +2 -1
  418. package/source/framework/runtime/index.ts +45 -13
  419. package/source/framework/runtime/node/request.ts +59 -13
  420. package/source/framework/utilities/index.ts +3 -1
  421. package/source/framework/utilities/openapi.utils.impl.ts +733 -0
  422. package/source/framework/utilities/openapi.utils.ts +6 -636
  423. package/source/framework/utilities/route-suggestion.util.ts +59 -0
  424. package/source/framework/utilities/validation.util.ts +20 -0
  425. package/source/generators/artifact.templates.ts +230 -0
  426. package/source/generators/index.ts +2 -0
  427. package/source/generators/project.templates.ts +392 -0
  428. package/source/manifest/client.ts +299 -0
  429. package/source/manifest/contract.ts +138 -0
  430. package/source/manifest/index.ts +5 -0
  431. package/source/manifest/introspect.ts +57 -0
  432. package/source/manifest/manifest.ts +364 -0
  433. package/source/manifest/schema.ts +200 -0
  434. package/source/types/builder.ts +5 -0
  435. package/source/types/config.ts +120 -2
  436. package/source/types/mcp.ts +63 -1
  437. package/tsconfig.build.json +13 -0
  438. package/source/commands/grafts.command.ts +0 -27
  439. package/tests/artifact-resolution.test.ts +0 -60
@@ -0,0 +1,162 @@
1
+ export interface MetricLabels {
2
+ [key: string]: string | number | boolean | undefined;
3
+ }
4
+
5
+ const DEFAULT_BUCKETS = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
6
+
7
+ function labelKey(labels?: MetricLabels): string {
8
+ if (!labels) return "";
9
+ const entries = Object.entries(labels)
10
+ .filter(([, value]) => value !== undefined)
11
+ .sort(([a], [b]) => a.localeCompare(b))
12
+ .map(([key, value]) => `${key}="${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`);
13
+ return entries.length ? `{${entries.join(",")}}` : "";
14
+ }
15
+
16
+ function metricName(name: string): string {
17
+ return name.replace(/[^a-zA-Z0-9_:]/g, "_");
18
+ }
19
+
20
+ interface CounterEntry {
21
+ name: string;
22
+ help: string;
23
+ values: Map<string, number>;
24
+ }
25
+
26
+ interface HistogramEntry {
27
+ name: string;
28
+ help: string;
29
+ buckets: number[];
30
+ values: Map<string, {counts: number[]; sum: number; count: number}>;
31
+ }
32
+
33
+ /**
34
+ * Dependency-free Prometheus registry. It is only touched when the
35
+ * `metrics` observability mode is enabled, so the hot path stays unchanged
36
+ * when observability is off.
37
+ */
38
+ export class MetricsRegistry {
39
+ private counters = new Map<string, CounterEntry>();
40
+ private histograms = new Map<string, HistogramEntry>();
41
+
42
+ counter(name: string, help = ""): this {
43
+ const key = metricName(name);
44
+ if (!this.counters.has(key)) this.counters.set(key, {name: key, help, values: new Map()});
45
+ return this;
46
+ }
47
+
48
+ increment(name: string, labels?: MetricLabels, value = 1): this {
49
+ const key = metricName(name);
50
+ let entry = this.counters.get(key);
51
+ if (!entry) {
52
+ entry = {name: key, help: `${name} counter`, values: new Map()};
53
+ this.counters.set(key, entry);
54
+ }
55
+ const labelsKey = labelKey(labels);
56
+ entry.values.set(labelsKey, (entry.values.get(labelsKey) ?? 0) + value);
57
+ return this;
58
+ }
59
+
60
+ histogram(name: string, help = "", buckets = DEFAULT_BUCKETS): this {
61
+ const key = metricName(name);
62
+ if (!this.histograms.has(key)) {
63
+ this.histograms.set(key, {
64
+ name: key,
65
+ help,
66
+ buckets: [...buckets].sort((a, b) => a - b),
67
+ values: new Map(),
68
+ });
69
+ }
70
+ return this;
71
+ }
72
+
73
+ observe(name: string, value: number, labels?: MetricLabels): this {
74
+ const key = metricName(name);
75
+ let entry = this.histograms.get(key);
76
+ if (!entry) {
77
+ entry = {
78
+ name: key,
79
+ help: `${name} histogram`,
80
+ buckets: DEFAULT_BUCKETS,
81
+ values: new Map(),
82
+ };
83
+ this.histograms.set(key, entry);
84
+ }
85
+ const labelsKey = labelKey(labels);
86
+ let bucketData = entry.values.get(labelsKey);
87
+ if (!bucketData) {
88
+ bucketData = {counts: new Array(entry.buckets.length).fill(0), sum: 0, count: 0};
89
+ entry.values.set(labelsKey, bucketData);
90
+ }
91
+ bucketData.sum += value;
92
+ bucketData.count += 1;
93
+ for (let index = 0; index < entry.buckets.length; index++) {
94
+ if (value <= entry.buckets[index]) bucketData.counts[index] += 1;
95
+ }
96
+ return this;
97
+ }
98
+
99
+ reset(): void {
100
+ this.counters.clear();
101
+ this.histograms.clear();
102
+ }
103
+
104
+ snapshot(): Record<string, any> {
105
+ return {
106
+ counters: Object.fromEntries([...this.counters].map(([name, entry]) => [
107
+ name,
108
+ Object.fromEntries(entry.values),
109
+ ])),
110
+ histograms: Object.fromEntries([...this.histograms].map(([name, entry]) => [
111
+ name,
112
+ {
113
+ buckets: entry.buckets,
114
+ values: Object.fromEntries([...entry.values].map(([labels, value]) => [labels, {
115
+ count: value.count,
116
+ sum: value.sum,
117
+ }])),
118
+ },
119
+ ])),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Prometheus text exposition format (version 0.0.4).
125
+ */
126
+ render(): string {
127
+ const lines: string[] = [];
128
+
129
+ for (const entry of this.counters.values()) {
130
+ if (entry.help) lines.push(`# HELP ${entry.name} ${entry.help}`);
131
+ lines.push(`# TYPE ${entry.name} counter`);
132
+ if (entry.values.size === 0) lines.push(`${entry.name} 0`);
133
+ for (const [labels, value] of entry.values) {
134
+ lines.push(`${entry.name}${labels} ${value}`);
135
+ }
136
+ }
137
+
138
+ for (const entry of this.histograms.values()) {
139
+ if (entry.help) lines.push(`# HELP ${entry.name} ${entry.help}`);
140
+ lines.push(`# TYPE ${entry.name} histogram`);
141
+ for (const [labels, data] of entry.values) {
142
+ for (let index = 0; index < entry.buckets.length; index++) {
143
+ const bucketLabels = labelKeyWithExtra(labels, `le="${entry.buckets[index]}"`);
144
+ lines.push(`${entry.name}_bucket${bucketLabels} ${data.counts[index]}`);
145
+ }
146
+ const infLabels = labelKeyWithExtra(labels, 'le="+Inf"');
147
+ lines.push(`${entry.name}_bucket${infLabels} ${data.count}`);
148
+ lines.push(`${entry.name}_sum${labels} ${data.sum}`);
149
+ lines.push(`${entry.name}_count${labels} ${data.count}`);
150
+ }
151
+ }
152
+
153
+ return lines.join("\n") + (lines.length ? "\n" : "");
154
+ }
155
+ }
156
+
157
+ function labelKeyWithExtra(labels: string, extra: string): string {
158
+ if (!labels) return `{${extra}}`;
159
+ return `{${labels.slice(1, -1)},${extra}}`;
160
+ }
161
+
162
+ export const metrics = new MetricsRegistry();
@@ -0,0 +1,151 @@
1
+ import type {PluginInterface} from "../../types/plugin.ts";
2
+ import type {ContextInterface} from "../../types/core.ts";
3
+ import type {PluginScope} from "../../core/plugins/scope.ts";
4
+ import {Logger} from "@protorians/logger";
5
+ import {metrics} from "./metrics.ts";
6
+ import {configureTraceExporter, parseTraceparent, traceparent, withSpan} from "./trace.ts";
7
+ import {readHeader, resolveRequestId} from "./request.ts";
8
+ import type {ObservabilityMode} from "../../types/config.ts";
9
+
10
+ export interface ObservabilityOptions {
11
+ mode?: ObservabilityMode;
12
+ metricsPath?: string;
13
+ otelEndpoint?: string;
14
+ requestIdHeader?: string;
15
+ serviceName?: string;
16
+ }
17
+
18
+ interface ResolvedOptions {
19
+ mode: ObservabilityMode;
20
+ metricsPath: string;
21
+ otelEndpoint: string;
22
+ requestIdHeader: string;
23
+ serviceName: string;
24
+ }
25
+
26
+ function resolveOptions(options: ObservabilityOptions): ResolvedOptions {
27
+ const mode = options.mode ?? "off";
28
+ return {
29
+ mode,
30
+ metricsPath: options.metricsPath || "/metrics",
31
+ otelEndpoint: options.otelEndpoint || "",
32
+ requestIdHeader: options.requestIdHeader || "x-request-id",
33
+ serviceName: options.serviceName || "raiton",
34
+ };
35
+ }
36
+
37
+ function shouldUseMetrics(mode: ObservabilityMode): boolean {
38
+ return mode === "metrics" || mode === "all";
39
+ }
40
+
41
+ function shouldUseTraces(mode: ObservabilityMode): boolean {
42
+ return mode === "traces" || mode === "all";
43
+ }
44
+
45
+ /**
46
+ * Observability plugin.
47
+ *
48
+ * - `off`: the middleware is not registered at all.
49
+ * - `metrics`: correlation id, Prometheus counters/histograms, `/metrics`.
50
+ * - `traces`: correlation id, OTLP spans (incoming and `tracedFetch` outgoing).
51
+ * - `all`: both.
52
+ */
53
+ export function observabilityPlugin(options: ObservabilityOptions = {}): PluginInterface {
54
+ const config = resolveOptions(options);
55
+
56
+ return {
57
+ name: "observability-plugin",
58
+ setup: (scope: PluginScope) => {
59
+ if (config.mode === "off") return;
60
+
61
+ if (shouldUseTraces(config.mode) && config.otelEndpoint) {
62
+ configureTraceExporter({
63
+ endpoint: config.otelEndpoint,
64
+ serviceName: config.serviceName,
65
+ });
66
+ }
67
+
68
+ metrics.counter("http_requests_total", "Total HTTP requests");
69
+ metrics.histogram("http_request_duration_seconds", "HTTP request duration in seconds");
70
+
71
+ scope.use(async ({context, next}: any) => {
72
+ const started = performance.now();
73
+ const method = String(context.req?.method ?? "GET").toUpperCase();
74
+ let requestId = context.state.requestId;
75
+
76
+ if (!requestId) {
77
+ requestId = resolveRequestId(context.req, config.requestIdHeader);
78
+ context.state.requestId = requestId;
79
+ context.reply.header(config.requestIdHeader, requestId);
80
+ }
81
+ context.state.responseStatus = context.state.responseStatus ?? 200;
82
+
83
+ const originalStatus = context.reply.status.bind(context.reply);
84
+ context.reply.status = (code: number) => {
85
+ context.state.responseStatus = code;
86
+ return originalStatus(code);
87
+ };
88
+
89
+ try {
90
+ if (shouldUseTraces(config.mode)) {
91
+ const parent = parseTraceparent(readHeader(context.req?.headers, "traceparent"));
92
+ await withSpan(`HTTP ${method}`, async (span) => {
93
+ span.setAttribute("http.method", method);
94
+ span.setAttribute("http.request_id", requestId);
95
+ context.state.traceId = span.traceId;
96
+ context.state.spanId = span.spanId;
97
+ await next();
98
+ }, {
99
+ parent,
100
+ attributes: {http_method: method, request_id: requestId},
101
+ });
102
+ } else {
103
+ await next();
104
+ }
105
+ } finally {
106
+ const status = Number(context.state.responseStatus ?? 200);
107
+ const route = context.state.matchedRoutePath ?? context.req?.url ?? "unknown";
108
+ const duration = (performance.now() - started) / 1000;
109
+
110
+ // Access logs are opt-in: they must not consume the
111
+ // observability performance budget. Error logs always
112
+ // carry the correlation id through the application.
113
+ if (process.env.RAITON_ACCESS_LOG === "1") {
114
+ Logger.info(
115
+ `[request] ${method} ${route} ${status} ${Math.round(duration * 1000)}ms ` +
116
+ `request_id=${requestId}` +
117
+ (context.state.traceId ? ` trace_id=${context.state.traceId}` : "")
118
+ );
119
+ }
120
+
121
+ if (shouldUseMetrics(config.mode)) {
122
+ metrics.increment("http_requests_total", {
123
+ method,
124
+ route,
125
+ status,
126
+ });
127
+ metrics.observe(
128
+ "http_request_duration_seconds",
129
+ duration,
130
+ {method, route},
131
+ );
132
+ if (status >= 500) {
133
+ metrics.increment("http_errors_total", {method, route, status});
134
+ }
135
+ }
136
+ }
137
+ });
138
+
139
+ if (shouldUseMetrics(config.mode)) {
140
+ const handler = async ({reply}: ContextInterface) => {
141
+ reply.type("text/plain; version=0.0.4; charset=utf-8");
142
+ return metrics.render();
143
+ };
144
+ (handler as any)._raitonInternal = true;
145
+ scope.get(config.metricsPath, handler);
146
+ }
147
+ },
148
+ };
149
+ }
150
+
151
+ export {traceparent};
@@ -0,0 +1,22 @@
1
+ let ready = true;
2
+ let reason: string | undefined;
3
+
4
+ export class Readiness {
5
+ static markReady(): void {
6
+ ready = true;
7
+ reason = undefined;
8
+ }
9
+
10
+ static markNotReady(nextReason = "shutting down"): void {
11
+ ready = false;
12
+ reason = nextReason;
13
+ }
14
+
15
+ static get isReady(): boolean {
16
+ return ready;
17
+ }
18
+
19
+ static snapshot(): {ready: boolean; reason?: string} {
20
+ return {ready, reason};
21
+ }
22
+ }
@@ -0,0 +1,31 @@
1
+ let counter = 0;
2
+ const VALID_REQUEST_ID = /^[A-Za-z0-9._:+\/-]{1,128}$/;
3
+
4
+ export function generateRequestId(): string {
5
+ counter = (counter + 1) % Number.MAX_SAFE_INTEGER;
6
+ return `${Date.now().toString(36)}-${counter.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
7
+ }
8
+
9
+ export function readHeader(headers: any, name: string): string | undefined {
10
+ if (!headers) return undefined;
11
+ if (typeof headers.get === "function") {
12
+ return headers.get(name) ?? undefined;
13
+ }
14
+ const lower = name.toLowerCase();
15
+ if (typeof headers === "object") {
16
+ for (const [key, value] of Object.entries(headers)) {
17
+ if (key.toLowerCase() === lower && value !== undefined) return String(value);
18
+ }
19
+ }
20
+ return undefined;
21
+ }
22
+
23
+ /**
24
+ * Reuse a valid incoming request id, otherwise generate one. Invalid values are
25
+ * rejected rather than reflected, to avoid log injection.
26
+ */
27
+ export function resolveRequestId(req: any, header = "x-request-id"): string {
28
+ const incoming = readHeader(req?.headers, header);
29
+ if (incoming && VALID_REQUEST_ID.test(incoming)) return incoming;
30
+ return generateRequestId();
31
+ }
@@ -0,0 +1,68 @@
1
+ import {Readiness} from "./readiness.ts";
2
+
3
+ /**
4
+ * Tracks in-flight requests and drains them with a configurable upper bound.
5
+ * Readiness flips to `false` as soon as shutdown starts.
6
+ */
7
+ export class ShutdownManager {
8
+ private inFlight = 0;
9
+ private waiters: Array<() => void> = [];
10
+ private draining = false;
11
+ private completedDrains = 0;
12
+
13
+ get activeRequests(): number {
14
+ return this.inFlight;
15
+ }
16
+
17
+ get isDraining(): boolean {
18
+ return this.draining;
19
+ }
20
+
21
+ get drains(): number {
22
+ return this.completedDrains;
23
+ }
24
+
25
+ track(): () => void {
26
+ this.inFlight += 1;
27
+ let released = false;
28
+ return () => {
29
+ if (released) return;
30
+ released = true;
31
+ this.inFlight = Math.max(0, this.inFlight - 1);
32
+ if (this.inFlight === 0) this.flush();
33
+ };
34
+ }
35
+
36
+ private flush(): void {
37
+ const waiters = this.waiters;
38
+ this.waiters = [];
39
+ for (const resolve of waiters) resolve();
40
+ }
41
+
42
+ async drain(timeoutMs = 10_000): Promise<{drained: boolean; remaining: number}> {
43
+ this.draining = true;
44
+ Readiness.markNotReady("shutting down");
45
+
46
+ if (this.inFlight === 0) {
47
+ this.completedDrains += 1;
48
+ return {drained: true, remaining: 0};
49
+ }
50
+
51
+ await Promise.race([
52
+ new Promise<void>(resolve => this.waiters.push(resolve)),
53
+ new Promise<void>(resolve => setTimeout(resolve, Math.max(0, timeoutMs))),
54
+ ]);
55
+
56
+ this.completedDrains += 1;
57
+ return {drained: this.inFlight === 0, remaining: this.inFlight};
58
+ }
59
+
60
+ reset(): void {
61
+ this.inFlight = 0;
62
+ this.waiters = [];
63
+ this.draining = false;
64
+ Readiness.markReady();
65
+ }
66
+ }
67
+
68
+ export const shutdown = new ShutdownManager();
@@ -0,0 +1,241 @@
1
+ import {AsyncLocalStorage} from "node:async_hooks";
2
+
3
+ export interface TraceContext {
4
+ traceId: string;
5
+ spanId: string;
6
+ parentSpanId?: string;
7
+ sampled: boolean;
8
+ }
9
+
10
+ export interface TraceSpanOptions {
11
+ attributes?: Record<string, any>;
12
+ parent?: TraceContext;
13
+ }
14
+
15
+ const storage = new AsyncLocalStorage<TraceContext>();
16
+
17
+ let idCounter = 0;
18
+
19
+ function randomHex(bytes = 16): string {
20
+ const cryptoObject: any = (globalThis as any).crypto;
21
+ if (cryptoObject?.getRandomValues) {
22
+ const array = new Uint8Array(bytes);
23
+ cryptoObject.getRandomValues(array);
24
+ return Array.from(array, value => value.toString(16).padStart(2, "0")).join("");
25
+ }
26
+ let output = "";
27
+ for (let index = 0; index < bytes * 2; index++) {
28
+ output += Math.floor(Math.random() * 16).toString(16);
29
+ }
30
+ return output;
31
+ }
32
+
33
+ export function generateTraceId(): string {
34
+ return randomHex(16);
35
+ }
36
+
37
+ export function generateSpanId(): string {
38
+ return randomHex(8);
39
+ }
40
+
41
+ export function currentTrace(): TraceContext | undefined {
42
+ return storage.getStore();
43
+ }
44
+
45
+ export function parseTraceparent(value?: string | null): TraceContext | undefined {
46
+ if (!value) return undefined;
47
+ const [version, traceId, spanId, flags] = value.trim().split("-");
48
+ if (version !== "00" || !traceId || traceId.length !== 32 || !spanId || spanId.length !== 16) return undefined;
49
+ return {
50
+ traceId,
51
+ parentSpanId: spanId,
52
+ spanId: generateSpanId(),
53
+ sampled: (parseInt(flags ?? "01", 16) & 1) === 1,
54
+ };
55
+ }
56
+
57
+ export function traceparent(context: TraceContext): string {
58
+ return `00-${context.traceId}-${context.spanId}-${context.sampled ? "01" : "00"}`;
59
+ }
60
+
61
+ export class TraceSpan {
62
+ public readonly traceId: string;
63
+ public readonly spanId: string;
64
+ public readonly parentSpanId?: string;
65
+ public readonly name: string;
66
+ public readonly startTime = Date.now();
67
+ public readonly attributes: Record<string, any>;
68
+ public readonly events: Array<{name: string; time: number; attributes?: Record<string, any>}> = [];
69
+ public status: "unset" | "ok" | "error" = "unset";
70
+ public error?: string;
71
+
72
+ constructor(name: string, context: TraceContext, attributes: Record<string, any> = {}) {
73
+ this.name = name;
74
+ this.traceId = context.traceId;
75
+ this.spanId = context.spanId;
76
+ this.parentSpanId = context.parentSpanId;
77
+ this.attributes = attributes;
78
+ }
79
+
80
+ setAttribute(key: string, value: any): this {
81
+ this.attributes[key] = value;
82
+ return this;
83
+ }
84
+
85
+ addEvent(name: string, attributes?: Record<string, any>): this {
86
+ this.events.push({name, time: Date.now(), attributes});
87
+ return this;
88
+ }
89
+
90
+ setStatus(status: "ok" | "error", error?: string): this {
91
+ this.status = status;
92
+ if (error) this.error = error;
93
+ return this;
94
+ }
95
+
96
+ get durationMs(): number {
97
+ return Date.now() - this.startTime;
98
+ }
99
+
100
+ context(): TraceContext {
101
+ return {
102
+ traceId: this.traceId,
103
+ spanId: this.spanId,
104
+ parentSpanId: this.parentSpanId,
105
+ sampled: true,
106
+ };
107
+ }
108
+
109
+ toOtlp(serviceName: string) {
110
+ return {
111
+ traceId: this.traceId,
112
+ spanId: this.spanId,
113
+ parentSpanId: this.parentSpanId,
114
+ name: this.name,
115
+ kind: 1,
116
+ startTimeUnixNano: String(BigInt(this.startTime) * 1_000_000n),
117
+ endTimeUnixNano: String(BigInt(this.startTime + this.durationMs) * 1_000_000n),
118
+ attributes: Object.entries(this.attributes)
119
+ .filter(([, value]) => value !== undefined && value !== null)
120
+ .map(([key, value]) => ({
121
+ key,
122
+ value: typeof value === "number"
123
+ ? {doubleValue: value}
124
+ : typeof value === "boolean"
125
+ ? {boolValue: value}
126
+ : {stringValue: String(value)},
127
+ })),
128
+ events: this.events.map(event => ({
129
+ name: event.name,
130
+ timeUnixNano: String(BigInt(event.time) * 1_000_000n),
131
+ })),
132
+ status: this.status === "error"
133
+ ? {code: 2, message: this.error ?? "error"}
134
+ : {code: 1},
135
+ };
136
+ }
137
+ }
138
+
139
+ export interface TraceExporterOptions {
140
+ endpoint?: string;
141
+ serviceName?: string;
142
+ headers?: Record<string, string>;
143
+ }
144
+
145
+ /**
146
+ * Minimal OTLP/HTTP JSON exporter. Export is fire-and-forget so tracing never
147
+ * blocks a request; failures are swallowed (tracing must not break the app).
148
+ */
149
+ export class OtlpExporter {
150
+ constructor(private readonly options: TraceExporterOptions = {}) {}
151
+
152
+ export(span: TraceSpan): void {
153
+ if (!this.options.endpoint) return;
154
+ const payload = {
155
+ resourceSpans: [{
156
+ resource: {
157
+ attributes: [{key: "service.name", value: {stringValue: this.options.serviceName ?? "raiton"}}],
158
+ },
159
+ scopeSpans: [{
160
+ scope: {name: "raiton"},
161
+ spans: [span.toOtlp(this.options.serviceName ?? "raiton")],
162
+ }],
163
+ }],
164
+ };
165
+
166
+ const endpoint = this.options.endpoint.replace(/\/$/, "");
167
+ const url = endpoint.endsWith("/v1/traces") ? endpoint : `${endpoint}/v1/traces`;
168
+
169
+ try {
170
+ void fetch(url, {
171
+ method: "POST",
172
+ headers: {"content-type": "application/json", ...(this.options.headers ?? {})},
173
+ body: JSON.stringify(payload),
174
+ }).catch(() => undefined);
175
+ } catch {
176
+ // Tracing is best-effort.
177
+ }
178
+ }
179
+ }
180
+
181
+ let defaultExporter = new OtlpExporter();
182
+
183
+ export function configureTraceExporter(options: TraceExporterOptions): void {
184
+ defaultExporter = new OtlpExporter(options);
185
+ }
186
+
187
+ export function startSpan(name: string, options: TraceSpanOptions = {}): TraceSpan {
188
+ const parent = options.parent ?? currentTrace();
189
+ const context: TraceContext = {
190
+ traceId: parent?.traceId ?? generateTraceId(),
191
+ spanId: generateSpanId(),
192
+ parentSpanId: parent?.spanId,
193
+ sampled: parent?.sampled ?? true,
194
+ };
195
+ return new TraceSpan(name, context, options.attributes);
196
+ }
197
+
198
+ /**
199
+ * Run a callback inside a trace. Nested spans share the trace id, which is how
200
+ * incoming and outgoing operations are correlated.
201
+ */
202
+ export async function withSpan<T>(
203
+ name: string,
204
+ callable: (span: TraceSpan) => Promise<T> | T,
205
+ options: TraceSpanOptions = {},
206
+ ): Promise<T> {
207
+ const span = startSpan(name, options);
208
+ try {
209
+ const result = await storage.run(span.context(), () => callable(span));
210
+ if (span.status === "unset") span.setStatus("ok");
211
+ return result;
212
+ } catch (error: any) {
213
+ span.setStatus("error", error?.message ?? String(error));
214
+ throw error;
215
+ } finally {
216
+ defaultExporter.export(span);
217
+ }
218
+ }
219
+
220
+ /**
221
+ * `fetch` wrapper that propagates the active trace and records an outgoing span.
222
+ */
223
+ export async function tracedFetch(input: any, init: RequestInit = {}): Promise<Response> {
224
+ const parent = currentTrace();
225
+ const headers = new Headers(init.headers ?? {});
226
+
227
+ return withSpan(
228
+ `HTTP ${init.method ?? "GET"} ${typeof input === "string" ? input : (input?.url ?? "outgoing")}`,
229
+ async (span) => {
230
+ // The outgoing operation is the child span; propagate its context
231
+ // so the remote service joins the same trace.
232
+ headers.set("traceparent", traceparent(span.context()));
233
+ span.setAttribute("http.method", init.method ?? "GET");
234
+ const response = await fetch(input, {...init, headers});
235
+ span.setAttribute("http.status_code", response.status);
236
+ if (!response.ok) span.setStatus("error", `HTTP ${response.status}`);
237
+ return response;
238
+ },
239
+ parent ? {parent} : {},
240
+ );
241
+ }