@timber-js/app 0.2.0-alpha.235 → 0.2.0-alpha.236

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 (265) hide show
  1. package/dist/_chunks/{actions-CYjRMpZI.js → actions-Top9GftB.js} +3 -3
  2. package/dist/_chunks/{actions-CYjRMpZI.js.map → actions-Top9GftB.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-BZJNt01a.js → cache-api-Bo8c7XVF.js} +6 -6
  4. package/dist/_chunks/{cache-api-BZJNt01a.js.map → cache-api-Bo8c7XVF.js.map} +1 -1
  5. package/dist/_chunks/{chains-D-RRc7CM.js → chains-BsGKkMTK.js} +2 -2
  6. package/dist/_chunks/{chains-D-RRc7CM.js.map → chains-BsGKkMTK.js.map} +1 -1
  7. package/dist/_chunks/chains-DHmoKxkO.js +1 -0
  8. package/dist/_chunks/{classify-_W0RWa5w.js → classify-cmE0Gins.js} +2 -2
  9. package/dist/_chunks/{classify-_W0RWa5w.js.map → classify-cmE0Gins.js.map} +1 -1
  10. package/dist/_chunks/{cli-check-Dl3yo3Zv.js → cli-check-BwiahbTC.js} +3 -3
  11. package/dist/_chunks/{cli-check-Dl3yo3Zv.js.map → cli-check-BwiahbTC.js.map} +1 -1
  12. package/dist/_chunks/{cli-schema-sync-CyrOHbAo.js → cli-schema-sync-B2ldclRO.js} +2 -2
  13. package/dist/_chunks/{cli-schema-sync-CyrOHbAo.js.map → cli-schema-sync-B2ldclRO.js.map} +1 -1
  14. package/dist/_chunks/{cli-schema-sync-CTWiBMZZ.js → cli-schema-sync-Brw7kTmm.js} +1 -1
  15. package/dist/_chunks/{client-dep-entries-C9hv-3k9.js → client-dep-entries-C1nMlLKV.js} +2 -2
  16. package/dist/_chunks/{client-dep-entries-C9hv-3k9.js.map → client-dep-entries-C1nMlLKV.js.map} +1 -1
  17. package/dist/_chunks/{cloudflare-_2fhxQE8.js → cloudflare-Dk5Hqo-O.js} +3 -3
  18. package/dist/_chunks/{cloudflare-_2fhxQE8.js.map → cloudflare-Dk5Hqo-O.js.map} +1 -1
  19. package/dist/_chunks/{convention-lint-D54k6uUM.js → convention-lint-CLpuzY5h.js} +3 -3
  20. package/dist/_chunks/{convention-lint-D54k6uUM.js.map → convention-lint-CLpuzY5h.js.map} +1 -1
  21. package/dist/_chunks/dev-server-BGGGhHXx.js +1 -0
  22. package/dist/_chunks/{dev-server-cmWVDgTf.js → dev-server-lrdpD7Ws.js} +121 -5
  23. package/dist/_chunks/dev-server-lrdpD7Ws.js.map +1 -0
  24. package/dist/_chunks/{dev-span-_NzMX-au.js → dev-span-RsVeYYc_.js} +5 -2
  25. package/dist/_chunks/dev-span-RsVeYYc_.js.map +1 -0
  26. package/dist/_chunks/{error-boundary-Cf1m-Ywk.js → error-boundary-Bh-egWUI.js} +6 -6
  27. package/dist/_chunks/{error-boundary-Cf1m-Ywk.js.map → error-boundary-Bh-egWUI.js.map} +1 -1
  28. package/dist/_chunks/{flight-source-node-BGanuoSS.js → flight-source-node-BO_xD9jC.js} +2 -2
  29. package/dist/_chunks/{flight-source-node-BGanuoSS.js.map → flight-source-node-BO_xD9jC.js.map} +1 -1
  30. package/dist/_chunks/{href-BtspoNc9.js → href-8l5VD23D.js} +2 -2
  31. package/dist/_chunks/{href-BtspoNc9.js.map → href-8l5VD23D.js.map} +1 -1
  32. package/dist/_chunks/{json-lossy-check-BXM45k8p.js → json-lossy-check-D47R9Fp5.js} +2 -2
  33. package/dist/_chunks/{json-lossy-check-BXM45k8p.js.map → json-lossy-check-D47R9Fp5.js.map} +1 -1
  34. package/dist/_chunks/{live-graph-C7-yA8W9.js → live-graph-ChuFfmLi.js} +4 -4
  35. package/dist/_chunks/{live-graph-C7-yA8W9.js.map → live-graph-ChuFfmLi.js.map} +1 -1
  36. package/dist/_chunks/{logger-YtMSKfft.js → logger-DDLtp5e-.js} +16 -1
  37. package/dist/_chunks/logger-DDLtp5e-.js.map +1 -0
  38. package/dist/_chunks/navigation-root-Cvb7P1ud.js.map +1 -1
  39. package/dist/_chunks/{node-response-D3hXWb8y.js → node-response-DNNnKnoS.js} +2 -2
  40. package/dist/_chunks/{node-response-D3hXWb8y.js.map → node-response-DNNnKnoS.js.map} +1 -1
  41. package/dist/_chunks/{poison-scan-CRSP06Es.js → poison-scan-CJ9QfJWb.js} +2 -2
  42. package/dist/_chunks/{poison-scan-CRSP06Es.js.map → poison-scan-CJ9QfJWb.js.map} +1 -1
  43. package/dist/_chunks/{scanner-BNQ4qnLX.js → scanner-CrB_h6FA.js} +5 -5
  44. package/dist/_chunks/{scanner-BNQ4qnLX.js.map → scanner-CrB_h6FA.js.map} +1 -1
  45. package/dist/_chunks/{sizeof-Cmx6Fs-Y.js → sizeof-DVhEVN_y.js} +2 -2
  46. package/dist/_chunks/{sizeof-Cmx6Fs-Y.js.map → sizeof-DVhEVN_y.js.map} +1 -1
  47. package/dist/_chunks/{walkers-DFC9KsBL.js → walkers-BUvpsb2Q.js} +3 -3
  48. package/dist/_chunks/{walkers-DFC9KsBL.js.map → walkers-BUvpsb2Q.js.map} +1 -1
  49. package/dist/adapters/cloudflare-dev.js +1 -1
  50. package/dist/adapters/cloudflare-kv-cache.js +2 -2
  51. package/dist/adapters/cloudflare.js +1 -1
  52. package/dist/adapters/nitro.js +1 -1
  53. package/dist/analyze/crawl-entry.js +3 -3
  54. package/dist/analyze/graph-command.js +3 -3
  55. package/dist/cache/index.js +2 -2
  56. package/dist/cache/stores/memory.js +1 -1
  57. package/dist/cli.js +3 -3
  58. package/dist/client/dev-pill/index.d.ts +2 -1
  59. package/dist/client/dev-pill/index.d.ts.map +1 -1
  60. package/dist/client/dev-pill/view.d.ts.map +1 -1
  61. package/dist/client/error-boundary.js +1 -1
  62. package/dist/client/index.js +4 -4
  63. package/dist/client/internal.js +3 -3
  64. package/dist/cookies/index.js +1 -1
  65. package/dist/dev-tools/await-span.d.ts +7 -0
  66. package/dist/dev-tools/await-span.d.ts.map +1 -1
  67. package/dist/dev-tools/instrumentation.d.ts.map +1 -1
  68. package/dist/dev-tools/logger.d.ts +8 -2
  69. package/dist/dev-tools/logger.d.ts.map +1 -1
  70. package/dist/dev-tools/span-sink.d.ts +9 -1
  71. package/dist/dev-tools/span-sink.d.ts.map +1 -1
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +73 -31
  74. package/dist/index.js.map +1 -1
  75. package/dist/native/rsc/_react/chunks/{react-server-dom-webpack-server.node.development-hQ_odxIB.js → react-server-dom-webpack-server.node.development-CAttMzVD.js} +2 -2
  76. package/dist/native/rsc/_react/flight-client.js +2 -2
  77. package/dist/native/rsc/_react/flight-server.js +1 -1
  78. package/dist/native/rsc/_react/flight-static.js +1 -1
  79. package/dist/native/rsc/adapters/cloudflare-kv-cache.js +1 -1
  80. package/dist/native/rsc/adapters/cloudflare.js +2 -2
  81. package/dist/native/rsc/cache/cache-api.js +3 -3
  82. package/dist/native/rsc/cache/index.js +3 -3
  83. package/dist/native/rsc/cache/timber-cache.js +2 -2
  84. package/dist/native/rsc/cdn/index.js +1 -1
  85. package/dist/native/rsc/client/use-cookie.js +1 -1
  86. package/dist/native/rsc/dev-tools/404-page.js +1 -1
  87. package/dist/native/rsc/dev-tools/await-span.js +5 -2
  88. package/dist/native/rsc/dev-tools/await-span.js.map +1 -1
  89. package/dist/native/rsc/dev-tools/error-page.js +2 -2
  90. package/dist/native/rsc/dev-tools/instrumentation.js +38 -3
  91. package/dist/native/rsc/dev-tools/instrumentation.js.map +1 -1
  92. package/dist/native/rsc/dev-tools/logger.js +123 -80
  93. package/dist/native/rsc/dev-tools/logger.js.map +1 -1
  94. package/dist/native/rsc/dev-tools/span-sink.js +1 -0
  95. package/dist/native/rsc/dev-tools/span-sink.js.map +1 -1
  96. package/dist/native/rsc/dev-tools/terminal.js +1 -1
  97. package/dist/native/rsc/manifest.json +1 -0
  98. package/dist/native/rsc/params/index.js +1 -1
  99. package/dist/native/rsc/routing/collision-probe.js +1 -1
  100. package/dist/native/rsc/routing/interception.js +1 -1
  101. package/dist/native/rsc/search-params/define.js +2 -2
  102. package/dist/native/rsc/server/access-gate.js +1 -1
  103. package/dist/native/rsc/server/action-client.js +2 -2
  104. package/dist/native/rsc/server/action-handler.js +8 -8
  105. package/dist/native/rsc/server/actions.js +3 -3
  106. package/dist/native/rsc/server/children-interception.js +1 -1
  107. package/dist/native/rsc/server/deny-boundary.js +1 -1
  108. package/dist/native/rsc/server/deny-renderer.js +10 -10
  109. package/dist/native/rsc/server/fallback-error.js +1 -1
  110. package/dist/native/rsc/server/flight-injector-core.js +2 -2
  111. package/dist/native/rsc/server/flight-source-node.js +2 -2
  112. package/dist/native/rsc/server/index.js +4 -4
  113. package/dist/native/rsc/server/interception-gates.js +2 -2
  114. package/dist/native/rsc/server/internal.js +15 -15
  115. package/dist/native/rsc/server/logger.js +2 -2
  116. package/dist/native/rsc/server/metadata-route-links.js +1 -1
  117. package/dist/native/rsc/server/node-body-response.js +1 -1
  118. package/dist/native/rsc/server/param-coercion.js +1 -1
  119. package/dist/native/rsc/server/pipeline-helpers.js +10 -10
  120. package/dist/native/rsc/server/pipeline-interception.js +4 -4
  121. package/dist/native/rsc/server/pipeline-metadata-route.js +10 -10
  122. package/dist/native/rsc/server/pipeline-outcome.js +4 -4
  123. package/dist/native/rsc/server/pipeline-phases.js +11 -11
  124. package/dist/native/rsc/server/pipeline.js +10 -10
  125. package/dist/native/rsc/server/prebuilt/capture-render.js +1 -1
  126. package/dist/native/rsc/server/prebuilt/dev-store.js +1 -1
  127. package/dist/native/rsc/server/prebuilt/overlay.js +3 -3
  128. package/dist/native/rsc/server/prebuilt-builder.js +8 -8
  129. package/dist/native/rsc/server/prebuilt-runtime.js +15 -15
  130. package/dist/native/rsc/server/primitives.js +2 -2
  131. package/dist/native/rsc/server/publish-params.js +1 -1
  132. package/dist/native/rsc/server/request-context.js +1 -1
  133. package/dist/native/rsc/server/route-element-builder.js +7 -7
  134. package/dist/native/rsc/server/route-element-helpers.js +1 -1
  135. package/dist/native/rsc/server/route-handler.js +1 -1
  136. package/dist/native/rsc/server/rsc-entry/action-dispatcher.js +1 -1
  137. package/dist/native/rsc/server/rsc-entry/action-middleware-runner.js +1 -1
  138. package/dist/native/rsc/server/rsc-entry/api-handler.js +1 -1
  139. package/dist/native/rsc/server/rsc-entry/deny-fallback.js +6 -6
  140. package/dist/native/rsc/server/rsc-entry/error-renderer.js +7 -7
  141. package/dist/native/rsc/server/rsc-entry/helpers.js +1 -1
  142. package/dist/native/rsc/server/rsc-entry/render-route.js +4 -4
  143. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js +7 -7
  144. package/dist/native/rsc/server/rsc-entry/rsc-payload.js +3 -3
  145. package/dist/native/rsc/server/rsc-entry/rsc-stream.js +6 -6
  146. package/dist/native/rsc/server/rsc-entry/ssr-renderer.js +10 -10
  147. package/dist/native/rsc/server/rsc-error-envelope.js +1 -1
  148. package/dist/native/rsc/server/sitemap-handler.js +1 -1
  149. package/dist/native/rsc/server/skippable-prefix.js +2 -2
  150. package/dist/native/rsc/server/slot-interception.js +1 -1
  151. package/dist/native/rsc/server/slot-resolver.js +11 -11
  152. package/dist/native/rsc/server/static-generator.js +2 -2
  153. package/dist/native/rsc/server/traced-access.js +1 -1
  154. package/dist/native/rsc/server/tracing.js +10 -0
  155. package/dist/native/rsc/server/tracing.js.map +1 -1
  156. package/dist/native/rsc/shared/dev-span.js +8 -2
  157. package/dist/native/rsc/shared/dev-span.js.map +1 -1
  158. package/dist/native/rsc/shared/href.js +1 -1
  159. package/dist/native/rsc/shared/span-waterfall.js +90 -0
  160. package/dist/native/rsc/shared/span-waterfall.js.map +1 -0
  161. package/dist/native/ssr/adapters/cloudflare-kv-cache.js +1 -1
  162. package/dist/native/ssr/adapters/cloudflare.js +2 -2
  163. package/dist/native/ssr/cache/cache-api.js +3 -3
  164. package/dist/native/ssr/cache/guarded-read.js +1 -1
  165. package/dist/native/ssr/cache/index.js +3 -3
  166. package/dist/native/ssr/cache/timber-cache.js +3 -3
  167. package/dist/native/ssr/cdn/index.js +1 -1
  168. package/dist/native/ssr/client/error-boundary.js +1 -1
  169. package/dist/native/ssr/client/index.js +5 -5
  170. package/dist/native/ssr/client/link.js +5 -5
  171. package/dist/native/ssr/client/navigation-commit.js +2 -2
  172. package/dist/native/ssr/client/nuqs-adapter.js +2 -2
  173. package/dist/native/ssr/client/params-context.js +1 -1
  174. package/dist/native/ssr/client/router-skew.js +1 -1
  175. package/dist/native/ssr/client/rsc-fetch.js +2 -2
  176. package/dist/native/ssr/client/use-pending-navigation.js +1 -1
  177. package/dist/native/ssr/client/use-search-params.js +2 -2
  178. package/dist/native/ssr/client/use-segment-params.js +1 -1
  179. package/dist/native/ssr/client/use-selected-layout-segment.js +1 -1
  180. package/dist/native/ssr/dev-tools/await-span.js +5 -2
  181. package/dist/native/ssr/dev-tools/await-span.js.map +1 -1
  182. package/dist/native/ssr/dev-tools/instrumentation.js +38 -3
  183. package/dist/native/ssr/dev-tools/instrumentation.js.map +1 -1
  184. package/dist/native/ssr/dev-tools/logger.js +123 -80
  185. package/dist/native/ssr/dev-tools/logger.js.map +1 -1
  186. package/dist/native/ssr/dev-tools/span-sink.js +1 -0
  187. package/dist/native/ssr/dev-tools/span-sink.js.map +1 -1
  188. package/dist/native/ssr/manifest.json +1 -0
  189. package/dist/native/ssr/params/index.js +1 -1
  190. package/dist/native/ssr/search-params/define.js +2 -2
  191. package/dist/native/ssr/server/access-gate.js +1 -1
  192. package/dist/native/ssr/server/action-client.js +2 -2
  193. package/dist/native/ssr/server/actions.js +3 -3
  194. package/dist/native/ssr/server/deny-boundary.js +2 -2
  195. package/dist/native/ssr/server/flight-injector-core.js +1 -1
  196. package/dist/native/ssr/server/flight-source-node.js +2 -2
  197. package/dist/native/ssr/server/index.js +4 -4
  198. package/dist/native/ssr/server/internal.js +12 -12
  199. package/dist/native/ssr/server/logger.js +2 -2
  200. package/dist/native/ssr/server/node-body-response.js +1 -1
  201. package/dist/native/ssr/server/node-stream-transforms.js +2 -2
  202. package/dist/native/ssr/server/param-coercion.js +3 -3
  203. package/dist/native/ssr/server/pipeline-helpers.js +7 -7
  204. package/dist/native/ssr/server/pipeline-interception.js +4 -4
  205. package/dist/native/ssr/server/pipeline-metadata-route.js +10 -10
  206. package/dist/native/ssr/server/pipeline-outcome.js +4 -4
  207. package/dist/native/ssr/server/pipeline-phases.js +10 -10
  208. package/dist/native/ssr/server/pipeline.js +10 -10
  209. package/dist/native/ssr/server/prebuilt/capture-render.js +2 -2
  210. package/dist/native/ssr/server/prebuilt/dev-store.js +1 -1
  211. package/dist/native/ssr/server/prebuilt/overlay.js +4 -4
  212. package/dist/native/ssr/server/prebuilt-runtime.js +14 -14
  213. package/dist/native/ssr/server/primitives.js +2 -2
  214. package/dist/native/ssr/server/request-context.js +2 -2
  215. package/dist/native/ssr/server/route-handler.js +1 -1
  216. package/dist/native/ssr/server/rsc-error-envelope.js +1 -1
  217. package/dist/native/ssr/server/ssr-form-state.js +2 -2
  218. package/dist/native/ssr/server/ssr-wrappers.js +1 -1
  219. package/dist/native/ssr/server/traced-access.js +1 -1
  220. package/dist/native/ssr/server/tracing.js +10 -0
  221. package/dist/native/ssr/server/tracing.js.map +1 -1
  222. package/dist/native/ssr/shared/dev-span.js +8 -2
  223. package/dist/native/ssr/shared/dev-span.js.map +1 -1
  224. package/dist/native/ssr/shared/href.js +1 -1
  225. package/dist/native/ssr/shared/span-waterfall.js +90 -0
  226. package/dist/native/ssr/shared/span-waterfall.js.map +1 -0
  227. package/dist/plugins/dev-precompile.d.ts +84 -0
  228. package/dist/plugins/dev-precompile.d.ts.map +1 -0
  229. package/dist/plugins/dev-server.d.ts.map +1 -1
  230. package/dist/plugins/entries.d.ts.map +1 -1
  231. package/dist/plugins/virtual-ids.d.ts +16 -0
  232. package/dist/plugins/virtual-ids.d.ts.map +1 -0
  233. package/dist/routes/index.js +1 -1
  234. package/dist/routing/index.js +3 -3
  235. package/dist/search-params/index.js +2 -2
  236. package/dist/server/index.js +2 -2
  237. package/dist/server/internal.js +14 -14
  238. package/dist/server/tracing.d.ts.map +1 -1
  239. package/dist/shared/dev-span.d.ts +12 -1
  240. package/dist/shared/dev-span.d.ts.map +1 -1
  241. package/dist/shared/span-waterfall.d.ts +88 -0
  242. package/dist/shared/span-waterfall.d.ts.map +1 -0
  243. package/package.json +2 -2
  244. package/src/client/dev-pill/index.ts +5 -2
  245. package/src/client/dev-pill/store.ts +1 -1
  246. package/src/client/dev-pill/view.ts +15 -5
  247. package/src/dev-tools/await-span.ts +10 -0
  248. package/src/dev-tools/instrumentation.ts +44 -6
  249. package/src/dev-tools/logger.ts +230 -155
  250. package/src/dev-tools/span-sink.ts +34 -3
  251. package/src/index.ts +21 -11
  252. package/src/plugins/dev-precompile.ts +168 -0
  253. package/src/plugins/dev-server.ts +16 -3
  254. package/src/plugins/entries.ts +1 -11
  255. package/src/plugins/virtual-ids.ts +15 -0
  256. package/src/server/tracing.ts +29 -0
  257. package/src/shared/dev-span.ts +17 -2
  258. package/src/{client/dev-pill/waterfall.ts → shared/span-waterfall.ts} +84 -51
  259. package/dist/_chunks/chains-KblEfYzm.js +0 -1
  260. package/dist/_chunks/dev-server-DrYBIg66.js +0 -1
  261. package/dist/_chunks/dev-server-cmWVDgTf.js.map +0 -1
  262. package/dist/_chunks/dev-span-_NzMX-au.js.map +0 -1
  263. package/dist/_chunks/logger-YtMSKfft.js.map +0 -1
  264. package/dist/client/dev-pill/waterfall.d.ts +0 -64
  265. package/dist/client/dev-pill/waterfall.d.ts.map +0 -1
