@bleedingdev/modern-js-server-core 3.2.0-ultramodern.0

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 (291) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/dist/cjs/adapters/node/helper/index.js +55 -0
  4. package/dist/cjs/adapters/node/helper/loadCache.js +58 -0
  5. package/dist/cjs/adapters/node/helper/loadConfig.js +78 -0
  6. package/dist/cjs/adapters/node/helper/loadEnv.js +66 -0
  7. package/dist/cjs/adapters/node/helper/loadPlugin.js +47 -0
  8. package/dist/cjs/adapters/node/helper/utils.js +39 -0
  9. package/dist/cjs/adapters/node/hono.js +95 -0
  10. package/dist/cjs/adapters/node/index.js +87 -0
  11. package/dist/cjs/adapters/node/node.js +180 -0
  12. package/dist/cjs/adapters/node/plugins/index.js +72 -0
  13. package/dist/cjs/adapters/node/plugins/nodeServer.js +43 -0
  14. package/dist/cjs/adapters/node/plugins/resource.js +206 -0
  15. package/dist/cjs/adapters/node/plugins/static.js +379 -0
  16. package/dist/cjs/constants.js +77 -0
  17. package/dist/cjs/context.js +41 -0
  18. package/dist/cjs/helper.js +45 -0
  19. package/dist/cjs/hono.js +46 -0
  20. package/dist/cjs/index.js +247 -0
  21. package/dist/cjs/plugins/compat/hooks.js +80 -0
  22. package/dist/cjs/plugins/compat/index.js +64 -0
  23. package/dist/cjs/plugins/contractGateAutopilot.js +158 -0
  24. package/dist/cjs/plugins/contractGateSnapshotStore.js +239 -0
  25. package/dist/cjs/plugins/default.js +61 -0
  26. package/dist/cjs/plugins/favicon.js +48 -0
  27. package/dist/cjs/plugins/index.js +157 -0
  28. package/dist/cjs/plugins/log.js +92 -0
  29. package/dist/cjs/plugins/mfCache.js +78 -0
  30. package/dist/cjs/plugins/middlewares.js +49 -0
  31. package/dist/cjs/plugins/monitors.js +192 -0
  32. package/dist/cjs/plugins/processedBy.js +50 -0
  33. package/dist/cjs/plugins/render/csrRscRender.js +74 -0
  34. package/dist/cjs/plugins/render/dataHandler.js +53 -0
  35. package/dist/cjs/plugins/render/index.js +158 -0
  36. package/dist/cjs/plugins/render/inject.js +92 -0
  37. package/dist/cjs/plugins/render/render.js +273 -0
  38. package/dist/cjs/plugins/render/renderRscHandler.js +72 -0
  39. package/dist/cjs/plugins/render/serverActionHandler.js +47 -0
  40. package/dist/cjs/plugins/render/ssrCache.js +198 -0
  41. package/dist/cjs/plugins/render/ssrRender.js +96 -0
  42. package/dist/cjs/plugins/render/utils.js +49 -0
  43. package/dist/cjs/plugins/route.js +68 -0
  44. package/dist/cjs/plugins/telemetry.js +1283 -0
  45. package/dist/cjs/serverBase.js +176 -0
  46. package/dist/cjs/types/config/bff.js +18 -0
  47. package/dist/cjs/types/config/dev.js +18 -0
  48. package/dist/cjs/types/config/html.js +18 -0
  49. package/dist/cjs/types/config/index.js +93 -0
  50. package/dist/cjs/types/config/output.js +18 -0
  51. package/dist/cjs/types/config/security.js +18 -0
  52. package/dist/cjs/types/config/server.js +18 -0
  53. package/dist/cjs/types/config/share.js +18 -0
  54. package/dist/cjs/types/config/source.js +18 -0
  55. package/dist/cjs/types/config/tools.js +18 -0
  56. package/dist/cjs/types/index.js +79 -0
  57. package/dist/cjs/types/plugins/base.js +18 -0
  58. package/dist/cjs/types/plugins/index.js +58 -0
  59. package/dist/cjs/types/plugins/plugin.js +18 -0
  60. package/dist/cjs/types/render.js +18 -0
  61. package/dist/cjs/types/requestHandler.js +18 -0
  62. package/dist/cjs/types/server.js +18 -0
  63. package/dist/cjs/utils/entry.js +40 -0
  64. package/dist/cjs/utils/env.js +51 -0
  65. package/dist/cjs/utils/error.js +93 -0
  66. package/dist/cjs/utils/index.js +114 -0
  67. package/dist/cjs/utils/middlewareCollector.js +63 -0
  68. package/dist/cjs/utils/publicDir.js +92 -0
  69. package/dist/cjs/utils/request.js +86 -0
  70. package/dist/cjs/utils/serverConfig.js +43 -0
  71. package/dist/cjs/utils/storage.js +69 -0
  72. package/dist/cjs/utils/transformStream.js +65 -0
  73. package/dist/cjs/utils/warmup.js +40 -0
  74. package/dist/esm/adapters/node/helper/index.mjs +5 -0
  75. package/dist/esm/adapters/node/helper/loadCache.mjs +14 -0
  76. package/dist/esm/adapters/node/helper/loadConfig.mjs +31 -0
  77. package/dist/esm/adapters/node/helper/loadEnv.mjs +22 -0
  78. package/dist/esm/adapters/node/helper/loadPlugin.mjs +13 -0
  79. package/dist/esm/adapters/node/helper/utils.mjs +5 -0
  80. package/dist/esm/adapters/node/hono.mjs +55 -0
  81. package/dist/esm/adapters/node/index.mjs +4 -0
  82. package/dist/esm/adapters/node/node.mjs +130 -0
  83. package/dist/esm/adapters/node/plugins/index.mjs +3 -0
  84. package/dist/esm/adapters/node/plugins/nodeServer.mjs +9 -0
  85. package/dist/esm/adapters/node/plugins/resource.mjs +138 -0
  86. package/dist/esm/adapters/node/plugins/static.mjs +329 -0
  87. package/dist/esm/constants.mjs +28 -0
  88. package/dist/esm/context.mjs +4 -0
  89. package/dist/esm/helper.mjs +11 -0
  90. package/dist/esm/hono.mjs +2 -0
  91. package/dist/esm/index.mjs +12 -0
  92. package/dist/esm/plugins/compat/hooks.mjs +40 -0
  93. package/dist/esm/plugins/compat/index.mjs +27 -0
  94. package/dist/esm/plugins/contractGateAutopilot.mjs +124 -0
  95. package/dist/esm/plugins/contractGateSnapshotStore.mjs +180 -0
  96. package/dist/esm/plugins/default.mjs +27 -0
  97. package/dist/esm/plugins/favicon.mjs +14 -0
  98. package/dist/esm/plugins/index.mjs +11 -0
  99. package/dist/esm/plugins/log.mjs +58 -0
  100. package/dist/esm/plugins/mfCache.mjs +35 -0
  101. package/dist/esm/plugins/middlewares.mjs +15 -0
  102. package/dist/esm/plugins/monitors.mjs +149 -0
  103. package/dist/esm/plugins/processedBy.mjs +16 -0
  104. package/dist/esm/plugins/render/csrRscRender.mjs +40 -0
  105. package/dist/esm/plugins/render/dataHandler.mjs +19 -0
  106. package/dist/esm/plugins/render/index.mjs +84 -0
  107. package/dist/esm/plugins/render/inject.mjs +55 -0
  108. package/dist/esm/plugins/render/render.mjs +230 -0
  109. package/dist/esm/plugins/render/renderRscHandler.mjs +38 -0
  110. package/dist/esm/plugins/render/serverActionHandler.mjs +13 -0
  111. package/dist/esm/plugins/render/ssrCache.mjs +158 -0
  112. package/dist/esm/plugins/render/ssrRender.mjs +62 -0
  113. package/dist/esm/plugins/render/utils.mjs +15 -0
  114. package/dist/esm/plugins/route.mjs +34 -0
  115. package/dist/esm/plugins/telemetry.mjs +1195 -0
  116. package/dist/esm/rslib-runtime.mjs +18 -0
  117. package/dist/esm/serverBase.mjs +139 -0
  118. package/dist/esm/types/config/bff.mjs +0 -0
  119. package/dist/esm/types/config/dev.mjs +0 -0
  120. package/dist/esm/types/config/html.mjs +0 -0
  121. package/dist/esm/types/config/index.mjs +6 -0
  122. package/dist/esm/types/config/output.mjs +0 -0
  123. package/dist/esm/types/config/security.mjs +0 -0
  124. package/dist/esm/types/config/server.mjs +0 -0
  125. package/dist/esm/types/config/share.mjs +0 -0
  126. package/dist/esm/types/config/source.mjs +0 -0
  127. package/dist/esm/types/config/tools.mjs +0 -0
  128. package/dist/esm/types/index.mjs +4 -0
  129. package/dist/esm/types/plugins/base.mjs +0 -0
  130. package/dist/esm/types/plugins/index.mjs +1 -0
  131. package/dist/esm/types/plugins/plugin.mjs +0 -0
  132. package/dist/esm/types/render.mjs +0 -0
  133. package/dist/esm/types/requestHandler.mjs +0 -0
  134. package/dist/esm/types/server.mjs +0 -0
  135. package/dist/esm/utils/entry.mjs +3 -0
  136. package/dist/esm/utils/env.mjs +14 -0
  137. package/dist/esm/utils/error.mjs +53 -0
  138. package/dist/esm/utils/index.mjs +9 -0
  139. package/dist/esm/utils/middlewareCollector.mjs +26 -0
  140. package/dist/esm/utils/publicDir.mjs +33 -0
  141. package/dist/esm/utils/request.mjs +40 -0
  142. package/dist/esm/utils/serverConfig.mjs +9 -0
  143. package/dist/esm/utils/storage.mjs +35 -0
  144. package/dist/esm/utils/transformStream.mjs +28 -0
  145. package/dist/esm/utils/warmup.mjs +6 -0
  146. package/dist/esm-node/adapters/node/helper/index.mjs +6 -0
  147. package/dist/esm-node/adapters/node/helper/loadCache.mjs +15 -0
  148. package/dist/esm-node/adapters/node/helper/loadConfig.mjs +32 -0
  149. package/dist/esm-node/adapters/node/helper/loadEnv.mjs +23 -0
  150. package/dist/esm-node/adapters/node/helper/loadPlugin.mjs +14 -0
  151. package/dist/esm-node/adapters/node/helper/utils.mjs +6 -0
  152. package/dist/esm-node/adapters/node/hono.mjs +56 -0
  153. package/dist/esm-node/adapters/node/index.mjs +5 -0
  154. package/dist/esm-node/adapters/node/node.mjs +131 -0
  155. package/dist/esm-node/adapters/node/plugins/index.mjs +4 -0
  156. package/dist/esm-node/adapters/node/plugins/nodeServer.mjs +10 -0
  157. package/dist/esm-node/adapters/node/plugins/resource.mjs +139 -0
  158. package/dist/esm-node/adapters/node/plugins/static.mjs +330 -0
  159. package/dist/esm-node/constants.mjs +29 -0
  160. package/dist/esm-node/context.mjs +5 -0
  161. package/dist/esm-node/helper.mjs +12 -0
  162. package/dist/esm-node/hono.mjs +3 -0
  163. package/dist/esm-node/index.mjs +13 -0
  164. package/dist/esm-node/plugins/compat/hooks.mjs +41 -0
  165. package/dist/esm-node/plugins/compat/index.mjs +28 -0
  166. package/dist/esm-node/plugins/contractGateAutopilot.mjs +125 -0
  167. package/dist/esm-node/plugins/contractGateSnapshotStore.mjs +182 -0
  168. package/dist/esm-node/plugins/default.mjs +28 -0
  169. package/dist/esm-node/plugins/favicon.mjs +15 -0
  170. package/dist/esm-node/plugins/index.mjs +12 -0
  171. package/dist/esm-node/plugins/log.mjs +59 -0
  172. package/dist/esm-node/plugins/mfCache.mjs +36 -0
  173. package/dist/esm-node/plugins/middlewares.mjs +16 -0
  174. package/dist/esm-node/plugins/monitors.mjs +150 -0
  175. package/dist/esm-node/plugins/processedBy.mjs +17 -0
  176. package/dist/esm-node/plugins/render/csrRscRender.mjs +41 -0
  177. package/dist/esm-node/plugins/render/dataHandler.mjs +20 -0
  178. package/dist/esm-node/plugins/render/index.mjs +85 -0
  179. package/dist/esm-node/plugins/render/inject.mjs +56 -0
  180. package/dist/esm-node/plugins/render/render.mjs +231 -0
  181. package/dist/esm-node/plugins/render/renderRscHandler.mjs +39 -0
  182. package/dist/esm-node/plugins/render/serverActionHandler.mjs +14 -0
  183. package/dist/esm-node/plugins/render/ssrCache.mjs +159 -0
  184. package/dist/esm-node/plugins/render/ssrRender.mjs +63 -0
  185. package/dist/esm-node/plugins/render/utils.mjs +16 -0
  186. package/dist/esm-node/plugins/route.mjs +35 -0
  187. package/dist/esm-node/plugins/telemetry.mjs +1196 -0
  188. package/dist/esm-node/rslib-runtime.mjs +19 -0
  189. package/dist/esm-node/serverBase.mjs +140 -0
  190. package/dist/esm-node/types/config/bff.mjs +1 -0
  191. package/dist/esm-node/types/config/dev.mjs +1 -0
  192. package/dist/esm-node/types/config/html.mjs +1 -0
  193. package/dist/esm-node/types/config/index.mjs +7 -0
  194. package/dist/esm-node/types/config/output.mjs +1 -0
  195. package/dist/esm-node/types/config/security.mjs +1 -0
  196. package/dist/esm-node/types/config/server.mjs +1 -0
  197. package/dist/esm-node/types/config/share.mjs +1 -0
  198. package/dist/esm-node/types/config/source.mjs +1 -0
  199. package/dist/esm-node/types/config/tools.mjs +1 -0
  200. package/dist/esm-node/types/index.mjs +5 -0
  201. package/dist/esm-node/types/plugins/base.mjs +1 -0
  202. package/dist/esm-node/types/plugins/index.mjs +2 -0
  203. package/dist/esm-node/types/plugins/plugin.mjs +1 -0
  204. package/dist/esm-node/types/render.mjs +1 -0
  205. package/dist/esm-node/types/requestHandler.mjs +1 -0
  206. package/dist/esm-node/types/server.mjs +1 -0
  207. package/dist/esm-node/utils/entry.mjs +4 -0
  208. package/dist/esm-node/utils/env.mjs +15 -0
  209. package/dist/esm-node/utils/error.mjs +54 -0
  210. package/dist/esm-node/utils/index.mjs +10 -0
  211. package/dist/esm-node/utils/middlewareCollector.mjs +27 -0
  212. package/dist/esm-node/utils/publicDir.mjs +34 -0
  213. package/dist/esm-node/utils/request.mjs +41 -0
  214. package/dist/esm-node/utils/serverConfig.mjs +10 -0
  215. package/dist/esm-node/utils/storage.mjs +36 -0
  216. package/dist/esm-node/utils/transformStream.mjs +29 -0
  217. package/dist/esm-node/utils/warmup.mjs +7 -0
  218. package/dist/types/adapters/node/helper/index.d.ts +6 -0
  219. package/dist/types/adapters/node/helper/loadCache.d.ts +2 -0
  220. package/dist/types/adapters/node/helper/loadConfig.d.ts +3 -0
  221. package/dist/types/adapters/node/helper/loadEnv.d.ts +3 -0
  222. package/dist/types/adapters/node/helper/loadPlugin.d.ts +3 -0
  223. package/dist/types/adapters/node/helper/utils.d.ts +21 -0
  224. package/dist/types/adapters/node/hono.d.ts +19 -0
  225. package/dist/types/adapters/node/index.d.ts +5 -0
  226. package/dist/types/adapters/node/node.d.ts +17 -0
  227. package/dist/types/adapters/node/plugins/index.d.ts +3 -0
  228. package/dist/types/adapters/node/plugins/nodeServer.d.ts +6 -0
  229. package/dist/types/adapters/node/plugins/resource.d.ts +11 -0
  230. package/dist/types/adapters/node/plugins/static.d.ts +25 -0
  231. package/dist/types/constants.d.ts +26 -0
  232. package/dist/types/context.d.ts +3 -0
  233. package/dist/types/helper.d.ts +10 -0
  234. package/dist/types/hono.d.ts +3 -0
  235. package/dist/types/index.d.ts +14 -0
  236. package/dist/types/plugins/compat/hooks.d.ts +8 -0
  237. package/dist/types/plugins/compat/index.d.ts +3 -0
  238. package/dist/types/plugins/contractGateAutopilot.d.ts +35 -0
  239. package/dist/types/plugins/contractGateSnapshotStore.d.ts +57 -0
  240. package/dist/types/plugins/default.d.ts +7 -0
  241. package/dist/types/plugins/favicon.d.ts +2 -0
  242. package/dist/types/plugins/index.d.ts +11 -0
  243. package/dist/types/plugins/log.d.ts +2 -0
  244. package/dist/types/plugins/mfCache.d.ts +12 -0
  245. package/dist/types/plugins/middlewares.d.ts +2 -0
  246. package/dist/types/plugins/monitors.d.ts +6 -0
  247. package/dist/types/plugins/processedBy.d.ts +2 -0
  248. package/dist/types/plugins/render/csrRscRender.d.ts +2 -0
  249. package/dist/types/plugins/render/dataHandler.d.ts +5 -0
  250. package/dist/types/plugins/render/index.d.ts +3 -0
  251. package/dist/types/plugins/render/inject.d.ts +7 -0
  252. package/dist/types/plugins/render/render.d.ts +16 -0
  253. package/dist/types/plugins/render/renderRscHandler.d.ts +2 -0
  254. package/dist/types/plugins/render/serverActionHandler.d.ts +2 -0
  255. package/dist/types/plugins/render/ssrCache.d.ts +18 -0
  256. package/dist/types/plugins/render/ssrRender.d.ts +26 -0
  257. package/dist/types/plugins/render/utils.d.ts +3 -0
  258. package/dist/types/plugins/route.d.ts +2 -0
  259. package/dist/types/plugins/telemetry.d.ts +309 -0
  260. package/dist/types/serverBase.d.ts +38 -0
  261. package/dist/types/types/config/bff.d.ts +142 -0
  262. package/dist/types/types/config/dev.d.ts +4 -0
  263. package/dist/types/types/config/html.d.ts +15 -0
  264. package/dist/types/types/config/index.d.ts +35 -0
  265. package/dist/types/types/config/output.d.ts +20 -0
  266. package/dist/types/types/config/security.d.ts +4 -0
  267. package/dist/types/types/config/server.d.ts +402 -0
  268. package/dist/types/types/config/share.d.ts +3 -0
  269. package/dist/types/types/config/source.d.ts +7 -0
  270. package/dist/types/types/config/tools.d.ts +2 -0
  271. package/dist/types/types/index.d.ts +4 -0
  272. package/dist/types/types/plugins/base.d.ts +57 -0
  273. package/dist/types/types/plugins/index.d.ts +2 -0
  274. package/dist/types/types/plugins/plugin.d.ts +31 -0
  275. package/dist/types/types/render.d.ts +24 -0
  276. package/dist/types/types/requestHandler.d.ts +48 -0
  277. package/dist/types/types/server.d.ts +67 -0
  278. package/dist/types/utils/entry.d.ts +3 -0
  279. package/dist/types/utils/env.d.ts +2 -0
  280. package/dist/types/utils/error.d.ts +8 -0
  281. package/dist/types/utils/index.d.ts +9 -0
  282. package/dist/types/utils/middlewareCollector.d.ts +12 -0
  283. package/dist/types/utils/publicDir.d.ts +40 -0
  284. package/dist/types/utils/request.d.ts +17 -0
  285. package/dist/types/utils/serverConfig.d.ts +8 -0
  286. package/dist/types/utils/storage.d.ts +5 -0
  287. package/dist/types/utils/transformStream.d.ts +5 -0
  288. package/dist/types/utils/warmup.d.ts +1 -0
  289. package/package.json +103 -0
  290. package/rslib.config.mts +4 -0
  291. package/rstest.config.mts +7 -0
