@timber-js/app 0.2.0-alpha.228 → 0.2.0-alpha.229

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 (145) hide show
  1. package/agent-skill.md +9 -0
  2. package/dist/_chunks/{actions-DprvPi7O.js → actions-DHum77eH.js} +3 -3
  3. package/dist/_chunks/{actions-DprvPi7O.js.map → actions-DHum77eH.js.map} +1 -1
  4. package/dist/_chunks/{cache-api-BjE-nNC0.js → cache-api-BZJNt01a.js} +4 -4
  5. package/dist/_chunks/{cache-api-BjE-nNC0.js.map → cache-api-BZJNt01a.js.map} +1 -1
  6. package/dist/_chunks/{chains-DaDEXv0c.js → chains-D-RRc7CM.js} +2 -2
  7. package/dist/_chunks/{chains-DaDEXv0c.js.map → chains-D-RRc7CM.js.map} +1 -1
  8. package/dist/_chunks/chains-KblEfYzm.js +1 -0
  9. package/dist/_chunks/{classify-BuIifN5v.js → classify-_W0RWa5w.js} +2 -2
  10. package/dist/_chunks/{classify-BuIifN5v.js.map → classify-_W0RWa5w.js.map} +1 -1
  11. package/dist/_chunks/{cli-check-B_fDvxhs.js → cli-check-B-JZkpBD.js} +3 -3
  12. package/dist/_chunks/{cli-check-B_fDvxhs.js.map → cli-check-B-JZkpBD.js.map} +1 -1
  13. package/dist/_chunks/{cli-schema-sync-D9OLUUFv.js → cli-schema-sync-CAllbqRB.js} +2 -2
  14. package/dist/_chunks/{cli-schema-sync-D9OLUUFv.js.map → cli-schema-sync-CAllbqRB.js.map} +1 -1
  15. package/dist/_chunks/{cli-schema-sync-CUIk0G2X.js → cli-schema-sync-y_8ijmzO.js} +1 -1
  16. package/dist/_chunks/{client-dep-entries-COuyF8-c.js → client-dep-entries-C9hv-3k9.js} +2 -2
  17. package/dist/_chunks/{client-dep-entries-COuyF8-c.js.map → client-dep-entries-C9hv-3k9.js.map} +1 -1
  18. package/dist/_chunks/{convention-lint-BHY0d5AQ.js → convention-lint-CrDKERHg.js} +3 -3
  19. package/dist/_chunks/{convention-lint-BHY0d5AQ.js.map → convention-lint-CrDKERHg.js.map} +1 -1
  20. package/dist/_chunks/dev-server-L8biS7Az.js +1 -0
  21. package/dist/_chunks/{dev-server-BaM7q3pr.js → dev-server-Rq659RR1.js} +8 -2
  22. package/dist/_chunks/dev-server-Rq659RR1.js.map +1 -0
  23. package/dist/_chunks/{build-manifest-Y4jl7nwU.js → dev-span-_NzMX-au.js} +25 -2
  24. package/dist/_chunks/dev-span-_NzMX-au.js.map +1 -0
  25. package/dist/_chunks/{error-boundary-D3YyVVuP.js → error-boundary-OHK1mI99.js} +3 -3
  26. package/dist/_chunks/{error-boundary-D3YyVVuP.js.map → error-boundary-OHK1mI99.js.map} +1 -1
  27. package/dist/_chunks/{flight-source-node-CZJ9Drb7.js → flight-source-node-BGanuoSS.js} +2 -2
  28. package/dist/_chunks/{flight-source-node-CZJ9Drb7.js.map → flight-source-node-BGanuoSS.js.map} +1 -1
  29. package/dist/_chunks/{global-context-DbxNWeBP.js → global-context-CFSSysdJ.js} +32 -2
  30. package/dist/_chunks/global-context-CFSSysdJ.js.map +1 -0
  31. package/dist/_chunks/{json-lossy-check-BNwKrm2R.js → json-lossy-check-BXM45k8p.js} +2 -2
  32. package/dist/_chunks/{json-lossy-check-BNwKrm2R.js.map → json-lossy-check-BXM45k8p.js.map} +1 -1
  33. package/dist/_chunks/{live-graph-DiRVmRrC.js → live-graph-C7-yA8W9.js} +4 -4
  34. package/dist/_chunks/{live-graph-DiRVmRrC.js.map → live-graph-C7-yA8W9.js.map} +1 -1
  35. package/dist/_chunks/{logger-DRMij51J.js → logger-YtMSKfft.js} +100 -57
  36. package/dist/_chunks/logger-YtMSKfft.js.map +1 -0
  37. package/dist/_chunks/navigation-root-CoGHIMiE.js +239 -0
  38. package/dist/_chunks/navigation-root-CoGHIMiE.js.map +1 -0
  39. package/dist/_chunks/{node-response-C-dQn-0N.js → node-response-D3hXWb8y.js} +2 -2
  40. package/dist/_chunks/{node-response-C-dQn-0N.js.map → node-response-D3hXWb8y.js.map} +1 -1
  41. package/dist/_chunks/{poison-scan-CqPGN0ru.js → poison-scan-CRSP06Es.js} +2 -2
  42. package/dist/_chunks/{poison-scan-CqPGN0ru.js.map → poison-scan-CRSP06Es.js.map} +1 -1
  43. package/dist/_chunks/{scanner-C__vsQ8d.js → scanner-BNQ4qnLX.js} +2 -2
  44. package/dist/_chunks/{scanner-C__vsQ8d.js.map → scanner-BNQ4qnLX.js.map} +1 -1
  45. package/dist/_chunks/segment-context-GAyTjjtS.js +33 -0
  46. package/dist/_chunks/segment-context-GAyTjjtS.js.map +1 -0
  47. package/dist/_chunks/{sizeof-DcEcQaSL.js → sizeof-Cmx6Fs-Y.js} +2 -2
  48. package/dist/_chunks/{sizeof-DcEcQaSL.js.map → sizeof-Cmx6Fs-Y.js.map} +1 -1
  49. package/dist/_chunks/{status-page-marker-C8POawuF.js → status-page-marker-U6B1aFMb.js} +3 -32
  50. package/dist/_chunks/status-page-marker-U6B1aFMb.js.map +1 -0
  51. package/dist/_chunks/{walkers-D6KY4jyS.js → walkers-D_QHR_nf.js} +3 -3
  52. package/dist/_chunks/{walkers-D6KY4jyS.js.map → walkers-D_QHR_nf.js.map} +1 -1
  53. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  54. package/dist/analyze/crawl-entry.js +3 -3
  55. package/dist/analyze/graph-command.js +2 -2
  56. package/dist/cache/index.js +2 -2
  57. package/dist/cache/stores/memory.js +1 -1
  58. package/dist/cli.js +3 -3
  59. package/dist/client/browser-entry/hmr.d.ts +7 -1
  60. package/dist/client/browser-entry/hmr.d.ts.map +1 -1
  61. package/dist/client/dev-pill/index.d.ts +32 -0
  62. package/dist/client/dev-pill/index.d.ts.map +1 -0
  63. package/dist/client/dev-pill/store.d.ts +96 -0
  64. package/dist/client/dev-pill/store.d.ts.map +1 -0
  65. package/dist/client/dev-pill/view.d.ts +9 -0
  66. package/dist/client/dev-pill/view.d.ts.map +1 -0
  67. package/dist/client/error-boundary.js +1 -1
  68. package/dist/client/index.d.ts +1 -0
  69. package/dist/client/index.d.ts.map +1 -1
  70. package/dist/client/index.js +3 -3
  71. package/dist/client/internal.js +16 -7
  72. package/dist/client/internal.js.map +1 -1
  73. package/dist/client/navigation-context.d.ts +20 -0
  74. package/dist/client/navigation-context.d.ts.map +1 -1
  75. package/dist/client/router-lifecycle.d.ts +4 -1
  76. package/dist/client/router-lifecycle.d.ts.map +1 -1
  77. package/dist/client/use-pending-navigation.d.ts +33 -9
  78. package/dist/client/use-pending-navigation.d.ts.map +1 -1
  79. package/dist/config-types.d.ts +10 -0
  80. package/dist/config-types.d.ts.map +1 -1
  81. package/dist/config-validation.d.ts.map +1 -1
  82. package/dist/dev-tools/await-span.d.ts +17 -0
  83. package/dist/dev-tools/await-span.d.ts.map +1 -0
  84. package/dist/dev-tools/instrumentation.d.ts.map +1 -1
  85. package/dist/dev-tools/logger.d.ts.map +1 -1
  86. package/dist/dev-tools/logs.d.ts.map +1 -1
  87. package/dist/dev-tools/span-sink.d.ts +42 -0
  88. package/dist/dev-tools/span-sink.d.ts.map +1 -0
  89. package/dist/index.d.ts.map +1 -1
  90. package/dist/index.js +282 -9
  91. package/dist/index.js.map +1 -1
  92. package/dist/plugins/dev-await.d.ts +40 -0
  93. package/dist/plugins/dev-await.d.ts.map +1 -0
  94. package/dist/plugins/entries.d.ts.map +1 -1
  95. package/dist/routing/index.js +2 -2
  96. package/dist/server/index.js +2 -2
  97. package/dist/server/internal.js +9 -8
  98. package/dist/server/internal.js.map +1 -1
  99. package/dist/server/pipeline.d.ts +8 -0
  100. package/dist/server/pipeline.d.ts.map +1 -1
  101. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  102. package/dist/server/slot-resolver.d.ts.map +1 -1
  103. package/dist/server/tracing.d.ts +18 -8
  104. package/dist/server/tracing.d.ts.map +1 -1
  105. package/dist/shared/dev-span.d.ts +97 -0
  106. package/dist/shared/dev-span.d.ts.map +1 -0
  107. package/docs/api/31-api-client.mdx +27 -1
  108. package/docs/api/34-api-config.mdx +21 -1
  109. package/docs/learn/09-streaming.mdx +7 -1
  110. package/package.json +3 -3
  111. package/src/client/browser-entry/hmr.ts +13 -1
  112. package/src/client/browser-entry/index.ts +4 -1
  113. package/src/client/dev-pill/index.ts +128 -0
  114. package/src/client/dev-pill/store.ts +231 -0
  115. package/src/client/dev-pill/view.ts +278 -0
  116. package/src/client/index.ts +1 -0
  117. package/src/client/navigation-context.ts +5 -2
  118. package/src/client/router-lifecycle.ts +23 -3
  119. package/src/client/use-pending-navigation.ts +93 -14
  120. package/src/config-types.ts +10 -0
  121. package/src/config-validation.ts +10 -0
  122. package/src/dev-tools/await-span.ts +40 -0
  123. package/src/dev-tools/instrumentation.ts +20 -0
  124. package/src/dev-tools/logger.ts +3 -37
  125. package/src/dev-tools/logs.ts +10 -1
  126. package/src/dev-tools/span-sink.ts +132 -0
  127. package/src/index.ts +2 -0
  128. package/src/plugins/dev-await.ts +268 -0
  129. package/src/plugins/entries.ts +2 -0
  130. package/src/server/pipeline.ts +14 -0
  131. package/src/server/rsc-entry/index.ts +7 -1
  132. package/src/server/slot-resolver.ts +45 -5
  133. package/src/server/tracing.ts +121 -87
  134. package/src/shared/dev-span.ts +182 -0
  135. package/dist/_chunks/build-manifest-Y4jl7nwU.js.map +0 -1
  136. package/dist/_chunks/chains-BS8fQYao.js +0 -1
  137. package/dist/_chunks/dev-server-BaM7q3pr.js.map +0 -1
  138. package/dist/_chunks/dev-server-NnGosJ06.js +0 -1
  139. package/dist/_chunks/global-context-DbxNWeBP.js.map +0 -1
  140. package/dist/_chunks/logger-DRMij51J.js.map +0 -1
  141. package/dist/_chunks/navigation-root-M3B2ZrdO.js +0 -122
  142. package/dist/_chunks/navigation-root-M3B2ZrdO.js.map +0 -1
  143. package/dist/_chunks/segment-context-CYiGTi3K.js +0 -131
  144. package/dist/_chunks/segment-context-CYiGTi3K.js.map +0 -1
  145. package/dist/_chunks/status-page-marker-C8POawuF.js.map +0 -1
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { randomUUID } from 'node:crypto';
12
+ import { trace, SpanStatusCode, type Span, type Tracer } from '@opentelemetry/api';
12
13
  import { traceAls, type TraceStore } from './als-registry.ts';