@@ -31,8 +31,13 @@ import {
31
31
  type DevLoggerConfig,
32
32
  } from './logger.ts';
33
33
  import { forwardSpan } from './span-sink.ts';
34
- import { installDevAwait } from './await-span.ts';
35
- import { AWAIT_SPAN_MIN_MS, AWAIT_SPAN_NAME } from '../shared/dev-span.ts';
34
+ import { installDevAwait, noteTracedWork } from './await-span.ts';
35
+ import {
36
+ AWAIT_SPAN_MIN_MS,
37
+ AWAIT_SPAN_NAME,
38
+ FETCH_BODY_SPAN_NAME,
39
+ FETCH_SPAN_NAME,
40
+ } from '../shared/dev-span.ts';
36
41
 
37
42
  // ─── Fetch Instrumentation ──────────────────────────────────────────────────
38
43
 
@@ -68,7 +73,7 @@ export function instrumentDevFetch(): DevFetchCleanup {
68
73
  const { method, url } = extractFetchInfo(input, init);
69
74
 
70
75
  return tracer.startActiveSpan(
71
- 'timber.fetch',
76
+ FETCH_SPAN_NAME,
72
77
  {
73
78
  attributes: {
74
79
  'http.request.method': method,
@@ -90,6 +95,7 @@ export function instrumentDevFetch(): DevFetchCleanup {
90
95
 
91
96
  span.setStatus({ code: api.SpanStatusCode.OK });
92
97
  span.end();
98
+ traceBodyReads(response, api.trace.setSpan(api.context.active(), span), tracer);
93
99
  return response;
94
100
  } catch (error) {
95
101
  span.setStatus({ code: api.SpanStatusCode.ERROR });
@@ -114,6 +120,39 @@ export function instrumentDevFetch(): DevFetchCleanup {
114
120
  return cleanup;
115
121
  }
116
122
 
123
+ /** The `Response` methods that read the whole body. */
124
+ const BODY_READERS = ['arrayBuffer', 'blob', 'bytes', 'formData', 'json', 'text'] as const;
125
+
126
+ /**
127
+ * Give each body read of `response` a `timber.fetch.body` span under the
128
+ * fetch span (`parent`), and tell the dev await wrapper the read is traced,
129
+ * so `await res.text()` is a wait that span explains rather than a second
130
+ * bar for the same time. Own properties on this one response; a clone, or a
131
+ * body read through `response.body`, is not traced.
132
+ */
133
+ function traceBodyReads(response: Response, parent: Context, tracer: api.Tracer): void {
134
+ for (const reader of BODY_READERS) {
135
+ const read = response[reader];
136
+ if (typeof read !== 'function') continue;
137
+ const traced = (): Promise<unknown> => {
138
+ const span = tracer.startSpan(FETCH_BODY_SPAN_NAME, {}, parent);
139
+ const reading = (async () => {
140
+ try {
141
+ return await read.call(response);
142
+ } catch (error) {
143
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
144
+ throw error;
145
+ } finally {
146
+ span.end();
147
+ }
148
+ })();
149
+ noteTracedWork(reading);
150
+ return reading;
151
+ };
152
+ Object.defineProperty(response, reader, { value: traced, configurable: true, writable: true });
153
+ }
154
+ }
155
+
117
156
  /**
118
157
  * Extract method and URL from the various fetch() call signatures.
119
158
  */
@@ -220,9 +259,8 @@ export class DevSpanProcessor implements SpanProcessor {
220
259
  if (this.mode === 'quiet') return '';
221
260
  if (this.mode === 'json') return formatJson(spans);
222
261
  if (this.mode === 'summary') return formatSpanSummary(spans, this.config);
223
- // Both 'tree' and 'verbose' use the tree formatter.
224
- // verbose will show additional detail (every component render) once
225
- // component-level spans are wired.
262
+ // Both 'tree' and 'verbose' use the tree formatter; tree hides
263
+ // explained waits and folds pass-through awaits, verbose prints every span.
226
264
  return formatSpanTree(spans, this.config);
227
265
  }
228
266
 
@@ -5,8 +5,9 @@
5
5
  * the single source of truth — no separate event system needed.
6
6
  *
7
7
  * Supports five modes:
8
- * - tree (default) — indented tree per request
9
- * - verbose — detailed tree showing every component render
8
+ * - tree (default) — indented tree per request; explained waits hidden,
9
+ * pass-through awaits folded (the dev pill's reading rules)
10
+ * - verbose — the same tree with every span as is
10
11
  * - summary — one line per request
11
12
  * - json — chronological NDJSON dump of all spans
12
13
  * - quiet — no output
@@ -18,7 +19,14 @@ import { STATUS_CODES } from 'node:http';
18
19
  import type { InspectColor } from 'node:util';
19
20
  import { styleText } from 'node:util';
20
21
  import type { ReadableSpan } from '@opentelemetry/sdk-trace-base';
21
- import { devSpanLabel } from '../shared/dev-span.ts';
22
+ import {
23
+ AWAIT_SPAN_NAME,
24
+ devSpanLabel,
25
+ FETCH_BODY_SPAN_NAME,
26
+ FETCH_SPAN_NAME,
27
+ ROOT_SPAN_NAME,
28
+ } from '../shared/dev-span.ts';
29
+ import { buildWaterfall, type WaterfallRow, type WaterfallSpan } from '../shared/span-waterfall.ts';
22
30
 
23
31
  // ─── Configuration ──────────────────────────────────────────────────────────
24
32
 
@@ -74,112 +82,106 @@ function relativeMs(time: HrTime, rootStart: HrTime): number {
74
82
  return hrTimeToMs(time) - hrTimeToMs(rootStart);
75
83
  }
76
84
 
77
- // ─── Span → Tree Mapping ────────────────────────────────────────────────────
85
+ // ─── Span → Rows ────────────────────────────────────────────────────────────
78
86
 
79
- /** Map a span to its display label and environment tag. */
80
- function spanLabel(span: ReadableSpan): { label: string; env: string } {
81
- return devSpanLabel(span.name, span.attributes);
82
- }
83
-
84
- // ─── Tree Node ──────────────────────────────────────────────────────────────
85
-
86
- interface SpanTreeNode {
87
+ /** An OTEL span as the shared waterfall rules read it. */
88
+ interface LogSpan extends WaterfallSpan {
87
89
  span: ReadableSpan;
88
- children: SpanTreeNode[];
89
90
  }
90
91
 
91
- /**
92
- * Build a tree from a flat list of spans using parentSpanId relationships.
93
- */
94
- function buildSpanTree(spans: ReadableSpan[]): {
95
- root: ReadableSpan | null;
96
- children: SpanTreeNode[];
97
- } {
98
- const root = spans.find((s) => s.name === 'http.server.request') ?? null;
99
- if (!root) return { root: null, children: [] };
100
-
101
- // Index spans by spanId for parent lookup
102
- const bySpanId = new Map<string, SpanTreeNode>();
103
- for (const span of spans) {
104
- if (span === root) continue;
105
- bySpanId.set(span.spanContext().spanId, { span, children: [] });
106
- }
107
-
108
- // Build parent-child relationships
109
- const rootChildren: SpanTreeNode[] = [];
110
- for (const node of bySpanId.values()) {
111
- const parentId = node.span.parentSpanContext?.spanId;
112
- if (parentId === root.spanContext().spanId) {
113
- rootChildren.push(node);
114
- } else if (parentId && bySpanId.has(parentId)) {
115
- bySpanId.get(parentId)!.children.push(node);
116
- } else {
117
- // Orphan — attach to root
118
- rootChildren.push(node);
119
- }
120
- }
121
-
122
- // Sort children by start time
123
- const sortByStart = (a: SpanTreeNode, b: SpanTreeNode) =>
124
- hrTimeToMs(a.span.startTime) - hrTimeToMs(b.span.startTime);
125
-
126
- rootChildren.sort(sortByStart);
127
- for (const node of bySpanId.values()) {
128
- node.children.sort(sortByStart);
129
- }
130
-
131
- // Post-process: re-parent layout/page spans into a nested chain.
132
- // React's concurrent rendering breaks OTEL parent chains — all layout/page
133
- // spans end up as direct children of timber.render. Re-nest them based on
134
- // start-time order to reflect the segment hierarchy.
135
- for (const node of bySpanId.values()) {
136
- if (node.span.name !== 'timber.render') continue;
137
- reNestLayoutPageSpans(node);
92
+ /** Items by key, keys in first-seen order. (`Map.groupBy` is ES2024.) */
93
+ function groupBy<T, K>(items: readonly T[], keyOf: (item: T) => K): Map<K, T[]> {
94
+ const groups = new Map<K, T[]>();
95
+ for (const item of items) {
96
+ const key = keyOf(item);
97
+ const group = groups.get(key);
98
+ if (group) group.push(item);
99
+ else groups.set(key, [item]);
138
100
  }
139
-
140
- return { root, children: rootChildren };
101
+ return groups;
141
102
  }
142
103
 
104
+ const LAYOUT = 'timber.layout';
105
+ const PAGE = 'timber.page';
106
+
143
107
  /**
144
- * Re-parent layout and page spans under a render node to form a nested chain.
108
+ * Project the trace's spans for `buildWaterfall()`, with the parent links
109
+ * the tree should draw:
145
110
  *
146
- * Layout/page spans all appear as flat children of timber.render because OTEL
147
- * context doesn't propagate through React's concurrent rendering. We
148
- * reconstruct the hierarchy: each layout becomes the parent of the next
149
- * layout/page span, forming a chain that matches the segment tree.
150
- *
151
- * Non-layout/page children (e.g. access gates, metadata) stay at their
152
- * current depth.
111
+ * - A span whose parent isn't in the trace hangs off the root.
112
+ * - Layout and page spans under a render are re-nested by segment. React's
113
+ * concurrent rendering breaks OTEL parent chains, so they all arrive as
114
+ * direct children of `timber.render`. The main route's layouts form a
115
+ * chain in start order, and its page hangs off the last one. Each parallel
116
+ * slot (`timber.slot`) is its own chain under that same layout: slots
117
+ * render beside the page, not inside each other. Which layout owns a slot
118
+ * isn't recorded, so a slot of an outer layout draws under the innermost
119
+ * one. Other render children (access gates, metadata) stay where they are.
153
120
  */
154
- function reNestLayoutPageSpans(renderNode: SpanTreeNode): void {
155
- const layoutPageNames = new Set(['timber.layout', 'timber.page']);
156
- const layoutPageChildren: SpanTreeNode[] = [];
157
- const otherChildren: SpanTreeNode[] = [];
158
-
159
- for (const child of renderNode.children) {
160
- if (layoutPageNames.has(child.span.name)) {
161
- layoutPageChildren.push(child);
162
- } else {
163
- otherChildren.push(child);
121
+ function toLogSpans(spans: ReadableSpan[], root: ReadableSpan): LogSpan[] {
122
+ const rootId = root.spanContext().spanId;
123
+ const ids = new Set(spans.map((s) => s.spanContext().spanId));
124
+ const nodes = spans.map((span): LogSpan => {
125
+ const parent = span.parentSpanContext?.spanId;
126
+ return {
127
+ span,
128
+ spanId: span.spanContext().spanId,
129
+ parentSpanId: span === root ? undefined : parent && ids.has(parent) ? parent : rootId,
130
+ name: span.name,
131
+ startMs: hrTimeToMs(span.startTime),
132
+ endMs: hrTimeToMs(span.endTime),
133
+ attributes: span.attributes,
134
+ };
135
+ });
136
+ for (const render of nodes) {
137
+ if (render.name !== 'timber.render') continue;
138
+ const segments = nodes
139
+ .filter((n) => n.parentSpanId === render.spanId && (n.name === LAYOUT || n.name === PAGE))
140
+ .sort((a, b) => a.startMs - b.startMs);
141
+ // Main route first (slot ''), so slots have its innermost layout to hang off.
142
+ const bySlot = groupBy(segments, (n) => String(n.attributes['timber.slot'] ?? ''));
143
+ let mainLayout = render.spanId;
144
+ for (const slot of ['', ...[...bySlot.keys()].filter((k) => k !== '')]) {
145
+ let parent = slot === '' ? render.spanId : mainLayout;
146
+ for (const node of bySlot.get(slot) ?? []) {
147
+ node.parentSpanId = parent;
148
+ if (node.name === LAYOUT) parent = node.spanId;
149
+ }
150
+ if (slot === '') mainLayout = parent;
164
151
  }
165
152
  }
153
+ return nodes;
154
+ }
166
155
 
167
- // Nothing to re-nest if 0 or 1 layout/page spans
168
- if (layoutPageChildren.length <= 1) return;
169
-
170
- // Chain them: first layout/page is direct child of render, second is
171
- // child of first, etc. They're already sorted by start time.
172
- for (let i = layoutPageChildren.length - 1; i > 0; i--) {
173
- layoutPageChildren[i - 1]!.children.push(layoutPageChildren[i]!);
174
- }
175
-
176
- // Rebuild render's children: other children + only the first layout/page
177
- renderNode.children = [...otherChildren, layoutPageChildren[0]!];
178
-
179
- // Re-sort by start time
180
- const sortByStart = (a: SpanTreeNode, b: SpanTreeNode) =>
181
- hrTimeToMs(a.span.startTime) - hrTimeToMs(b.span.startTime);
182
- renderNode.children.sort(sortByStart);
156
+ /**
157
+ * Tree connectors for rows in tree order: each row's `├─`/`└─` and the rails
158
+ * of its ancestors. A row is its parent's last child when no sibling follows
159
+ * before the tree climbs back above it.
160
+ */
161
+ function treeConnectors<T>(
162
+ items: readonly T[],
163
+ depthOf: (item: T) => number
164
+ ): Array<{ item: T; prefix: string; connector: string }> {
165
+ const siblingBelow: boolean[] = [];
166
+ const isLast = [...items]
167
+ .reverse()
168
+ .map((item) => {
169
+ const d = depthOf(item);
170
+ const last = !siblingBelow[d];
171
+ siblingBelow[d] = true;
172
+ siblingBelow.length = d + 1;
173
+ return last;
174
+ })
175
+ .reverse();
176
+ const ancestorIsLast: boolean[] = [];
177
+ return items.map((item, i) => {
178
+ const d = depthOf(item);
179
+ let prefix = '';
180
+ for (let level = 0; level < d; level++) prefix += ancestorIsLast[level] ? ' ' : '│ ';
181
+ const last = isLast[i] === true;
182
+ ancestorIsLast[d] = last;
183
+ return { item, prefix, connector: last ? '└─' : '├─' };
184
+ });
183
185
  }
184
186
 
185
187
  // ─── Log Mode Resolution ────────────────────────────────────────────────────
@@ -200,11 +202,39 @@ export function resolveLogMode(config?: DevLoggerConfig): DevLogMode {
200
202
 
201
203
  /**
202
204
  * Format spans as a full indented tree string for stderr.
205
+ *
206
+ * Tree mode applies the dev pill's reading rules (shared/span-waterfall.ts):
207
+ * waits whose work other rows already show are left out, and an await that
208
+ * only wraps one other await or fetch folds into it. Verbose mode prints
209
+ * every span as is.
203
210
  */
204
211
  export function formatSpanTree(spans: ReadableSpan[], config?: DevLoggerConfig): string {
205
212
  const slowPhaseMs = config?.slowPhaseMs ?? 200;
206
- const { root, children } = buildSpanTree(spans);
213
+ const root = spans.find((s) => s.name === ROOT_SPAN_NAME);
207
214
  if (!root) return '';
215
+ const readable = config?.mode !== 'verbose';
216
+ const logSpans = toLogSpans(spans, root);
217
+ // Body reads are drawn on their fetch's line, not as rows of their own.
218
+ const bodies = groupBy(
219
+ logSpans.filter((s) => s.name === FETCH_BODY_SPAN_NAME),
220
+ (s) => s.parentSpanId
221
+ );
222
+ const { rows, hiddenWaits } = buildWaterfall(logSpans, {
223
+ hideWaits: readable,
224
+ fold: readable,
225
+ // The root is the header line, not a row: anything folded into it would
226
+ // vanish. Codex review on #1290.
227
+ expanded: new Set([root.spanContext().spanId]),
228
+ skip: (s) =>
229
+ s.name === FETCH_BODY_SPAN_NAME ||
230
+ // A layout or page that returned at once says nothing; its children
231
+ // take its place. Unless it carries events (a cache HIT/MISS): those
232
+ // print under its own row. Codex review on #1290.
233
+ (readable &&
234
+ (s.name === LAYOUT || s.name === PAGE) &&
235
+ s.endMs - s.startMs < 1 &&
236
+ s.span.events.length === 0),
237
+ });
208
238
 
209
239
  const rootStart = root.startTime;
210
240
  const lines: string[] = [];
@@ -225,10 +255,10 @@ export function formatSpanTree(spans: ReadableSpan[], config?: DevLoggerConfig):
225
255
  lines.push(`${colorMethod(method)} ${style('bold', path)} ${dimTrace}`);
226
256
  }
227
257
 
228
- // Render child span nodes
229
- for (let i = 0; i < children.length; i++) {
230
- const isLast = i === children.length - 1;
231
- formatSpanNode(children[i]!, lines, '', isLast, slowPhaseMs, rootStart);
258
+ // The root is the header line; everything else is at least one level in.
259
+ const body = rows.filter((r) => r.span.span !== root);
260
+ for (const { item, prefix, connector } of treeConnectors(body, (r) => r.depth - 1)) {
261
+ formatRow(item, lines, prefix, connector, bodies, slowPhaseMs, rootStart);
232
262
  }
233
263
 
234
264
  // Result line
@@ -244,26 +274,37 @@ export function formatSpanTree(spans: ReadableSpan[], config?: DevLoggerConfig):
244
274
  ? style('dim', ` (caused by deny(${denyInfo}) inside Suspense — status already committed)`)
245
275
  : '';
246
276
 
277
+ // Say what tree mode left out, and how to see it.
278
+ const folded = body.reduce((n, r) => n + r.folded.length, 0);
279
+ const omitted = [
280
+ hiddenWaits > 0 ? `${hiddenWaits} wait${hiddenWaits === 1 ? '' : 's'} hidden` : '',
281
+ folded > 0 ? `${folded} await${folded === 1 ? '' : 's'} folded` : '',
282
+ ].filter(Boolean);
283
+ const omittedNote =
284
+ omitted.length > 0 ? style('dim', ` · ${omitted.join(', ')} (TIMBER_DEV_LOG=verbose)`) : '';
285
+
247
286
  lines.push(
248
- `${style(statusFmt, `└─ ✓ ${statusText}`)}${style('dim', ` total ${totalMs}ms`)}${denyNote}`
287
+ `${style(statusFmt, `└─ ✓ ${statusText}`)}${style('dim', ` total ${totalMs}ms`)}${denyNote}${omittedNote}`
249
288
  );
250
289
 
251
290
  return lines.join('\n') + '\n';
252
291
  }
253
292
 
293
+ /** A fetch line's times: the row's interval, plus the body read after it. */
294
+ interface FetchTiming {
295
+ startMs: number;
296
+ endMs: number;
297
+ durationMs: number;
298
+ /** Time spent reading the body, 0 when it was never read or took <1ms. */
299
+ bodyMs: number;
300
+ }
301
+
254
302
  /**
255
303
  * Format a fetch span line with method, URL, timing, duration, and cache status.
256
304
  *
257
- * Output: `├─ fetch GET https://api.example.com/data 12ms → 89ms (77ms) [cache: HIT]`
305
+ * Output: `├─ fetch GET https://api.example.com/data 12ms → 140ms (77ms + 51ms body) [cdn: HIT]`
258
306
  */
259
- function formatFetchLine(
260
- span: ReadableSpan,
261
- prefix: string,
262
- connector: string,
263
- startMs: number,
264
- endMs: number,
265
- durationMs: number
266
- ): string {
307
+ function formatFetchLine(span: ReadableSpan, lead: string, timing: FetchTiming): string {
267
308
  const method = String(span.attributes['http.request.method'] ?? 'GET');
268
309
  const url = String(span.attributes['http.url'] ?? '');
269
310
  const statusCode = span.attributes['http.response.status_code'] as number | undefined;
@@ -271,8 +312,10 @@ function formatFetchLine(
271
312
  const fetchError = span.attributes['timber.fetch_error'] as string | undefined;
272
313
  const isError = span.status.code === 2; // SpanStatusCode.ERROR
273
314
 
274
- let line = `${prefix}${connector} ${style('dim', `fetch ${method}`)} ${url}`;
275
- line += ` ${style('dim', `${startMs}ms → ${endMs}ms (${durationMs}ms)`)}`;
315
+ const { startMs, endMs, durationMs, bodyMs } = timing;
316
+ const body = bodyMs > 0 ? ` + ${bodyMs}ms body` : '';
317
+ let line = `${lead}${style('dim', `fetch ${method}`)} ${url}`;
318
+ line += ` ${style('dim', `${startMs}ms → ${endMs}ms (${durationMs}ms${body})`)}`;
276
319
 
277
320
  if (cacheStatus) {
278
321
  line += ` ${style('dim', `[cdn: ${cacheStatus}]`)}`;
@@ -288,53 +331,91 @@ function formatFetchLine(
288
331
  return line;
289
332
  }
290
333
 
334
+ /** An access gate's result from its span: ` → DENY 403 (app/admin/access.ts)`. */
335
+ function accessOutcome(span: ReadableSpan): string {
336
+ const result = span.attributes['timber.result'] as string | undefined;
337
+ if (!result) return '';
338
+ const status = span.attributes['timber.deny_status'] as number | undefined;
339
+ const denyFile = span.attributes['timber.deny_file'] as string | undefined;
340
+ return ` → ${result.toUpperCase()}${status ? ` ${status}` : ''}${denyFile ? ` (${denyFile})` : ''}`;
341
+ }
342
+
291
343
  /**
292
- * Format a single span tree node with children, timing, and annotations.
344
+ * Format one row: its line, then its cache annotations.
345
+ *
346
+ * A folded row keeps the outer span's interval, which is the code that asked
347
+ * for the work, and reads as the fetch when the chain ends in one, since
348
+ * that is the I/O. Otherwise it reads as the outer span. Cache events from
349
+ * every span in the row are kept.
293
350
  */
294
- function formatSpanNode(
295
- node: SpanTreeNode,
351
+ function formatRow(
352
+ row: WaterfallRow<LogSpan>,
296
353
  lines: string[],
297
354
  prefix: string,
298
- isLast: boolean,
355
+ connector: string,
356
+ bodies: ReadonlyMap<string | undefined, readonly LogSpan[]>,
299
357
  slowPhaseMs: number,
300
358
  rootStart: HrTime
301
359
  ): void {
302
- const connector = isLast ? '└─' : '├─';
303
- const childPrefix = prefix + (isLast ? ' ' : '│ ');
304
- const { label, env } = spanLabel(node.span);
305
- const startMs = Math.round(relativeMs(node.span.startTime, rootStart));
306
- const endMs = Math.round(relativeMs(node.span.endTime, rootStart));
360
+ const childPrefix = prefix + (connector === '└─' ? ' ' : '│ ');
361
+ const outer = row.span.span;
362
+ const chain = [row.span, ...row.folded];
363
+ const leaf = row.folded.at(-1);
364
+ const startMs = Math.round(relativeMs(outer.startTime, rootStart));
365
+ const endMs = Math.round(relativeMs(outer.endTime, rootStart));
307
366
  const durationMs = endMs - startMs;
308
- const isSlow = durationMs > slowPhaseMs;
309
-
310
- // Fetch spans get special formatting: no env tag, duration in parens, cache status
311
- if (node.span.name === 'timber.fetch') {
312
- const fetchLine = formatFetchLine(node.span, prefix, connector, startMs, endMs, durationMs);
313
- lines.push(fetchLine);
314
- return;
315
- }
316
-
317
- // Access results from span attributes
318
- const accessResult = node.span.attributes['timber.result'] as string | undefined;
319
-
320
- let timing = `${startMs}ms → ${endMs}ms`;
321
- if (accessResult) {
322
- const accessStatus = node.span.attributes['timber.deny_status'] as number | undefined;
323
- const denyFile = node.span.attributes['timber.deny_file'] as string | undefined;
324
- timing += ` → ${accessResult.toUpperCase()}${accessStatus ? ` ${accessStatus}` : ''}`;
325
- if (denyFile) {
326
- timing += ` (${denyFile})`;
327
- }
367
+ const slow = (text: string) => (durationMs > slowPhaseMs ? style('yellow', text) : text);
368
+ const envTag = (span: ReadableSpan) =>
369
+ `${style('cyan', `[${devSpanLabel(span.name, span.attributes).env}]`)} `;
370
+
371
+ // A framework span folded into its await keeps both names:
372
+ // `[proxy] proxy.ts → await next()`.
373
+ const frame =
374
+ outer.name !== AWAIT_SPAN_NAME && row.folded.length > 0
375
+ ? `${envTag(outer)}${slow(devSpanLabel(outer.name, outer.attributes).label)} → `
376
+ : '';
377
+ const lead = `${prefix}${connector} ${frame}`;
378
+ const outcome = accessOutcome(outer);
379
+
380
+ if (leaf?.name === FETCH_SPAN_NAME || outer.name === FETCH_SPAN_NAME) {
381
+ const fetch = leaf?.name === FETCH_SPAN_NAME ? leaf : row.span;
382
+ const reads = bodies.get(fetch.spanId) ?? [];
383
+ // The reads' own time: work the app did between headers and reading
384
+ // the body is not body time. Codex review on #1290.
385
+ const bodyMs = Math.round(reads.reduce((ms, r) => ms + (r.endMs - r.startMs), 0));
386
+ const lastRead = reads.reduce<ReadableSpan | undefined>(
387
+ (last, r) => (last && hrTimeToMs(last.endTime) >= r.endMs ? last : r.span),
388
+ undefined
389
+ );
390
+ const end = lastRead
391
+ ? Math.max(endMs, Math.round(relativeMs(lastRead.endTime, rootStart)))
392
+ : endMs;
393
+ // An access gate that folded into its fetch keeps its outcome. Codex
394
+ // review on #1290.
395
+ // The row keeps the outer interval, but the parenthesized time is the
396
+ // fetch's own: an outer loader's duration already includes the body read,
397
+ // so adding `+ body` to it counted the body twice. Codex review on #1290.
398
+ const fetchLine = formatFetchLine(fetch.span, lead, {
399
+ startMs,
400
+ endMs: end,
401
+ durationMs: Math.round(fetch.endMs - fetch.startMs),
402
+ bodyMs,
403
+ });
404
+ lines.push(outcome ? `${fetchLine}${style('dim', outcome)}` : fetchLine);
405
+ } else {
406
+ const timing = `${startMs}ms → ${endMs}ms${outcome}`;
407
+ // The row reads as its first await, the code that asked for the work.
408
+ // An await's label already starts with `await`; a tag would say it twice.
409
+ const named = (frame ? row.folded[0] : row.span)?.span ?? outer;
410
+ const { label } = devSpanLabel(named.name, named.attributes);
411
+ const tag = frame || named.name === AWAIT_SPAN_NAME ? '' : envTag(named);
412
+ lines.push(`${lead}${tag}${frame ? label : slow(label)} ${style('dim', timing)}`);
328
413
  }
329
414
 
330
- const styledLabel = isSlow ? style('yellow', label) : label;
331
- const envTag = style('cyan', `[${env}]`);
332
- const line = `${prefix}${connector} ${envTag} ${styledLabel} ${style('dim', timing)}`;
333
- lines.push(line);
334
-
335
415
  // Span events (cache hits/misses) as child annotations
336
- for (const event of node.span.events) {
337
- if (event.name === 'timber.cache.hit' || event.name === 'timber.cache.miss') {
416
+ for (const { span } of chain) {
417
+ for (const event of span.events) {
418
+ if (event.name !== 'timber.cache.hit' && event.name !== 'timber.cache.miss') continue;
338
419
  const key = String(event.attributes?.['key'] ?? '');
339
420
  const hitMiss = event.name === 'timber.cache.hit' ? 'HIT' : 'MISS';
340
421
  const durMs = event.attributes?.['duration_ms'] as number | undefined;
@@ -345,12 +426,6 @@ function formatSpanNode(
345
426
  );
346
427
  }
347
428
  }
348
-
349
- // Render children
350
- for (let i = 0; i < node.children.length; i++) {
351
- const childIsLast = i === node.children.length - 1;
352
- formatSpanNode(node.children[i]!, lines, childPrefix, childIsLast, slowPhaseMs, rootStart);
353
- }
354
429
  }
355
430
 
356
431
  /**
@@ -11,6 +11,7 @@
11
11
  * this is what keeps the browser channel gated to `vite dev`.
12
12
  */
13
13
 
14
+ import { AsyncLocalStorage } from 'node:async_hooks';
14
15
  import type { ReadableSpan } from '@opentelemetry/sdk-trace-base';
15
16
  import {
16
17
  DEV_SPAN_ATTRIBUTES,
@@ -89,7 +90,15 @@ export interface SpanSinkChannel {
89
90
 
90
91
  /**
91
92
  * Install the sink that broadcasts spans on the dev server's HMR channel,
92
- * and answers replay requests from it.
93
+ * and answers replay requests from it. Every message is an array of spans
94
+ * of one trace, in the order they ended.
95
+ *
96
+ * Spans are batched: one send per trace per event-loop turn, not one per
97
+ * span. The sink is called inside the request, and each `hot.send` makes
98
+ * promises there, for each of which React's dev async debug hook captures a
99
+ * stack (~6µs a span; ~6ms on a 213-span trace). So the flush is scheduled
100
+ * from an `AsyncLocalStorage.snapshot()` taken here, at install, where no
101
+ * request is in scope: the send runs outside every request (TIM-1627).
93
102
  *
94
103
  * Broadcasting alone loses most of a document load: the root span ends when
95
104
  * the pipeline returns its Response, tens of milliseconds in, and the page's
@@ -104,6 +113,15 @@ export interface SpanSinkChannel {
104
113
  export function installSpanSink(hot: SpanSinkChannel): () => void {
105
114
  const globals = globalThis as Record<symbol, unknown>;
106
115
  const recent = new Map<string, DevSpanPayload[]>();
116
+ const outsideRequests = AsyncLocalStorage.snapshot();
117
+ let pending = new Map<string, DevSpanPayload[]>();
118
+ let scheduled: NodeJS.Immediate | undefined;
119
+ const flush = () => {
120
+ const batches = pending;
121
+ pending = new Map();
122
+ scheduled = undefined;
123
+ for (const spans of batches.values()) hot.send(DEV_SPAN_EVENT, spans);
124
+ };
107
125
  const sink: DevSpanSink = (span) => {
108
126
  let spans = recent.get(span.traceId);
109
127
  if (!spans) {
@@ -115,18 +133,31 @@ export function installSpanSink(hot: SpanSinkChannel): () => void {
115
133
  recent.set(span.traceId, spans);
116
134
  }
117
135
  spans.push(span);
118
- hot.send(DEV_SPAN_EVENT, span);
136
+ let batch = pending.get(span.traceId);
137
+ if (!batch) {
138
+ batch = [];
139
+ pending.set(span.traceId, batch);
140
+ }
141
+ batch.push(span);
142
+ scheduled ??= outsideRequests(() => setImmediate(flush));
119
143
  };
120
144
  const onReplay = (data: unknown, client: { send(event: string, data: unknown): void }) => {
121
145
  if (typeof data !== 'object' || data === null || !('traceId' in data)) return;
122
146
  const { traceId } = data;
123
147
  if (typeof traceId !== 'string') return;
124
- for (const span of recent.get(traceId) ?? []) client.send(DEV_SPAN_EVENT, span);
148
+ const spans = recent.get(traceId);
149
+ // A copy: the trace's own list keeps growing while the send is queued.
150
+ if (spans) client.send(DEV_SPAN_EVENT, spans.slice());
125
151
  };
126
152
  globals[DEV_SPAN_SINK_KEY] = sink;
127
153
  hot.on(DEV_SPAN_REPLAY_EVENT, onReplay);
128
154
  return () => {
129
155
  hot.off(DEV_SPAN_REPLAY_EVENT, onReplay);
156
+ // Send what is queued now rather than drop it: the channel closes after.
157
+ if (scheduled) {
158
+ clearImmediate(scheduled);
159
+ flush();
160
+ }
130
161
  if (globals[DEV_SPAN_SINK_KEY] === sink) delete globals[DEV_SPAN_SINK_KEY];
131
162
  };
132
163
  }