@@ -0,0 +1,1195 @@
1
+ import { ContractGateAutopilot } from "./contractGateAutopilot.mjs";
2
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "./contractGateSnapshotStore.mjs";
3
+ class TelemetryStartupHealthError extends Error {
4
+ constructor(failedExporters){
5
+ super(`Telemetry startup health check failed for exporters: ${failedExporters.map((item)=>item.name).join(', ')}`), this.code = 'TELEMETRY_EXPORTER_STARTUP_HEALTH_FAILED';
6
+ this.name = 'TelemetryStartupHealthError';
7
+ this.failedExporters = failedExporters;
8
+ }
9
+ }
10
+ const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;
11
+ const DEFAULT_OTLP_ENDPOINT = 'http://127.0.0.1:4318/v1/logs';
12
+ const DEFAULT_VM_ENDPOINT = 'http://127.0.0.1:8428/api/v1/import/prometheus';
13
+ const DEFAULT_TIMEOUT_MS = 5000;
14
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
15
+ const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
16
+ const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
17
+ const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
18
+ const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
19
+ const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
20
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
21
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60000;
22
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10000;
23
+ function clamp(value, min, max) {
24
+ return Math.max(min, Math.min(max, value));
25
+ }
26
+ function isRecord(value) {
27
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
28
+ }
29
+ function redactObject(value, redactionKeys) {
30
+ if (!isRecord(value)) return;
31
+ const output = {};
32
+ for (const [key, nested] of Object.entries(value)){
33
+ if (redactionKeys.has(key)) {
34
+ output[key] = '[REDACTED]';
35
+ continue;
36
+ }
37
+ if (Array.isArray(nested)) {
38
+ output[key] = nested.map((item)=>{
39
+ if (isRecord(item)) return redactObject(item, redactionKeys);
40
+ return item;
41
+ });
42
+ continue;
43
+ }
44
+ if (isRecord(nested)) {
45
+ output[key] = redactObject(nested, redactionKeys);
46
+ continue;
47
+ }
48
+ output[key] = nested;
49
+ }
50
+ return output;
51
+ }
52
+ function normalizeLabels(labels) {
53
+ if (!labels) return;
54
+ const normalized = {};
55
+ for (const [key, value] of Object.entries(labels))if (null != value) normalized[key] = String(value);
56
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
57
+ }
58
+ function parseTraceparent(header) {
59
+ if (!header) return;
60
+ const match = header.trim().match(TRACEPARENT_REGEX);
61
+ if (!match) return;
62
+ const traceId = match[1]?.toLowerCase();
63
+ const spanId = match[2]?.toLowerCase();
64
+ if (!traceId || !spanId) return;
65
+ return {
66
+ traceId,
67
+ spanId
68
+ };
69
+ }
70
+ function extractError(args) {
71
+ for (const arg of args)if (arg instanceof Error) return {
72
+ name: arg.name,
73
+ message: arg.message,
74
+ stack: arg.stack
75
+ };
76
+ }
77
+ function toTelemetryEnvelope(event, input) {
78
+ const base = {
79
+ timestamp: Date.now(),
80
+ service: input.service,
81
+ module: input.module,
82
+ environment: input.environment,
83
+ ...input.traceId ? {
84
+ traceId: input.traceId
85
+ } : {},
86
+ ...input.spanId ? {
87
+ spanId: input.spanId
88
+ } : {},
89
+ ...input.attributes ? {
90
+ attributes: input.attributes
91
+ } : {}
92
+ };
93
+ if ('log' === event.type) {
94
+ const payload = event.payload;
95
+ const args = payload.args || [];
96
+ const signalType = 'trace' === payload.level ? 'trace' : 'log';
97
+ return {
98
+ ...base,
99
+ signalType,
100
+ name: payload.message,
101
+ level: payload.level,
102
+ attributes: {
103
+ ...base.attributes || {},
104
+ args
105
+ },
106
+ error: extractError(args)
107
+ };
108
+ }
109
+ if ('timing' === event.type) return {
110
+ ...base,
111
+ signalType: 'metric',
112
+ name: event.payload.name,
113
+ value: event.payload.dur,
114
+ unit: 'ms',
115
+ tags: normalizeLabels(event.payload.tags),
116
+ attributes: {
117
+ ...base.attributes || {},
118
+ desc: event.payload.desc,
119
+ args: event.payload.args
120
+ }
121
+ };
122
+ return {
123
+ ...base,
124
+ signalType: 'metric',
125
+ name: event.payload.name,
126
+ value: 1,
127
+ unit: 'count',
128
+ tags: normalizeLabels(event.payload.tags),
129
+ attributes: {
130
+ ...base.attributes || {},
131
+ args: event.payload.args
132
+ }
133
+ };
134
+ }
135
+ async function postWithTimeout(options) {
136
+ const controller = new AbortController();
137
+ const timer = setTimeout(()=>controller.abort(), options.timeoutMs);
138
+ if ('function' == typeof timer.unref) timer.unref();
139
+ try {
140
+ const response = await fetch(options.endpoint, {
141
+ method: 'POST',
142
+ body: options.body,
143
+ headers: options.headers,
144
+ signal: controller.signal
145
+ });
146
+ if (!response.ok) throw new Error(`Telemetry exporter request failed: ${response.status} ${response.statusText}`);
147
+ } finally{
148
+ clearTimeout(timer);
149
+ }
150
+ }
151
+ function sanitizeMetricName(value) {
152
+ return value.replace(/[^a-zA-Z0-9_:]/g, '_').replace(/_+/g, '_');
153
+ }
154
+ function escapeLabelValue(value) {
155
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
156
+ }
157
+ function toPrometheusLine(envelope, metricPrefix) {
158
+ const metricName = sanitizeMetricName(`${metricPrefix}_${envelope.signalType}_${envelope.name}`);
159
+ const labels = {
160
+ service: envelope.service,
161
+ module: envelope.module,
162
+ environment: envelope.environment,
163
+ ...envelope.level ? {
164
+ level: envelope.level
165
+ } : {},
166
+ ...envelope.traceId ? {
167
+ trace_id: envelope.traceId
168
+ } : {},
169
+ ...envelope.spanId ? {
170
+ span_id: envelope.spanId
171
+ } : {},
172
+ ...envelope.tags || {}
173
+ };
174
+ const labelPairs = Object.entries(labels).sort(([a], [b])=>a.localeCompare(b)).map(([key, value])=>`${sanitizeMetricName(key)}="${escapeLabelValue(value)}"`);
175
+ const labelText = labelPairs.length > 0 ? `{${labelPairs.join(',')}}` : '';
176
+ const value = 'number' == typeof envelope.value && Number.isFinite(envelope.value) ? envelope.value : 1;
177
+ const timestampMs = envelope.timestamp;
178
+ return `${metricName}${labelText} ${value} ${timestampMs}`;
179
+ }
180
+ function createOtlpTelemetryExporter(options = {}) {
181
+ const endpoint = options.endpoint || DEFAULT_OTLP_ENDPOINT;
182
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
183
+ const headers = {
184
+ 'content-type': 'application/json',
185
+ ...options.headers || {}
186
+ };
187
+ return {
188
+ name: 'otlp',
189
+ async emit (batch) {
190
+ if (0 === batch.length) return;
191
+ const body = JSON.stringify({
192
+ resource: {
193
+ service: batch[0]?.service,
194
+ module: batch[0]?.module,
195
+ environment: batch[0]?.environment
196
+ },
197
+ emittedAt: Date.now(),
198
+ events: batch
199
+ });
200
+ await postWithTimeout({
201
+ endpoint,
202
+ body,
203
+ headers,
204
+ timeoutMs
205
+ });
206
+ }
207
+ };
208
+ }
209
+ function createVictoriaMetricsTelemetryExporter(options = {}) {
210
+ const endpoint = options.endpoint || DEFAULT_VM_ENDPOINT;
211
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
212
+ const metricPrefix = sanitizeMetricName(options.metricPrefix || 'modernjs');
213
+ const headers = {
214
+ 'content-type': 'text/plain; version=0.0.4',
215
+ ...options.headers || {}
216
+ };
217
+ return {
218
+ name: 'victoria-metrics',
219
+ async emit (batch) {
220
+ if (0 === batch.length) return;
221
+ const lines = batch.map((item)=>toPrometheusLine(item, metricPrefix));
222
+ await postWithTimeout({
223
+ endpoint,
224
+ body: `${lines.join('\n')}\n`,
225
+ headers,
226
+ timeoutMs
227
+ });
228
+ }
229
+ };
230
+ }
231
+ class TelemetryRegistry {
232
+ async register(exporter) {
233
+ this.exporters.push(exporter);
234
+ this.exporterHealth.set(exporter.name, {
235
+ name: exporter.name,
236
+ healthy: true,
237
+ failures: 0
238
+ });
239
+ if (exporter.init) try {
240
+ await exporter.init({
241
+ service: this.service,
242
+ module: this.module,
243
+ environment: this.environment
244
+ });
245
+ this.markExporterHealthy(exporter.name);
246
+ } catch (error) {
247
+ this.markExporterFailure(exporter.name, error);
248
+ throw error;
249
+ }
250
+ else this.markExporterHealthy(exporter.name);
251
+ }
252
+ getOrCreateExporterHealth(name) {
253
+ const existing = this.exporterHealth.get(name);
254
+ if (existing) return existing;
255
+ const next = {
256
+ name,
257
+ healthy: true,
258
+ failures: 0
259
+ };
260
+ this.exporterHealth.set(name, next);
261
+ return next;
262
+ }
263
+ markExporterHealthy(name) {
264
+ const status = this.getOrCreateExporterHealth(name);
265
+ status.healthy = true;
266
+ status.lastSuccessAt = Date.now();
267
+ status.lastError = void 0;
268
+ }
269
+ markExporterFailure(name, error) {
270
+ const status = this.getOrCreateExporterHealth(name);
271
+ status.healthy = false;
272
+ status.failures += 1;
273
+ status.lastFailureAt = Date.now();
274
+ status.lastError = error instanceof Error ? error.message : String(error);
275
+ }
276
+ maybeEmitSloAlert(type, value, threshold) {
277
+ if (!this.onSloAlert || value < threshold) return;
278
+ const now = Date.now();
279
+ const lastTimestamp = this.lastSloAlertAt.get(type) ?? 0;
280
+ if (now - lastTimestamp < this.alertCooldownMs) return;
281
+ this.lastSloAlertAt.set(type, now);
282
+ const queueDepth = this.queue.length;
283
+ try {
284
+ this.onSloAlert({
285
+ timestamp: now,
286
+ service: this.service,
287
+ module: this.module,
288
+ environment: this.environment,
289
+ type,
290
+ value,
291
+ threshold,
292
+ queueDepth,
293
+ queueCapacity: this.maxQueueSize,
294
+ queueUtilization: queueDepth / this.maxQueueSize,
295
+ totalDropped: this.totalDroppedCount
296
+ });
297
+ } catch (_error) {}
298
+ }
299
+ enqueue(envelope) {
300
+ if (this.samplingRate < 1 && Math.random() > this.samplingRate) return;
301
+ const redactedEnvelope = this.redactionKeys.size > 0 ? {
302
+ ...envelope,
303
+ attributes: redactObject(envelope.attributes, this.redactionKeys)
304
+ } : envelope;
305
+ if (this.queue.length >= this.maxQueueSize) {
306
+ this.queue.shift();
307
+ this.droppedCount += 1;
308
+ this.totalDroppedCount += 1;
309
+ this.maybeEmitSloAlert('queue.drop', this.totalDroppedCount, this.queueDroppedWarnThreshold);
310
+ }
311
+ this.queue.push(redactedEnvelope);
312
+ this.maybeEmitSloAlert('queue.utilization', this.queue.length / this.maxQueueSize, this.queueUtilizationWarnThreshold);
313
+ if (this.queue.length >= this.maxBatchSize) this.flush();
314
+ }
315
+ enqueueMetric(input) {
316
+ this.enqueue({
317
+ timestamp: Date.now(),
318
+ service: this.service,
319
+ module: this.module,
320
+ environment: this.environment,
321
+ signalType: 'metric',
322
+ name: input.name,
323
+ value: input.value,
324
+ unit: input.unit || 'count',
325
+ traceId: input.traceId,
326
+ spanId: input.spanId,
327
+ parentSpanId: input.parentSpanId,
328
+ tags: input.tags,
329
+ attributes: input.attributes
330
+ });
331
+ }
332
+ enqueueLog(input) {
333
+ this.enqueue({
334
+ timestamp: Date.now(),
335
+ service: this.service,
336
+ module: this.module,
337
+ environment: this.environment,
338
+ signalType: 'log',
339
+ name: input.name,
340
+ level: input.level,
341
+ traceId: input.traceId,
342
+ spanId: input.spanId,
343
+ parentSpanId: input.parentSpanId,
344
+ tags: input.tags,
345
+ attributes: input.attributes,
346
+ error: input.error
347
+ });
348
+ }
349
+ enqueueTrace(input) {
350
+ this.enqueue({
351
+ timestamp: Date.now(),
352
+ service: this.service,
353
+ module: this.module,
354
+ environment: this.environment,
355
+ signalType: 'trace',
356
+ name: input.name,
357
+ traceId: input.traceId,
358
+ spanId: input.spanId,
359
+ parentSpanId: input.parentSpanId,
360
+ tags: input.tags,
361
+ attributes: input.attributes
362
+ });
363
+ }
364
+ buildDroppedEnvelope(droppedCount) {
365
+ return {
366
+ timestamp: Date.now(),
367
+ service: this.service,
368
+ module: this.module,
369
+ environment: this.environment,
370
+ signalType: 'metric',
371
+ name: 'telemetry.queue.dropped',
372
+ value: droppedCount,
373
+ unit: 'count',
374
+ tags: {
375
+ reason: 'queue_backpressure'
376
+ }
377
+ };
378
+ }
379
+ buildQueueDepthEnvelope(queueDepth) {
380
+ return {
381
+ timestamp: Date.now(),
382
+ service: this.service,
383
+ module: this.module,
384
+ environment: this.environment,
385
+ signalType: 'metric',
386
+ name: 'telemetry.queue.depth',
387
+ value: queueDepth,
388
+ unit: 'count',
389
+ tags: {
390
+ capacity: String(this.maxQueueSize)
391
+ }
392
+ };
393
+ }
394
+ buildQueueUtilizationEnvelope(queueDepth) {
395
+ return {
396
+ timestamp: Date.now(),
397
+ service: this.service,
398
+ module: this.module,
399
+ environment: this.environment,
400
+ signalType: 'metric',
401
+ name: 'telemetry.queue.utilization',
402
+ value: queueDepth / this.maxQueueSize,
403
+ unit: 'ratio',
404
+ tags: {
405
+ capacity: String(this.maxQueueSize)
406
+ }
407
+ };
408
+ }
409
+ async emitBatch(batch) {
410
+ const results = await Promise.allSettled(this.exporters.map(async (exporter)=>{
411
+ await exporter.emit(batch);
412
+ return exporter.name;
413
+ }));
414
+ for (const [index, result] of results.entries()){
415
+ const exporterName = this.exporters[index]?.name || `exporter-${index}`;
416
+ if ('rejected' === result.status) {
417
+ this.markExporterFailure(exporterName, result.reason);
418
+ continue;
419
+ }
420
+ this.markExporterHealthy(exporterName);
421
+ }
422
+ }
423
+ buildStartupProbeEnvelope() {
424
+ return {
425
+ timestamp: Date.now(),
426
+ service: this.service,
427
+ module: this.module,
428
+ environment: this.environment,
429
+ signalType: 'log',
430
+ name: 'telemetry.exporter.startup_probe',
431
+ level: 'info',
432
+ tags: {
433
+ phase: 'startup'
434
+ },
435
+ attributes: {
436
+ source: 'TelemetryRegistry'
437
+ }
438
+ };
439
+ }
440
+ async startupHealthCheck(options) {
441
+ if (0 === this.exporters.length) return;
442
+ const probeBatch = [
443
+ this.buildStartupProbeEnvelope()
444
+ ];
445
+ const failedExporters = [];
446
+ await Promise.all(this.exporters.map(async (exporter)=>{
447
+ try {
448
+ await exporter.emit(probeBatch);
449
+ this.markExporterHealthy(exporter.name);
450
+ } catch (error) {
451
+ this.markExporterFailure(exporter.name, error);
452
+ const status = this.exporterHealth.get(exporter.name);
453
+ if (status) failedExporters.push({
454
+ ...status
455
+ });
456
+ }
457
+ }));
458
+ if ((options?.failLoud ?? true) && failedExporters.length > 0) throw new TelemetryStartupHealthError(failedExporters);
459
+ }
460
+ getExporterHealth() {
461
+ return Array.from(this.exporterHealth.values()).map((item)=>({
462
+ ...item
463
+ }));
464
+ }
465
+ getQueueStats() {
466
+ return {
467
+ depth: this.queue.length,
468
+ capacity: this.maxQueueSize,
469
+ utilization: this.queue.length / this.maxQueueSize,
470
+ pendingDropped: this.droppedCount,
471
+ totalDropped: this.totalDroppedCount
472
+ };
473
+ }
474
+ async flushInternal() {
475
+ const queueDepthBeforeFlush = this.queue.length;
476
+ if (queueDepthBeforeFlush > 0) {
477
+ this.queue.unshift(this.buildQueueUtilizationEnvelope(queueDepthBeforeFlush));
478
+ this.queue.unshift(this.buildQueueDepthEnvelope(queueDepthBeforeFlush));
479
+ }
480
+ if (this.droppedCount > 0) {
481
+ const droppedCount = this.droppedCount;
482
+ this.droppedCount = 0;
483
+ this.queue.unshift(this.buildDroppedEnvelope(droppedCount));
484
+ }
485
+ if (0 === this.queue.length) return;
486
+ if (0 === this.exporters.length) {
487
+ this.queue.length = 0;
488
+ return;
489
+ }
490
+ while(this.queue.length > 0){
491
+ const batch = this.queue.splice(0, this.maxBatchSize);
492
+ await this.emitBatch(batch);
493
+ }
494
+ await Promise.allSettled(this.exporters.map(async (exporter)=>{
495
+ if (exporter.flush) await exporter.flush();
496
+ }));
497
+ }
498
+ flush() {
499
+ if (this.flushing) return this.flushing;
500
+ this.flushing = this.flushInternal().finally(()=>{
501
+ this.flushing = null;
502
+ });
503
+ return this.flushing;
504
+ }
505
+ async shutdown() {
506
+ if (this.flushTimer) clearInterval(this.flushTimer);
507
+ await this.flush();
508
+ await Promise.allSettled(this.exporters.map(async (exporter)=>{
509
+ if (exporter.shutdown) await exporter.shutdown();
510
+ }));
511
+ }
512
+ constructor(options){
513
+ this.exporters = [];
514
+ this.queue = [];
515
+ this.droppedCount = 0;
516
+ this.totalDroppedCount = 0;
517
+ this.flushing = null;
518
+ this.exporterHealth = new Map();
519
+ this.lastSloAlertAt = new Map();
520
+ this.service = options.service;
521
+ this.module = options.module;
522
+ this.environment = options.environment;
523
+ this.samplingRate = clamp(options.samplingRate ?? 1, 0, 1);
524
+ this.maxBatchSize = Math.max(1, options.maxBatchSize ?? 50);
525
+ this.maxQueueSize = Math.max(1, options.maxQueueSize ?? 1000);
526
+ this.flushIntervalMs = Math.max(50, options.flushIntervalMs ?? 1000);
527
+ this.redactionKeys = new Set(options.redactionKeys || []);
528
+ this.queueUtilizationWarnThreshold = clamp(options.slo?.queueUtilizationWarnThreshold ?? 0.8, 0, 1);
529
+ this.queueDroppedWarnThreshold = Math.max(1, options.slo?.queueDroppedWarnThreshold ?? 1);
530
+ this.alertCooldownMs = Math.max(0, options.slo?.alertCooldownMs ?? 60000);
531
+ this.onSloAlert = options.slo?.onAlert;
532
+ this.flushTimer = setInterval(()=>{
533
+ this.flush();
534
+ }, this.flushIntervalMs);
535
+ if ('function' == typeof this.flushTimer.unref) this.flushTimer.unref();
536
+ }
537
+ }
538
+ class TelemetryCanaryOrchestrator {
539
+ setRequiredContractGates(gates) {
540
+ this.requiredContractGates = Array.from(new Set(gates.map((item)=>item.trim()).filter(Boolean)));
541
+ }
542
+ addRequiredContractGate(name) {
543
+ const normalizedName = name.trim();
544
+ if (!normalizedName) return;
545
+ if (!this.requiredContractGates.includes(normalizedName)) this.requiredContractGates.push(normalizedName);
546
+ }
547
+ setContractGate(name, passed, reason) {
548
+ this.contractGates.set(name, {
549
+ name,
550
+ passed,
551
+ reason,
552
+ updatedAt: Date.now()
553
+ });
554
+ }
555
+ setContractGates(gates) {
556
+ for (const [name, value] of Object.entries(gates)){
557
+ if ('boolean' == typeof value) {
558
+ this.setContractGate(name, value);
559
+ continue;
560
+ }
561
+ this.setContractGate(name, value.passed, value.reason);
562
+ }
563
+ }
564
+ resetToCanary() {
565
+ this.state = 'canary';
566
+ this.consecutiveHealthy = 0;
567
+ this.consecutiveFailures = 0;
568
+ }
569
+ collectFailures() {
570
+ const failures = [];
571
+ const queueStats = this.registry.getQueueStats();
572
+ const unhealthyExporterCount = this.registry.getExporterHealth().filter((item)=>!item.healthy).length;
573
+ if (queueStats.utilization > this.maxQueueUtilization) failures.push({
574
+ reason: 'queue_utilization',
575
+ threshold: this.maxQueueUtilization,
576
+ value: queueStats.utilization
577
+ });
578
+ if (queueStats.totalDropped > this.maxTotalDropped) failures.push({
579
+ reason: 'queue_dropped',
580
+ threshold: this.maxTotalDropped,
581
+ value: queueStats.totalDropped
582
+ });
583
+ if (unhealthyExporterCount > this.maxUnhealthyExporters) failures.push({
584
+ reason: 'unhealthy_exporter',
585
+ threshold: this.maxUnhealthyExporters,
586
+ value: unhealthyExporterCount
587
+ });
588
+ for (const gateName of this.requiredContractGates){
589
+ const gate = this.contractGates.get(gateName);
590
+ if (!gate) {
591
+ failures.push({
592
+ reason: 'contract_gate_missing',
593
+ gate: gateName,
594
+ message: `Contract gate "${gateName}" is missing`
595
+ });
596
+ continue;
597
+ }
598
+ if (!gate.passed) failures.push({
599
+ reason: 'contract_gate_failed',
600
+ gate: gateName,
601
+ message: gate.reason || `Contract gate "${gateName}" is not passing`
602
+ });
603
+ }
604
+ return {
605
+ failures,
606
+ queueStats,
607
+ unhealthyExporterCount
608
+ };
609
+ }
610
+ evaluate() {
611
+ const now = Date.now();
612
+ const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
613
+ let action = 'hold';
614
+ if (failures.length > 0) {
615
+ this.consecutiveHealthy = 0;
616
+ this.consecutiveFailures += 1;
617
+ if ('rolled_back' !== this.state && this.consecutiveFailures >= this.rollbackConsecutiveFailures) {
618
+ this.state = 'rolled_back';
619
+ action = 'rollback';
620
+ }
621
+ } else {
622
+ this.consecutiveFailures = 0;
623
+ this.consecutiveHealthy += 1;
624
+ if ('canary' === this.state && this.consecutiveHealthy >= this.minConsecutiveHealthyEvaluations) {
625
+ this.state = 'promoted';
626
+ action = 'promote';
627
+ }
628
+ }
629
+ const decision = {
630
+ timestamp: now,
631
+ action,
632
+ state: this.state,
633
+ consecutiveHealthy: this.consecutiveHealthy,
634
+ consecutiveFailures: this.consecutiveFailures,
635
+ failures,
636
+ queueStats,
637
+ unhealthyExporterCount,
638
+ contractGates: Array.from(this.contractGates.values()).map((item)=>({
639
+ ...item
640
+ }))
641
+ };
642
+ try {
643
+ this.onEvaluate?.(decision);
644
+ } catch (_error) {}
645
+ if ('promote' === action) try {
646
+ this.onPromote?.(decision);
647
+ } catch (_error) {}
648
+ if ('rollback' === action) try {
649
+ this.onRollback?.(decision);
650
+ } catch (_error) {}
651
+ return decision;
652
+ }
653
+ getStatusSnapshot() {
654
+ const now = Date.now();
655
+ const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
656
+ return {
657
+ timestamp: now,
658
+ state: this.state,
659
+ consecutiveHealthy: this.consecutiveHealthy,
660
+ consecutiveFailures: this.consecutiveFailures,
661
+ queueStats,
662
+ unhealthyExporterCount,
663
+ requiredContractGates: [
664
+ ...this.requiredContractGates
665
+ ],
666
+ contractGates: Array.from(this.contractGates.values()).map((item)=>({
667
+ ...item
668
+ })),
669
+ failurePreview: failures
670
+ };
671
+ }
672
+ start() {
673
+ if (this.evaluationTimer) return;
674
+ this.evaluationTimer = setInterval(()=>{
675
+ this.evaluate();
676
+ }, this.evaluationIntervalMs);
677
+ if ('function' == typeof this.evaluationTimer.unref) this.evaluationTimer.unref();
678
+ }
679
+ stop() {
680
+ if (this.evaluationTimer) {
681
+ clearInterval(this.evaluationTimer);
682
+ this.evaluationTimer = void 0;
683
+ }
684
+ }
685
+ constructor(options){
686
+ this.requiredContractGates = [];
687
+ this.contractGates = new Map();
688
+ this.state = 'canary';
689
+ this.consecutiveHealthy = 0;
690
+ this.consecutiveFailures = 0;
691
+ this.registry = options.registry;
692
+ this.evaluationIntervalMs = Math.max(250, options.evaluationIntervalMs ?? 15000);
693
+ this.minConsecutiveHealthyEvaluations = Math.max(1, options.minConsecutiveHealthyEvaluations ?? 3);
694
+ this.rollbackConsecutiveFailures = Math.max(1, options.rollbackConsecutiveFailures ?? 2);
695
+ this.maxQueueUtilization = clamp(options.maxQueueUtilization ?? 0.8, 0, 1);
696
+ this.maxTotalDropped = Math.max(0, options.maxTotalDropped ?? 0);
697
+ this.maxUnhealthyExporters = Math.max(0, options.maxUnhealthyExporters ?? 0);
698
+ this.setRequiredContractGates(options.requiredContractGates || []);
699
+ this.onEvaluate = options.onEvaluate;
700
+ this.onPromote = options.onPromote;
701
+ this.onRollback = options.onRollback;
702
+ }
703
+ }
704
+ function normalizeMetricsInput(prefixOrTags, tags) {
705
+ if ('string' == typeof prefixOrTags) return {
706
+ prefix: prefixOrTags,
707
+ tags: tags || {}
708
+ };
709
+ if (isRecord(prefixOrTags)) return {
710
+ prefix: void 0,
711
+ tags: prefixOrTags
712
+ };
713
+ return {
714
+ prefix: void 0,
715
+ tags: tags || {}
716
+ };
717
+ }
718
+ function normalizeMetricName(name, prefix) {
719
+ return prefix && prefix.length > 0 ? `${prefix}.${name}` : name;
720
+ }
721
+ function toTelemetryMetricTags(tags) {
722
+ const output = {};
723
+ for (const [key, value] of Object.entries(tags))if (null != value) output[key] = String(value);
724
+ return output;
725
+ }
726
+ function getTraceContext(tags) {
727
+ const traceId = 'string' == typeof tags.trace_id ? tags.trace_id : 'string' == typeof tags.traceId ? tags.traceId : void 0;
728
+ const spanId = 'string' == typeof tags.span_id ? tags.span_id : 'string' == typeof tags.spanId ? tags.spanId : void 0;
729
+ const parentSpanId = 'string' == typeof tags.parent_span_id ? tags.parent_span_id : 'string' == typeof tags.parentSpanId ? tags.parentSpanId : void 0;
730
+ return {
731
+ traceId,
732
+ spanId,
733
+ parentSpanId
734
+ };
735
+ }
736
+ const createTelemetryAwareMetrics = (baseMetrics, registry)=>{
737
+ const emitCounter = (name, value, prefixOrTags, tags)=>{
738
+ const normalized = normalizeMetricsInput(prefixOrTags, tags);
739
+ baseMetrics.emitCounter(name, value, normalized.prefix, normalized.tags);
740
+ try {
741
+ const metricName = normalizeMetricName(name, normalized.prefix);
742
+ const traceContext = getTraceContext(normalized.tags);
743
+ registry.enqueueMetric({
744
+ name: metricName,
745
+ value,
746
+ unit: 'count',
747
+ traceId: traceContext.traceId,
748
+ spanId: traceContext.spanId,
749
+ parentSpanId: traceContext.parentSpanId,
750
+ tags: toTelemetryMetricTags(normalized.tags),
751
+ attributes: normalized.tags
752
+ });
753
+ } catch (_error) {}
754
+ };
755
+ const emitTimer = (name, value, prefixOrTags, tags)=>{
756
+ const normalized = normalizeMetricsInput(prefixOrTags, tags);
757
+ baseMetrics.emitTimer(name, value, normalized.prefix, normalized.tags);
758
+ try {
759
+ const metricName = normalizeMetricName(name, normalized.prefix);
760
+ const traceContext = getTraceContext(normalized.tags);
761
+ registry.enqueueMetric({
762
+ name: metricName,
763
+ value,
764
+ unit: 'ms',
765
+ traceId: traceContext.traceId,
766
+ spanId: traceContext.spanId,
767
+ parentSpanId: traceContext.parentSpanId,
768
+ tags: toTelemetryMetricTags(normalized.tags),
769
+ attributes: normalized.tags
770
+ });
771
+ } catch (_error) {}
772
+ };
773
+ return {
774
+ ...baseMetrics,
775
+ emitCounter,
776
+ emitTimer
777
+ };
778
+ };
779
+ function resolveRuntimeFallbackSignalEndpoint(configuredEndpoint) {
780
+ const rawEndpoint = configuredEndpoint?.trim();
781
+ if (!rawEndpoint) return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
782
+ if (rawEndpoint.startsWith('/')) return rawEndpoint;
783
+ try {
784
+ return new URL(rawEndpoint).pathname || DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
785
+ } catch (_error) {
786
+ return `/${rawEndpoint.replace(/^\/+/, '')}`;
787
+ }
788
+ }
789
+ function createRuntimeSignalError(message, code) {
790
+ const error = new Error(message);
791
+ error.code = code;
792
+ return error;
793
+ }
794
+ function getUtf8ByteLength(input) {
795
+ if ("u" > typeof Buffer) return Buffer.byteLength(input);
796
+ return new TextEncoder().encode(input).length;
797
+ }
798
+ function normalizeRuntimeSignalOrigin(value) {
799
+ if ('string' != typeof value || 0 === value.trim().length) return;
800
+ try {
801
+ return new URL(value).origin;
802
+ } catch (_error) {
803
+ return;
804
+ }
805
+ }
806
+ function normalizeRuntimeSignalAppName(payload) {
807
+ if ('string' != typeof payload.appName) return 'unknown';
808
+ const normalized = payload.appName.trim();
809
+ return normalized.length > 0 ? normalized : 'unknown';
810
+ }
811
+ function normalizeRuntimeSignalRuntimeDigest(payload) {
812
+ if ('string' == typeof payload.runtimeDigest && payload.runtimeDigest.trim()) return payload.runtimeDigest.trim();
813
+ const metadata = payload.metadata;
814
+ if (metadata && 'object' == typeof metadata && !Array.isArray(metadata) && 'string' == typeof metadata.runtimeDigest) {
815
+ const digest = String(metadata.runtimeDigest).trim();
816
+ if (digest) return digest;
817
+ }
818
+ }
819
+ function normalizeRuntimeFallbackSignalAuthConfig(configured) {
820
+ const headerName = 'string' == typeof configured?.headerName && configured.headerName.trim() ? configured.headerName.trim().toLowerCase() : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
821
+ const expectedFromEnv = 'string' == typeof configured?.expectedValueEnv && configured.expectedValueEnv.trim().length > 0 ? process.env[configured.expectedValueEnv.trim()] : void 0;
822
+ const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
823
+ const expectedValue = expectedFromConfig || expectedFromEnv;
824
+ const enabled = configured?.enabled === true;
825
+ if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled is true but no expected token is configured');
826
+ return {
827
+ enabled,
828
+ headerName,
829
+ expectedValue
830
+ };
831
+ }
832
+ function enforceRuntimeFallbackSignalAuthToken(token, authConfig) {
833
+ if (!authConfig.enabled) return;
834
+ if (!token || token !== authConfig.expectedValue) throw createRuntimeSignalError('runtime fallback signal auth failed', 'UNAUTHORIZED');
835
+ }
836
+ function enforceRuntimeFallbackSignalAuth(c, runtimeSignalConfig) {
837
+ enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
838
+ }
839
+ function normalizeRuntimeFallbackTrustPolicy(configured) {
840
+ const allowedApps = Array.isArray(configured?.allowedApps) ? configured.allowedApps.map((item)=>'string' == typeof item ? item.trim() : '').filter(Boolean) : [];
841
+ const allowedEntryOrigins = Array.isArray(configured?.allowedEntryOrigins) ? configured.allowedEntryOrigins.map((item)=>normalizeRuntimeSignalOrigin(item)).filter((item)=>Boolean(item)) : [];
842
+ const expectedRuntimeDigestsRaw = configured?.expectedRuntimeDigests || {};
843
+ const expectedRuntimeDigests = {};
844
+ Object.entries(expectedRuntimeDigestsRaw).forEach(([appName, digest])=>{
845
+ if ('string' == typeof appName && appName.trim().length > 0 && 'string' == typeof digest && digest.trim().length > 0) expectedRuntimeDigests[appName.trim()] = digest.trim();
846
+ });
847
+ return {
848
+ allowedApps,
849
+ allowedEntryOrigins,
850
+ expectedRuntimeDigests,
851
+ enforceRuntimeDigest: configured?.enforceRuntimeDigest === true,
852
+ maxSignalsPerWindow: Math.max(1, Math.floor(configured?.maxSignalsPerWindow ?? DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW)),
853
+ windowMs: Math.max(1000, Math.floor(configured?.windowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS)),
854
+ dedupeWindowMs: Math.max(0, Math.floor(configured?.dedupeWindowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS))
855
+ };
856
+ }
857
+ function createRuntimeFallbackSignalRuntimeState() {
858
+ return {
859
+ rateLimitBySource: new Map(),
860
+ dedupeByFingerprint: new Map()
861
+ };
862
+ }
863
+ function cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy) {
864
+ const dedupeExpiryMs = Math.max(trustPolicy.dedupeWindowMs, trustPolicy.windowMs, 1000);
865
+ runtimeState.dedupeByFingerprint.forEach((lastSeenAt, fingerprint)=>{
866
+ if (now - lastSeenAt > dedupeExpiryMs) runtimeState.dedupeByFingerprint.delete(fingerprint);
867
+ });
868
+ runtimeState.rateLimitBySource.forEach((state, source)=>{
869
+ if (now - state.windowStartedAt > 2 * trustPolicy.windowMs) runtimeState.rateLimitBySource.delete(source);
870
+ });
871
+ }
872
+ function enforceRuntimeFallbackSignalTrustPolicy(payload, runtimeSignalContext) {
873
+ const { trustPolicy, runtimeState } = runtimeSignalContext;
874
+ const now = Date.now();
875
+ cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy);
876
+ const appName = normalizeRuntimeSignalAppName(payload);
877
+ const entryOrigin = normalizeRuntimeSignalOrigin(payload.entry);
878
+ const runtimeDigest = normalizeRuntimeSignalRuntimeDigest(payload);
879
+ if (trustPolicy.allowedApps.length > 0 && !trustPolicy.allowedApps.includes(appName)) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" is not trusted`, 'UNTRUSTED_SOURCE');
880
+ if (trustPolicy.allowedEntryOrigins.length > 0) {
881
+ if (!entryOrigin || !trustPolicy.allowedEntryOrigins.includes(entryOrigin)) throw createRuntimeSignalError(`runtime fallback signal entry origin "${entryOrigin || 'unknown'}" is not trusted`, 'UNTRUSTED_SOURCE');
882
+ }
883
+ const expectedDigest = trustPolicy.expectedRuntimeDigests[appName];
884
+ if (expectedDigest && runtimeDigest !== expectedDigest) throw createRuntimeSignalError(`runtime fallback runtimeDigest mismatch for app "${appName}"`, 'UNTRUSTED_SOURCE');
885
+ if (trustPolicy.enforceRuntimeDigest && !runtimeDigest) throw createRuntimeSignalError(`runtime fallback signal for app "${appName}" is missing runtimeDigest`, 'UNTRUSTED_SOURCE');
886
+ const dedupeFingerprint = JSON.stringify({
887
+ appName,
888
+ entryOrigin: entryOrigin || 'unknown',
889
+ reason: payload.reason || 'runtime_fallback',
890
+ phase: payload.phase || 'unknown',
891
+ runtimeDigest: runtimeDigest || 'unknown'
892
+ });
893
+ const dedupeWindowMs = trustPolicy.dedupeWindowMs;
894
+ if (dedupeWindowMs > 0) {
895
+ const lastSeenAt = runtimeState.dedupeByFingerprint.get(dedupeFingerprint);
896
+ runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
897
+ if ('number' == typeof lastSeenAt && now - lastSeenAt <= dedupeWindowMs) return {
898
+ deduped: true
899
+ };
900
+ } else runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
901
+ const sourceKey = `${appName}@${entryOrigin || 'unknown'}`;
902
+ const rateState = runtimeState.rateLimitBySource.get(sourceKey);
903
+ if (!rateState || now - rateState.windowStartedAt > trustPolicy.windowMs) runtimeState.rateLimitBySource.set(sourceKey, {
904
+ count: 1,
905
+ windowStartedAt: now
906
+ });
907
+ else {
908
+ if (rateState.count >= trustPolicy.maxSignalsPerWindow) throw createRuntimeSignalError(`runtime fallback signal rate-limited for source "${sourceKey}"`, 'RATE_LIMITED');
909
+ rateState.count += 1;
910
+ }
911
+ return {
912
+ deduped: false
913
+ };
914
+ }
915
+ function maybeWarnLegacyOtlpEndpoint(endpoint) {
916
+ if (!endpoint || !endpoint.includes('/v1/metrics')) return;
917
+ console.warn(`[telemetry] OTLP endpoint "${endpoint}" looks like a metrics path. UltraModern telemetry exporter expects log-style envelopes (default: ${DEFAULT_OTLP_ENDPOINT}).`);
918
+ }
919
+ async function parseRuntimeFallbackSignalPayload(c, maxBodyBytes) {
920
+ const contentLengthHeader = c.req.header('content-length');
921
+ if (contentLengthHeader) {
922
+ const contentLength = Number.parseInt(contentLengthHeader, 10);
923
+ if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
924
+ }
925
+ const rawBody = await c.req.raw.text();
926
+ const payload = parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes);
927
+ return {
928
+ rawBody,
929
+ payload
930
+ };
931
+ }
932
+ function parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes) {
933
+ if (!rawBody || 0 === rawBody.trim().length) throw createRuntimeSignalError('runtime fallback signal body is empty', 'INVALID_PAYLOAD');
934
+ if (getUtf8ByteLength(rawBody) > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
935
+ let payload;
936
+ try {
937
+ payload = JSON.parse(rawBody);
938
+ } catch (_error) {
939
+ throw createRuntimeSignalError('runtime fallback signal body must be valid JSON', 'INVALID_PAYLOAD');
940
+ }
941
+ if (!payload || 'object' != typeof payload || Array.isArray(payload)) throw createRuntimeSignalError('runtime fallback signal body must be a JSON object', 'INVALID_PAYLOAD');
942
+ return payload;
943
+ }
944
+ function getRuntimeSignalErrorStatusCode(signalError) {
945
+ if ('PAYLOAD_TOO_LARGE' === signalError.code) return 413;
946
+ if ('INVALID_PAYLOAD' === signalError.code) return 400;
947
+ if ('UNAUTHORIZED' === signalError.code) return 401;
948
+ if ('RATE_LIMITED' === signalError.code) return 429;
949
+ if ('UNTRUSTED_SOURCE' === signalError.code) return 403;
950
+ return 500;
951
+ }
952
+ async function persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
953
+ const now = Date.now();
954
+ const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
955
+ const snapshot = await gateSnapshotStore.readSnapshot() || {};
956
+ const existingGates = snapshot.gates && 'object' == typeof snapshot.gates ? snapshot.gates : {};
957
+ const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
958
+ const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
959
+ const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
960
+ const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
961
+ snapshot.schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
962
+ snapshot.updatedAt = now;
963
+ snapshot.gates = {
964
+ ...existingGates,
965
+ [runtimeSignalConfig.gateName]: {
966
+ passed: false,
967
+ reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
968
+ updatedAt: now,
969
+ expiresAt: now + runtimeSignalConfig.failureHoldMs,
970
+ source: 'runtime-mf-fallback-signal',
971
+ metadata: payload
972
+ }
973
+ };
974
+ await gateSnapshotStore.writeSnapshot(snapshot);
975
+ }
976
+ function emitCanaryDecisionMetric(registry, decision, action) {
977
+ try {
978
+ registry.enqueueMetric({
979
+ name: `telemetry.canary.${action}`,
980
+ value: 1,
981
+ unit: 'count',
982
+ tags: {
983
+ action,
984
+ state: decision.state,
985
+ failures: String(decision.failures.length)
986
+ }
987
+ });
988
+ } catch (_error) {}
989
+ }
990
+ const hasEnabledTelemetryExporters = (config)=>Boolean(config?.exporters?.otlp?.enabled || config?.exporters?.victoriaMetrics?.enabled);
991
+ const injectTelemetryPlugin = ()=>({
992
+ name: '@modern-js/inject-telemetry',
993
+ setup (api) {
994
+ const serverConfig = api.getServerConfig();
995
+ const telemetryConfig = serverConfig?.server?.telemetry;
996
+ if (!telemetryConfig) return;
997
+ if (true !== telemetryConfig.enabled && !hasEnabledTelemetryExporters(telemetryConfig)) return;
998
+ const { middlewares, metaName, appDirectory } = api.getServerContext();
999
+ const serviceName = telemetryConfig.service || metaName || 'modern-js';
1000
+ const moduleName = telemetryConfig.module || 'server';
1001
+ const environmentName = telemetryConfig.environment || process.env.MODERN_ENV || process.env.NODE_ENV || 'development';
1002
+ const registry = new TelemetryRegistry({
1003
+ service: serviceName,
1004
+ module: moduleName,
1005
+ environment: environmentName,
1006
+ samplingRate: telemetryConfig.samplingRate,
1007
+ flushIntervalMs: telemetryConfig.flushIntervalMs,
1008
+ maxBatchSize: telemetryConfig.maxBatchSize,
1009
+ maxQueueSize: telemetryConfig.maxQueueSize,
1010
+ redactionKeys: telemetryConfig.redactionKeys
1011
+ });
1012
+ let canaryOrchestrator;
1013
+ let contractGateAutopilot;
1014
+ let runtimeFallbackSignalConfig;
1015
+ let gateSnapshotStorePromise;
1016
+ const canaryConfig = telemetryConfig.canary;
1017
+ if (canaryConfig?.enabled) {
1018
+ const contractGates = canaryConfig.contractGates;
1019
+ canaryOrchestrator = new TelemetryCanaryOrchestrator({
1020
+ registry,
1021
+ evaluationIntervalMs: canaryConfig.evaluationIntervalMs,
1022
+ minConsecutiveHealthyEvaluations: canaryConfig.minConsecutiveHealthyEvaluations,
1023
+ rollbackConsecutiveFailures: canaryConfig.rollbackConsecutiveFailures,
1024
+ maxQueueUtilization: canaryConfig.maxQueueUtilization,
1025
+ maxTotalDropped: canaryConfig.maxTotalDropped,
1026
+ maxUnhealthyExporters: canaryConfig.maxUnhealthyExporters,
1027
+ requiredContractGates: Object.keys(contractGates || {}),
1028
+ onPromote: (decision)=>{
1029
+ emitCanaryDecisionMetric(registry, decision, 'promote');
1030
+ },
1031
+ onRollback: (decision)=>{
1032
+ emitCanaryDecisionMetric(registry, decision, 'rollback');
1033
+ }
1034
+ });
1035
+ if (contractGates) canaryOrchestrator.setContractGates(contractGates);
1036
+ const autopilotEnabled = canaryConfig.autopilot?.enabled ?? true;
1037
+ if (autopilotEnabled) {
1038
+ const gateSnapshotPath = resolveContractGateSnapshotPath(appDirectory, canaryConfig.autopilot?.gateSnapshotPath);
1039
+ gateSnapshotStorePromise = resolveContractGateSnapshotStore({
1040
+ appDirectory,
1041
+ gateSnapshotPath: gateSnapshotPath || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
1042
+ stateStore: canaryConfig.autopilot?.stateStore
1043
+ });
1044
+ const runtimeSignalConfig = canaryConfig.autopilot?.runtimeFallbackSignal;
1045
+ const runtimeSignalEnabled = runtimeSignalConfig?.enabled ?? true;
1046
+ if (runtimeSignalEnabled && gateSnapshotStorePromise) runtimeFallbackSignalConfig = {
1047
+ endpoint: resolveRuntimeFallbackSignalEndpoint(runtimeSignalConfig?.endpoint),
1048
+ gateName: runtimeSignalConfig?.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
1049
+ gateSnapshotStore: gateSnapshotStorePromise,
1050
+ failureHoldMs: Math.max(1000, runtimeSignalConfig?.failureHoldMs ?? DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS),
1051
+ maxBodyBytes: Math.max(512, runtimeSignalConfig?.maxBodyBytes ?? DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES),
1052
+ auth: normalizeRuntimeFallbackSignalAuthConfig(runtimeSignalConfig?.auth),
1053
+ trustPolicy: normalizeRuntimeFallbackTrustPolicy(runtimeSignalConfig?.trustPolicy),
1054
+ runtimeState: createRuntimeFallbackSignalRuntimeState()
1055
+ };
1056
+ }
1057
+ }
1058
+ if (runtimeFallbackSignalConfig) {
1059
+ const signalConfig = runtimeFallbackSignalConfig;
1060
+ middlewares.push({
1061
+ name: 'telemetry-runtime-fallback-signal',
1062
+ path: signalConfig.endpoint,
1063
+ method: 'post',
1064
+ order: 'pre',
1065
+ handler: async (c)=>{
1066
+ try {
1067
+ enforceRuntimeFallbackSignalAuth(c, signalConfig);
1068
+ const { payload } = await parseRuntimeFallbackSignalPayload(c, signalConfig.maxBodyBytes);
1069
+ const trustResult = enforceRuntimeFallbackSignalTrustPolicy(payload, signalConfig);
1070
+ if (trustResult.deduped) return c.json({
1071
+ ok: true,
1072
+ deduped: true
1073
+ }, 202);
1074
+ await persistRuntimeFallbackContractGate(payload, signalConfig);
1075
+ return c.json({
1076
+ ok: true
1077
+ }, 202);
1078
+ } catch (error) {
1079
+ const signalError = error;
1080
+ const status = getRuntimeSignalErrorStatusCode(signalError);
1081
+ return c.json({
1082
+ ok: false,
1083
+ error: signalError instanceof Error ? signalError.message : String(signalError)
1084
+ }, status);
1085
+ }
1086
+ }
1087
+ });
1088
+ }
1089
+ middlewares.push({
1090
+ name: 'telemetry-runtime-status',
1091
+ path: DEFAULT_RUNTIME_STATUS_ENDPOINT,
1092
+ method: 'get',
1093
+ order: 'pre',
1094
+ handler: async (c)=>{
1095
+ try {
1096
+ if (runtimeFallbackSignalConfig?.auth.enabled) enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeFallbackSignalConfig.auth.headerName), runtimeFallbackSignalConfig.auth);
1097
+ return c.json({
1098
+ ok: true,
1099
+ timestamp: Date.now(),
1100
+ telemetry: {
1101
+ queueStats: registry.getQueueStats(),
1102
+ exporterHealth: registry.getExporterHealth()
1103
+ },
1104
+ canary: canaryOrchestrator ? {
1105
+ enabled: true,
1106
+ ...canaryOrchestrator.getStatusSnapshot()
1107
+ } : {
1108
+ enabled: false
1109
+ },
1110
+ runtimeFallbackSignal: runtimeFallbackSignalConfig ? {
1111
+ enabled: true,
1112
+ endpoint: runtimeFallbackSignalConfig.endpoint,
1113
+ gateName: runtimeFallbackSignalConfig.gateName,
1114
+ failureHoldMs: runtimeFallbackSignalConfig.failureHoldMs,
1115
+ maxBodyBytes: runtimeFallbackSignalConfig.maxBodyBytes,
1116
+ auth: {
1117
+ enabled: runtimeFallbackSignalConfig.auth.enabled,
1118
+ headerName: runtimeFallbackSignalConfig.auth.headerName
1119
+ },
1120
+ trustPolicy: {
1121
+ allowedApps: runtimeFallbackSignalConfig.trustPolicy.allowedApps,
1122
+ allowedEntryOrigins: runtimeFallbackSignalConfig.trustPolicy.allowedEntryOrigins,
1123
+ enforceRuntimeDigest: runtimeFallbackSignalConfig.trustPolicy.enforceRuntimeDigest,
1124
+ expectedRuntimeDigestsCount: Object.keys(runtimeFallbackSignalConfig.trustPolicy.expectedRuntimeDigests).length,
1125
+ maxSignalsPerWindow: runtimeFallbackSignalConfig.trustPolicy.maxSignalsPerWindow,
1126
+ windowMs: runtimeFallbackSignalConfig.trustPolicy.windowMs,
1127
+ dedupeWindowMs: runtimeFallbackSignalConfig.trustPolicy.dedupeWindowMs
1128
+ }
1129
+ } : {
1130
+ enabled: false
1131
+ }
1132
+ });
1133
+ } catch (error) {
1134
+ const signalError = error;
1135
+ return c.json({
1136
+ ok: false,
1137
+ error: signalError instanceof Error ? signalError.message : String(signalError)
1138
+ }, getRuntimeSignalErrorStatusCode(signalError));
1139
+ }
1140
+ }
1141
+ });
1142
+ middlewares.push({
1143
+ name: 'inject-telemetry',
1144
+ handler: async (c, next)=>{
1145
+ const monitors = c.get('monitors');
1146
+ if (monitors) {
1147
+ const traceContext = parseTraceparent(c.req.header('traceparent'));
1148
+ const monitor = (event)=>{
1149
+ registry.enqueue(toTelemetryEnvelope(event, {
1150
+ service: serviceName,
1151
+ module: moduleName,
1152
+ environment: environmentName,
1153
+ traceId: traceContext?.traceId,
1154
+ spanId: traceContext?.spanId,
1155
+ attributes: {
1156
+ requestMethod: c.req.method,
1157
+ requestPath: c.req.path
1158
+ }
1159
+ }));
1160
+ };
1161
+ monitors.push(monitor);
1162
+ }
1163
+ await next();
1164
+ }
1165
+ });
1166
+ let prepared = false;
1167
+ api.onPrepare(async ()=>{
1168
+ if (prepared) return;
1169
+ prepared = true;
1170
+ if (telemetryConfig.exporters?.otlp?.enabled) {
1171
+ maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
1172
+ await registry.register(createOtlpTelemetryExporter(telemetryConfig.exporters.otlp));
1173
+ }
1174
+ if (telemetryConfig.exporters?.victoriaMetrics?.enabled) await registry.register(createVictoriaMetricsTelemetryExporter(telemetryConfig.exporters.victoriaMetrics));
1175
+ await registry.startupHealthCheck({
1176
+ failLoud: telemetryConfig.failLoudStartup ?? true
1177
+ });
1178
+ if (!canaryOrchestrator) return;
1179
+ canaryOrchestrator.start();
1180
+ if (gateSnapshotStorePromise) {
1181
+ const gateSnapshotStore = await gateSnapshotStorePromise;
1182
+ contractGateAutopilot = new ContractGateAutopilot({
1183
+ orchestrator: canaryOrchestrator,
1184
+ gateSnapshotPath: resolveContractGateSnapshotPath(appDirectory, canaryConfig?.autopilot?.gateSnapshotPath),
1185
+ gateSnapshotStore,
1186
+ pollIntervalMs: canaryConfig?.autopilot?.pollIntervalMs,
1187
+ gateStaleAfterMs: canaryConfig?.autopilot?.gateStaleAfterMs
1188
+ });
1189
+ }
1190
+ if (contractGateAutopilot) await contractGateAutopilot.start();
1191
+ canaryOrchestrator.evaluate();
1192
+ });
1193
+ }
1194
+ });
1195
+ export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, hasEnabledTelemetryExporters, injectTelemetryPlugin, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayloadFromRawBody, resolveRuntimeFallbackSignalEndpoint };