13
14
  import { controlFlowStatus, isSsrStreamError } from './signal-identity.ts';
14
15
 
@@ -127,9 +128,6 @@ export async function initDevTracing(
127
128
  const globals = globalThis as Record<symbol, unknown>;
128
129
  if (globals[DEV_TRACING_INIT_KEY]) return;
129
130
 
130
- const api = await getOtelApi();
131
- if (!api) return;
132
-
133
131
  // Tracing is a diagnostic: any failure to load or construct the SDK
134
132
  // disables it with a warning and never fails the server's boot (TIM-1554).
135
133
  try {
@@ -141,9 +139,6 @@ export async function initDevTracing(
141
139
  return;
142
140
  }
143
141
 
144
- // Reset cached tracer so next getTracer() picks up the new provider
145
- _tracer = undefined;
146
-
147
142
  globals[DEV_TRACING_INIT_KEY] = true;
148
143
  }
149
144
 
@@ -194,42 +189,19 @@ export function getPlatformTracer(): PlatformTracer | undefined {
194
189
  // ─── OTEL Span Helpers ───────────────────────────────────────────────────
195
190
 
196
191
  /**
197
- * Attempt to get the @opentelemetry/api tracer. Returns undefined if the
198
- * package is not installed or no SDK is registered.
192
+ * The timber.js OTEL tracer.
199
193
  *
200
- * timber.js depends on @opentelemetry/api as the vendor-neutral interface.
201
- * The API is a no-op by default — spans are only emitted when the developer
202
- * initializes an SDK in register().
203
- */
204
- let _otelApi: typeof import('@opentelemetry/api') | null | undefined;
205
-
206
- async function getOtelApi(): Promise<typeof import('@opentelemetry/api') | null> {
207
- if (_otelApi === undefined) {
208
- try {
209
- _otelApi = await import('@opentelemetry/api');
210
- } catch {
211
- _otelApi = null;
212
- }
213
- }
214
- return _otelApi;
215
- }
216
-
217
- /** OTEL tracer instance, lazily created. */
218
- let _tracer: import('@opentelemetry/api').Tracer | null | undefined;
219
-
220
- /**
221
- * Get the timber.js OTEL tracer. Returns null if @opentelemetry/api is not available.
194
+ * `@opentelemetry/api` is a direct dependency and a no-op until an SDK
195
+ * registers a provider (the user's `register()`, or dev tracing). Imported
196
+ * statically, not lazily, so `withSpan()` can invoke its callback in the
197
+ * same synchronous frame it was called in: a server component wrapped in a
198
+ * span (`timber.page`, `timber.layout`) must run while React's render
199
+ * dispatcher is still set, or a synchronous component that calls `use()`
200
+ * fails with an invalid hook call. Looked up per span — the API's proxy
201
+ * tracer follows a provider registered after boot.
222
202
  */
223
- export async function getTracer(): Promise<import('@opentelemetry/api').Tracer | null> {
224
- if (_tracer === undefined) {
225
- const api = await getOtelApi();
226
- if (api) {
227
- _tracer = api.trace.getTracer('timber.js');
228
- } else {
229
- _tracer = null;
230
- }
231
- }
232
- return _tracer;
203
+ function getTracer(): Tracer {
204
+ return trace.getTracer('timber.js');
233
205
  }
234
206
 
235
207
  /**
@@ -239,9 +211,12 @@ export async function getTracer(): Promise<import('@opentelemetry/api').Tracer |
239
211
  * (Cloudflare Workers), the fn is wrapped in platformTracer.enterSpan()
240
212
  * so it appears in the platform's native trace view.
241
213
  * - **OTEL span** — when an OTEL SDK is active, the fn also runs inside an
242
- * OTEL span (dual emission). No SDK and no platform tracer = zero overhead.
214
+ * OTEL span (dual emission). With no SDK the OTEL span is the API's
215
+ * non-recording no-op.
243
216
  *
244
217
  * Automatically:
218
+ * - Invokes fn synchronously, in the caller's frame — a wrapped server
219
+ * component still sees React's render dispatcher (see getTracer())
245
220
  * - Creates the span as a child of the current context
246
221
  * - Runs fn in its own trace scope carrying the span's IDs, for log–trace
247
222
  * correlation and setSpanAttribute()
@@ -251,8 +226,27 @@ export async function getTracer(): Promise<import('@opentelemetry/api').Tracer |
251
226
  export async function withSpan<T>(
252
227
  name: string,
253
228
  attributes: Record<string, string | number | boolean>,
254
- fn: () => T | Promise<T>
229
+ fn: () => T | PromiseLike<T>
255
230
  ): Promise<T> {
231
+ return traceCall(name, attributes, fn);
232
+ }
233
+
234
+ /**
235
+ * The span core of {@link withSpan}, keeping the shape of the call: `fn` runs
236
+ * synchronously, a value it returns comes back as that value, a promise as a
237
+ * promise, and a synchronous throw is rethrown synchronously.
238
+ *
239
+ * For a framework wrapper that invokes a server component inside a span.
240
+ * React drives a synchronous component through throws: `use()` on a pending
241
+ * promise throws, and Flight retries the component once it settles. That only
242
+ * works if the throw leaves the wrapper synchronously — `withSpan()` would
243
+ * turn it into a rejection, which Flight reports as a render error.
244
+ */
245
+ export function traceCall<T>(
246
+ name: string,
247
+ attributes: Record<string, string | number | boolean>,
248
+ fn: () => T | PromiseLike<T>
249
+ ): T | Promise<T> {
256
250
  const platformTracer = getPlatformTracer();
257
251
  if (!platformTracer) {
258
252
  return runOtelSpan(name, attributes, fn);
@@ -269,20 +263,17 @@ export async function withSpan<T>(
269
263
  });
270
264
  }
271
265
 
272
- /** The OTEL half of withSpan() — no-op passthrough when no SDK is active. */
273
- async function runOtelSpan<T>(
266
+ /**
267
+ * The OTEL half of withSpan() — a non-recording span when no SDK is active.
268
+ * Calls `fn` synchronously; see {@link getTracer}.
269
+ */
270
+ function runOtelSpan<T>(
274
271
  name: string,
275
272
  attributes: Record<string, string | number | boolean>,
276
- fn: () => T | Promise<T>
277
- ): Promise<T> {
278
- const tracer = await getTracer();
279
- if (!tracer) {
280
- return fn();
281
- }
282
-
283
- const api = (await getOtelApi())!;
284
- return tracer.startActiveSpan(name, { attributes }, (span) =>
285
- runInSpanScope({ spanId: span.spanContext().spanId }, () => settleOtelSpan(api, span, fn))
273
+ fn: () => T | PromiseLike<T>
274
+ ): T | Promise<T> {
275
+ return getTracer().startActiveSpan(name, { attributes }, (span) =>
276
+ runInSpanScope({ spanId: span.spanContext().spanId }, () => settleOtelSpan(span, fn))
286
277
  );
287
278
  }
288
279
 
@@ -301,26 +292,83 @@ function isOutcomeSignal(error: unknown): boolean {
301
292
  return status !== undefined && status < 500;
302
293
  }
303
294
 
304
- /** Run `fn` and end `span` with its outcome (see {@link isOutcomeSignal}). */
305
- async function settleOtelSpan<T>(
306
- api: typeof import('@opentelemetry/api'),
307
- span: import('@opentelemetry/api').Span,
308
- fn: () => T | Promise<T>
309
- ): Promise<T> {
295
+ /**
296
+ * Run `fn` and end `span` with its outcome (see {@link isOutcomeSignal}),
297
+ * keeping the call's shape (see {@link traceCall}).
298
+ */
299
+ function settleOtelSpan<T>(span: Span, fn: () => T | PromiseLike<T>): T | Promise<T> {
300
+ let result: T | PromiseLike<T>;
310
301
  try {
311
- const result = await fn();
312
- span.setStatus({ code: api.SpanStatusCode.OK });
313
- return result;
302
+ result = fn();
314
303
  } catch (error) {
315
- if (isOutcomeSignal(error)) throw error;
316
- span.setStatus({ code: api.SpanStatusCode.ERROR });
304
+ endSpanWithError(span, error);
305
+ throw error;
306
+ }
307
+ if (isPromiseLike(result)) {
308
+ // Any thenable, not only a native Promise — a custom or cross-realm one
309
+ // must hold the span open too, as `await` would. Its `then` is called
310
+ // here, synchronously, so a lazy thenable starts its work in this span.
311
+ const thenable = result;
312
+ return new Promise<T>((resolve, reject) => {
313
+ const fail = (error: unknown) => {
314
+ endSpanWithError(span, error);
315
+ reject(error);
316
+ };
317
+ try {
318
+ thenable.then((value) => {
319
+ endSpanOk(span);
320
+ resolve(value);
321
+ }, fail);
322
+ } catch (error) {
323
+ // A `then` that throws is a rejection, as for `await`; end the span.
324
+ fail(error);
325
+ }
326
+ });
327
+ }
328
+ endSpanOk(span);
329
+ return result;
330
+ }
331
+
332
+ function isPromiseLike<T>(value: T | PromiseLike<T>): value is PromiseLike<T> {
333
+ return (
334
+ (typeof value === 'object' || typeof value === 'function') &&
335
+ value !== null &&
336
+ 'then' in value &&
337
+ typeof value.then === 'function'
338
+ );
339
+ }
340
+
341
+ function endSpanOk(span: Span): void {
342
+ span.setStatus({ code: SpanStatusCode.OK });
343
+ span.end();
344
+ }
345
+
346
+ /**
347
+ * True when `error` is React suspending the component, not failing it: a
348
+ * thrown thenable, or the `SuspenseException` that `use()` throws on a
349
+ * pending promise. Flight retries the component once the promise settles, so
350
+ * a span around a synchronous component (see {@link traceCall}) that suspends
351
+ * is not an error span — the retry's span carries the real outcome.
352
+ *
353
+ * React does not export `SuspenseException`; Flight recognises it by
354
+ * identity, and its message — which React keeps stable because it is the
355
+ * user-facing explanation when one is caught by mistake — is the only handle
356
+ * outside React.
357
+ */
358
+ function isReactSuspension(error: unknown): boolean {
359
+ if (typeof error !== 'object' || error === null) return false;
360
+ if ('then' in error && typeof error.then === 'function') return true;
361
+ return error instanceof Error && error.message.startsWith('Suspense Exception:');
362
+ }
363
+
364
+ function endSpanWithError(span: Span, error: unknown): void {
365
+ if (!isOutcomeSignal(error) && !isReactSuspension(error)) {
366
+ span.setStatus({ code: SpanStatusCode.ERROR });
317
367
  if (error instanceof Error) {
318
368
  span.recordException(error);
319
369
  }
320
- throw error;
321
- } finally {
322
- span.end();
323
370
  }
371
+ span.end();
324
372
  }
325
373
 
326
374
  /**
@@ -337,10 +385,7 @@ export async function setSpanAttribute(
337
385
  platformSpan.setAttribute(key, value);
338
386
  }
339
387
 
340
- const api = await getOtelApi();
341
- if (!api) return;
342
-
343
- const activeSpan = api.trace.getActiveSpan();
388
+ const activeSpan = trace.getActiveSpan();
344
389
  if (activeSpan?.isRecording()) {
345
390
  activeSpan.setAttribute(key, value);
346
391
  }
@@ -354,10 +399,7 @@ export async function addSpanEvent(
354
399
  name: string,
355
400
  attributes?: Record<string, string | number | boolean>
356
401
  ): Promise<void> {
357
- const api = await getOtelApi();
358
- if (!api) return;
359
-
360
- const activeSpan = api.trace.getActiveSpan();
402
+ const activeSpan = trace.getActiveSpan();
361
403
  if (activeSpan?.isRecording()) {
362
404
  activeSpan.addEvent(name, attributes);
363
405
  }
@@ -367,8 +409,7 @@ export async function addSpanEvent(
367
409
  * Fire-and-forget span event — no await, no microtask overhead.
368
410
  *
369
411
  * Used on the cache hot path where awaiting addSpanEvent creates an
370
- * unnecessary microtask per cache operation. If OTEL is not loaded yet,
371
- * the event is silently dropped (acceptable for diagnostics).
412
+ * unnecessary microtask per cache operation.
372
413
  *
373
414
  * See TIM-370 for perf motivation.
374
415
  */
@@ -376,11 +417,7 @@ export function addSpanEventSync(
376
417
  name: string,
377
418
  attributes?: Record<string, string | number | boolean>
378
419
  ): void {
379
- // Fast path: if OTEL API hasn't been loaded yet, skip entirely.
380
- // _otelApi is undefined (not yet loaded), null (failed to load), or the module.
381
- if (!_otelApi) return;
382
-
383
- const activeSpan = _otelApi.trace.getActiveSpan();
420
+ const activeSpan = trace.getActiveSpan();
384
421
  if (activeSpan?.isRecording()) {
385
422
  activeSpan.addEvent(name, attributes);
386
423
  }
@@ -392,10 +429,7 @@ export function addSpanEventSync(
392
429
  * reaches logs through the span's own trace scope, not from here.)
393
430
  */
394
431
  export async function getOtelTraceId(): Promise<string | undefined> {
395
- const api = await getOtelApi();
396
- if (!api) return undefined;
397
-
398
- const activeSpan = api.trace.getActiveSpan();
432
+ const activeSpan = trace.getActiveSpan();
399
433
  if (!activeSpan) return undefined;
400
434
 
401
435
  const ctx = activeSpan.spanContext();
@@ -0,0 +1,182 @@
1
+ /**
2
+ * The wire contract between the dev server's span sink and the dev request
3
+ * pill in the browser. Dev-only; see design/50-dev-request-pill.md.
4
+ *
5
+ * Isomorphic: no server, client, or build-time imports.
6
+ */
7
+
8
+ /** HMR event that carries one finished span to the browser. */
9
+ export const DEV_SPAN_EVENT = 'timber:span';
10
+
11
+ /** HMR event a tab sends to ask for a trace's spans that ended before it connected. */
12
+ export const DEV_SPAN_REPLAY_EVENT = 'timber:span-replay';
13
+
14
+ /**
15
+ * `globalThis` key holding the span sink. The dev server plugin installs it
16
+ * and `DevSpanProcessor` (RSC module graph, same process, separate module
17
+ * instances) reads it, so the hand-off is a `Symbol.for` global.
18
+ */
19
+ export const DEV_SPAN_SINK_KEY = Symbol.for('timber.dev.span-sink');
20
+
21
+ /** The `Server-Timing` metric whose `desc` is the response's trace ID. */
22
+ export const TRACE_TIMING_NAME = 'timber-trace';
23
+
24
+ /**
25
+ * `globalThis` key holding the dev await wrapper. The dev await transform
26
+ * (`plugins/dev-await.ts`) rewrites `await x` in app server code to call
27
+ * it, looked up at call time; dev tracing installs it. With nothing
28
+ * installed the call is a plain await. See design/50-dev-request-pill.md
29
+ * §"Phase 2".
30
+ */
31
+ export const DEV_AWAIT_KEY = Symbol.for('timber.dev.await');
32
+
33
+ /** Span name for one awaited call in app server code. */
34
+ export const AWAIT_SPAN_NAME = 'timber.await';
35
+
36
+ /**
37
+ * Await spans shorter than this are dropped before they reach the terminal
38
+ * tree or the pill: `await params` and other awaits of settled values would
39
+ * otherwise drown the I/O the spans exist to show.
40
+ */
41
+ export const AWAIT_SPAN_MIN_MS = 1;
42
+
43
+ /** Root span of every pipeline request. */
44
+ export const ROOT_SPAN_NAME = 'http.server.request';
45
+
46
+ /**
47
+ * The span attributes that may reach the browser — the ones the pill reads,
48
+ * and nothing else. An allowlist of keys, not of prefixes: a prefix let
49
+ * through `timber.fetch_error` (an error message that can quote a full URL)
50
+ * and user attributes such as `url.full` or
51
+ * `http.request.header.authorization`. Typing the payload with this list
52
+ * means the pill cannot read an attribute that isn't on it.
53
+ */
54
+ export const DEV_SPAN_ATTRIBUTES = [
55
+ 'http.request.method',
56
+ 'http.response.status_code',
57
+ /** Query and fragment stripped. */
58
+ 'http.url',
59
+ /** Query and fragment stripped. */
60
+ 'url.path',
61
+ 'timber.route',
62
+ 'timber.segment',
63
+ 'timber.slot',
64
+ 'timber.action_name',
65
+ 'timber.cache_status',
66
+ /** The awaited expression's source text, whitespace collapsed, truncated. */
67
+ 'timber.await_label',
68
+ /** `path/relative/to/root.ts:line` of the await. */
69
+ 'timber.await_location',
70
+ ] as const;
71
+
72
+ export type DevSpanAttribute = (typeof DEV_SPAN_ATTRIBUTES)[number];
73
+
74
+ /** Attributes that hold a URL; sent without query or fragment. */
75
+ export const DEV_SPAN_URL_ATTRIBUTES: ReadonlySet<DevSpanAttribute> = new Set([
76
+ 'http.url',
77
+ 'url.path',
78
+ ]);
79
+
80
+ export type DevSpanSink = (span: DevSpanPayload) => void;
81
+
82
+ /** One finished span, projected for the browser. */
83
+ export interface DevSpanPayload {
84
+ traceId: string;
85
+ spanId: string;
86
+ /** Absent for the root span. */
87
+ parentSpanId?: string;
88
+ name: string;
89
+ /** Epoch milliseconds. */
90
+ startMs: number;
91
+ /** Epoch milliseconds. */
92
+ endMs: number;
93
+ error: boolean;
94
+ /** Only `DEV_SPAN_ATTRIBUTES`; URLs without query or fragment. */
95
+ attributes: Partial<Record<DevSpanAttribute, string | number | boolean>>;
96
+ /** Names of `timber.*` span events, e.g. `timber.cache.hit`. */
97
+ events: string[];
98
+ }
99
+
100
+ /**
101
+ * Read the trace ID from `Server-Timing` metrics, either a raw header value
102
+ * or the `serverTiming` entries of a `PerformanceResourceTiming`.
103
+ */
104
+ export function traceIdFromServerTiming(
105
+ timing: string | null | readonly { name: string; description: string }[]
106
+ ): string | null {
107
+ if (timing == null) return null;
108
+ if (typeof timing !== 'string') {
109
+ return timing.find((t) => t.name === TRACE_TIMING_NAME)?.description || null;
110
+ }
111
+ // `timber-trace;desc="<32 hex>"` — the ID is hex, so no escaping to undo.
112
+ const match = new RegExp(`(?:^|,)\\s*${TRACE_TIMING_NAME}\\s*;\\s*desc="?([0-9a-f]+)"?`).exec(
113
+ timing
114
+ );
115
+ return match?.[1] ?? null;
116
+ }
117
+
118
+ /** The `Server-Timing` entry that carries a trace ID. */
119
+ export function traceTimingEntry(traceId: string): string {
120
+ return `${TRACE_TIMING_NAME};desc="${traceId}"`;
121
+ }
122
+
123
+ // ─── Labels ─────────────────────────────────────────────────────────────────
124
+
125
+ /** Span attributes as either side holds them (OTEL also allows arrays). */
126
+ type SpanAttributes = Readonly<Record<string, unknown>>;
127
+
128
+ /** `@slot ` for a span from a parallel slot, so it reads apart from the main route. */
129
+ function slotPrefix(attrs: SpanAttributes): string {
130
+ const slot = attrs['timber.slot'];
131
+ return slot ? `${String(slot)} ` : '';
132
+ }
133
+
134
+ /**
135
+ * Map a span to its display label and environment tag. One mapping for the
136
+ * terminal tree and the dev request pill, so the two never name a span
137
+ * differently.
138
+ */
139
+ export function devSpanLabel(name: string, attrs: SpanAttributes): { label: string; env: string } {
140
+ switch (name) {
141
+ case ROOT_SPAN_NAME: {
142
+ const method = attrs['http.request.method'] ?? 'GET';
143
+ const path = attrs['url.path'] ?? '/';
144
+ return { label: `${String(method)} ${String(path)}`, env: 'rsc' };
145
+ }
146
+ case 'timber.proxy':
147
+ return { label: 'proxy.ts', env: 'proxy' };
148
+ case 'timber.middleware':
149
+ return { label: 'middleware.ts', env: 'rsc' };
150
+ case 'timber.render':
151
+ return { label: 'render', env: 'rsc' };
152
+ case 'timber.access': {
153
+ const seg = attrs['timber.segment'] ?? 'segment';
154
+ return { label: `AccessGate (${String(seg)})`, env: 'rsc' };
155
+ }
156
+ case 'timber.ssr':
157
+ return { label: 'hydration render', env: 'ssr' };
158
+ case 'timber.action': {
159
+ const actionName = attrs['timber.action_name'] ?? 'action';
160
+ return { label: String(actionName), env: 'rsc' };
161
+ }
162
+ case 'timber.metadata':
163
+ return { label: 'metadata()', env: 'rsc' };
164
+ case 'timber.layout': {
165
+ const seg = attrs['timber.segment'] ?? '/';
166
+ return { label: `layout ${slotPrefix(attrs)}${String(seg)}`, env: 'rsc' };
167
+ }
168
+ case 'timber.page': {
169
+ const route = attrs['timber.route'] ?? '/';
170
+ return { label: `page ${slotPrefix(attrs)}${String(route)}`, env: 'rsc' };
171
+ }
172
+ case AWAIT_SPAN_NAME:
173
+ return { label: `await ${String(attrs['timber.await_label'] ?? '')}`, env: 'await' };
174
+ case 'timber.fetch': {
175
+ const fetchMethod = attrs['http.request.method'] ?? 'GET';
176
+ const fetchUrl = attrs['http.url'] ?? '';
177
+ return { label: `fetch ${String(fetchMethod)} ${String(fetchUrl)}`, env: 'fetch' };
178
+ }
179
+ default:
180
+ return { label: name, env: 'rsc' };
181
+ }
182
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-manifest-Y4jl7nwU.js","names":[],"sources":["../../src/server/build-manifest.ts"],"sourcesContent":["/**\n * Build manifest types and utilities for CSS and JS asset tracking.\n *\n * The build manifest maps route segment file paths to their output\n * chunks from Vite's client build. This enables:\n * - <link rel=\"stylesheet\"> injection in HTML <head>\n * - <script type=\"module\"> with hashed URLs in production\n * - <link rel=\"modulepreload\"> for client chunk dependencies\n * - Link preload headers for Early Hints (103)\n *\n * In dev mode, Vite's HMR client handles CSS/JS injection, so the build\n * manifest is empty. In production, it's populated from Vite's\n * .vite/manifest.json after the client build.\n *\n * Design docs: 18-build-system.md §\"Build Manifest\", 02-rendering-pipeline.md §\"Early Hints\"\n */\n\n/** A font asset entry in the build manifest. */\nexport interface ManifestFontEntry {\n /** URL path to the font file (e.g. `/_timber/fonts/inter-latin-400-abc123.woff2`). */\n href: string;\n /** Font format (e.g. `woff2`). */\n format: string;\n /** Crossorigin attribute — always `anonymous` for fonts. */\n crossOrigin: string;\n}\n\n/** Build manifest mapping input file paths to output asset URLs. */\nexport interface BuildManifest {\n /** Map from input file path (relative to project root) to output CSS URLs. */\n css: Record<string, string[]>;\n /** Map from input file path to output JS chunk URL (hashed filename). */\n js: Record<string, string>;\n /** Map from input file path to transitive JS dependency URLs for modulepreload. */\n modulepreload: Record<string, string[]>;\n /** Map from input file path to font assets used by that module. */\n fonts: Record<string, ManifestFontEntry[]>;\n /**\n * Cache-busting hashes for metadata route files (opengraph-image, etc.).\n * Map from file path (relative to project root) to short content hash.\n * In dev mode this is empty — a startup nonce is used instead.\n */\n metadataRouteHashes?: Record<string, string>;\n /**\n * Static request-dependency map from the Vite plugin's module-graph analysis.\n * Map from segment entry file path to whether it's request-dependent.\n * Used by buildSegmentInfo() for X-Timber-Segments in production.\n */\n requestDep?: Record<string, boolean>;\n}\n\n/**\n * Empty build manifest used in dev mode, and the single source of truth for\n * what an empty manifest contains.\n *\n * `virtual:timber-build-manifest` serializes this constant into its generated\n * source rather than restating it — one literal for the dev module, one for the\n * production module's `globalThis.__TIMBER_BUILD_MANIFEST__ ?? …` fallback.\n * They were three hand-written objects that had already drifted: this one and\n * the dev literal were missing `requestDep` while the production fallback had\n * it, so a reader who grepped the built bundle for `requestDep` found the one\n * copy that mentioned it and read the fallback as the shipped map (TIM-1300).\n * A field added here now reaches every copy.\n */\nexport const EMPTY_BUILD_MANIFEST: BuildManifest = {\n css: {},\n js: {},\n modulepreload: {},\n fonts: {},\n metadataRouteHashes: {},\n requestDep: {},\n};\n\n/** Segment shape expected by collectRouteCss (matches ManifestSegmentNode). */\ninterface SegmentWithFiles {\n layout?: { filePath: string };\n page?: { filePath: string };\n}\n\n/**\n * Collect all CSS files needed for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting CSS for each layout and page.\n * Deduplicates while preserving order (root layout CSS first).\n */\nexport function collectRouteCss(segments: SegmentWithFiles[], manifest: BuildManifest): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const cssFiles = manifest.css[file.filePath];\n if (!cssFiles) continue;\n for (const url of cssFiles) {\n if (!seen.has(url)) {\n seen.add(url);\n result.push(url);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"stylesheet\"> tags for CSS URLs.\n *\n * Returns an HTML string to prepend to headHtml for injection\n * via injectHead() before </head>.\n */\nexport function buildCssLinkTags(cssUrls: string[]): string {\n // Emit only <link rel=\"stylesheet\"> — no preload tags. CSS preloading\n // is handled by 103 Early Hints (Link header) which fires before the\n // HTML stream. Float also emits `<link rel=\"stylesheet\" data-precedence>`\n // at the top of <head> during Fizz rendering — the browser discovers\n // CSS from that tag. A <link rel=\"preload\"> here would arrive *after*\n // Float's stylesheet tag and trigger \"Preload was ignored\" warnings.\n return cssUrls.map((url) => `<link rel=\"stylesheet\" href=\"${url}\">`).join('');\n}\n\n// ─── Font utilities ──────────────────────────────────────────────────────\n\n/**\n * Collect all font entries needed for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting fonts for each layout and page.\n * Deduplicates by href while preserving order.\n */\nexport function collectRouteFonts(\n segments: SegmentWithFiles[],\n manifest: BuildManifest\n): ManifestFontEntry[] {\n const seen = new Set<string>();\n const result: ManifestFontEntry[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const fonts = manifest.fonts[file.filePath];\n if (!fonts) continue;\n for (const entry of fonts) {\n if (!seen.has(entry.href)) {\n seen.add(entry.href);\n result.push(entry);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"preload\"> tags for font assets.\n *\n * Font preloads use `as=font` and always include `crossorigin` (required\n * for font preloads even for same-origin resources per the spec).\n */\nexport function buildFontPreloadTags(fonts: ManifestFontEntry[]): string {\n return fonts\n .map(\n (f) =>\n `<link rel=\"preload\" href=\"${f.href}\" as=\"font\" type=\"font/${f.format}\" crossorigin=\"${f.crossOrigin}\">`\n )\n .join('');\n}\n\n// ─── JS chunk utilities ──────────────────────────────────────────────────\n\n/**\n * Collect modulepreload URLs for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting transitive JS dependencies\n * for each layout and page. Deduplicates across segments.\n */\nexport function collectRouteModulepreloads(\n segments: SegmentWithFiles[],\n manifest: BuildManifest\n): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const preloads = manifest.modulepreload[file.filePath];\n if (!preloads) continue;\n for (const url of preloads) {\n if (!seen.has(url)) {\n seen.add(url);\n result.push(url);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"modulepreload\"> tags for JS dependency URLs.\n *\n * Modulepreload hints tell the browser to fetch and parse JS modules\n * before they're needed, reducing waterfall latency for dynamic imports.\n */\nexport function buildModulepreloadTags(urls: string[]): string {\n return urls.map((url) => `<link rel=\"modulepreload\" href=\"${url}\">`).join('');\n}\n"],"mappings":";;;;;;;;;;;;;;AAgEA,IAAa,uBAAsC;CACjD,KAAK,CAAC;CACN,IAAI,CAAC;CACL,eAAe,CAAC;CAChB,OAAO,CAAC;CACR,qBAAqB,CAAC;CACtB,YAAY,CAAC;AACf;;;;;;;AAcA,SAAgB,gBAAgB,UAA8B,UAAmC;CAC/F,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAE1B,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,SAAS,IAAI,KAAK;EACnC,IAAI,CAAC,UAAU;EACf,KAAK,MAAM,OAAO,UAChB,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,OAAO,KAAK,GAAG;EACjB;CAEJ;CAGF,OAAO;AACT;;;;;;;AA0BA,SAAgB,kBACd,UACA,UACqB;CACrB,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA8B,CAAC;CAErC,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,QAAQ,SAAS,MAAM,KAAK;EAClC,IAAI,CAAC,OAAO;EACZ,KAAK,MAAM,SAAS,OAClB,IAAI,CAAC,KAAK,IAAI,MAAM,IAAI,GAAG;GACzB,KAAK,IAAI,MAAM,IAAI;GACnB,OAAO,KAAK,KAAK;EACnB;CAEJ;CAGF,OAAO;AACT;;;;;;;AAyBA,SAAgB,2BACd,UACA,UACU;CACV,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAE1B,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,SAAS,cAAc,KAAK;EAC7C,IAAI,CAAC,UAAU;EACf,KAAK,MAAM,OAAO,UAChB,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,OAAO,KAAK,GAAG;EACjB;CAEJ;CAGF,OAAO;AACT"}
@@ -1 +0,0 @@
1
- export { t as formatChains } from "./chains-DaDEXv0c.js";