@timber-js/app 0.2.0-alpha.238 → 0.2.0-alpha.239

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 (37) hide show
  1. package/dist/_chunks/dev-span-RsVeYYc_.js.map +1 -1
  2. package/dist/dev-tools/instrumentation.d.ts.map +1 -1
  3. package/dist/dev-tools/log-columns.d.ts +50 -0
  4. package/dist/dev-tools/log-columns.d.ts.map +1 -0
  5. package/dist/dev-tools/logger.d.ts +5 -0
  6. package/dist/dev-tools/logger.d.ts.map +1 -1
  7. package/dist/native/rsc/dev-tools/instrumentation.js +5 -1
  8. package/dist/native/rsc/dev-tools/instrumentation.js.map +1 -1
  9. package/dist/native/rsc/dev-tools/log-columns.js +69 -0
  10. package/dist/native/rsc/dev-tools/log-columns.js.map +1 -0
  11. package/dist/native/rsc/dev-tools/logger.js +60 -33
  12. package/dist/native/rsc/dev-tools/logger.js.map +1 -1
  13. package/dist/native/rsc/manifest.json +1 -0
  14. package/dist/native/rsc/shared/dev-span.js +5 -2
  15. package/dist/native/rsc/shared/dev-span.js.map +1 -1
  16. package/dist/native/rsc/shared/span-waterfall.js +13 -2
  17. package/dist/native/rsc/shared/span-waterfall.js.map +1 -1
  18. package/dist/native/ssr/dev-tools/instrumentation.js +5 -1
  19. package/dist/native/ssr/dev-tools/instrumentation.js.map +1 -1
  20. package/dist/native/ssr/dev-tools/log-columns.js +69 -0
  21. package/dist/native/ssr/dev-tools/log-columns.js.map +1 -0
  22. package/dist/native/ssr/dev-tools/logger.js +60 -33
  23. package/dist/native/ssr/dev-tools/logger.js.map +1 -1
  24. package/dist/native/ssr/manifest.json +1 -0
  25. package/dist/native/ssr/shared/dev-span.js +5 -2
  26. package/dist/native/ssr/shared/dev-span.js.map +1 -1
  27. package/dist/native/ssr/shared/span-waterfall.js +13 -2
  28. package/dist/native/ssr/shared/span-waterfall.js.map +1 -1
  29. package/dist/shared/dev-span.d.ts +6 -0
  30. package/dist/shared/dev-span.d.ts.map +1 -1
  31. package/dist/shared/span-waterfall.d.ts.map +1 -1
  32. package/package.json +1 -1
  33. package/src/dev-tools/instrumentation.ts +4 -1
  34. package/src/dev-tools/log-columns.ts +156 -0
  35. package/src/dev-tools/logger.ts +107 -63
  36. package/src/shared/dev-span.ts +13 -1
  37. package/src/shared/span-waterfall.ts +36 -4
@@ -25,8 +25,10 @@ import {
25
25
  FETCH_BODY_SPAN_NAME,
26
26
  FETCH_SPAN_NAME,
27
27
  ROOT_SPAN_NAME,
28
+ fetchDisplayUrl,
28
29
  } from '../shared/dev-span.ts';
29
30
  import { buildWaterfall, type WaterfallRow, type WaterfallSpan } from '../shared/span-waterfall.ts';
31
+ import { fitParts, renderColumns, type ColumnLine } from './log-columns.ts';
30
32
 
31
33
  // ─── Configuration ──────────────────────────────────────────────────────────
32
34
 
@@ -37,6 +39,11 @@ export interface DevLoggerConfig {
37
39
  mode?: DevLogMode;
38
40
  /** Threshold in ms to highlight slow phases. Default: 200. */
39
41
  slowPhaseMs?: number;
42
+ /**
43
+ * Terminal width to cut tree lines to, so nothing wraps through the tree.
44
+ * Undefined (stderr is not a terminal) prints lines whole.
45
+ */
46
+ columns?: number;
40
47
  }
41
48
 
42
49
  // ─── Styling ────────────────────────────────────────────────────────────────
@@ -245,20 +252,23 @@ export function formatSpanTree(spans: ReadableSpan[], config?: DevLoggerConfig):
245
252
  const traceId = root.spanContext().traceId;
246
253
  const actionName = root.attributes['timber.action_name'] as string | undefined;
247
254
 
248
- const dimTrace = style('dim', `trace_id: ${traceId}`);
255
+ // A long path is cut before the trace ID is.
256
+ const dimTrace = ` ${style('dim', `trace_id: ${traceId}`)}`;
249
257
  if (actionName) {
250
258
  const actionFile = root.attributes['timber.action_file'] as string | undefined;
259
+ const action = `ACTION ${actionName}${actionFile ? ` (${actionFile})` : ''}`;
260
+ lines.push(fitParts(style('bold', action), dimTrace, config?.columns));
261
+ } else {
251
262
  lines.push(
252
- `${style('bold', `ACTION ${actionName}${actionFile ? ` (${actionFile})` : ''}`)} ${dimTrace}`
263
+ fitParts(`${colorMethod(method)} ${style('bold', path)}`, dimTrace, config?.columns)
253
264
  );
254
- } else {
255
- lines.push(`${colorMethod(method)} ${style('bold', path)} ${dimTrace}`);
256
265
  }
257
266
 
258
267
  // The root is the header line; everything else is at least one level in.
259
268
  const body = rows.filter((r) => r.span.span !== root);
269
+ const tree: ColumnLine[] = [];
260
270
  for (const { item, prefix, connector } of treeConnectors(body, (r) => r.depth - 1)) {
261
- formatRow(item, lines, prefix, connector, bodies, slowPhaseMs, rootStart);
271
+ formatRow(item, tree, prefix, connector, bodies, slowPhaseMs, rootStart);
262
272
  }
263
273
 
264
274
  // Result line
@@ -283,52 +293,71 @@ export function formatSpanTree(spans: ReadableSpan[], config?: DevLoggerConfig):
283
293
  const omittedNote =
284
294
  omitted.length > 0 ? style('dim', ` · ${omitted.join(', ')} (TIMBER_DEV_LOG=verbose)`) : '';
285
295
 
296
+ // The total sits in the duration column, under every row's duration.
297
+ tree.push({
298
+ durationMs: totalMs,
299
+ text: style(statusFmt, `✓ ${statusText}`),
300
+ tail: `${denyNote}${omittedNote}`,
301
+ });
286
302
  lines.push(
287
- `${style(statusFmt, `└─ ✓ ${statusText}`)}${style('dim', ` total ${totalMs}ms`)}${denyNote}${omittedNote}`
303
+ ...renderColumns(tree, config?.columns, {
304
+ dim: (text) => style('dim', text),
305
+ slow: (text) => style('yellow', text),
306
+ })
288
307
  );
289
308
 
290
309
  return lines.join('\n') + '\n';
291
310
  }
292
311
 
293
- /** A fetch line's times: the row's interval, plus the body read after it. */
312
+ /**
313
+ * A fetch's own timing, for the parenthesized note after its URL: the time
314
+ * to headers, and the body read after them.
315
+ */
294
316
  interface FetchTiming {
295
- startMs: number;
296
- endMs: number;
297
- durationMs: number;
317
+ /** Time to headers. */
318
+ headersMs: number;
298
319
  /** Time spent reading the body, 0 when it was never read or took <1ms. */
299
320
  bodyMs: number;
321
+ /** The row's duration column, to leave out a note that repeats it. */
322
+ rowMs: number;
300
323
  }
301
324
 
302
325
  /**
303
- * Format a fetch span line with method, URL, timing, duration, and cache status.
326
+ * A fetch's text, in two parts: `head` is the method and URL (as the pill
327
+ * labels it, without the scheme), the part a narrow terminal cuts; `tail`
328
+ * is its own timing when the duration column doesn't already say it, cache
329
+ * status, and an error or 4xx/5xx status, which are kept.
304
330
  *
305
- * Output: `├─ fetch GET https://api.example.com/data 12ms → 140ms (77ms + 51ms body) [cdn: HIT]`
331
+ * Output: `fetch GET api.example.com/data` + ` (77ms + 51ms body) [cdn: HIT]`
306
332
  */
307
- function formatFetchLine(span: ReadableSpan, lead: string, timing: FetchTiming): string {
333
+ function formatFetchParts(span: ReadableSpan, timing: FetchTiming): { head: string; tail: string } {
308
334
  const method = String(span.attributes['http.request.method'] ?? 'GET');
309
- const url = String(span.attributes['http.url'] ?? '');
335
+ const url = fetchDisplayUrl(String(span.attributes['http.url'] ?? ''));
310
336
  const statusCode = span.attributes['http.response.status_code'] as number | undefined;
311
337
  const cacheStatus = span.attributes['timber.cache_status'] as string | undefined;
312
338
  const fetchError = span.attributes['timber.fetch_error'] as string | undefined;
313
339
  const isError = span.status.code === 2; // SpanStatusCode.ERROR
314
340
 
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})`)}`;
341
+ const { headersMs, bodyMs, rowMs } = timing;
342
+ const head = `${style('dim', `fetch ${method}`)} ${url}`;
343
+ let text = '';
344
+ // The column shows the row's interval. A body read, or wrappers folded
345
+ // around the fetch, make the fetch's own time worth saying.
346
+ if (bodyMs > 0) text += ` ${style('dim', `(${headersMs}ms + ${bodyMs}ms body)`)}`;
347
+ else if (headersMs !== rowMs) text += ` ${style('dim', `(${headersMs}ms)`)}`;
319
348
 
320
349
  if (cacheStatus) {
321
- line += ` ${style('dim', `[cdn: ${cacheStatus}]`)}`;
350
+ text += ` ${style('dim', `[cdn: ${cacheStatus}]`)}`;
322
351
  }
323
352
 
324
353
  if (isError) {
325
354
  const errMsg = fetchError ? `: ${fetchError}` : '';
326
- line += ` ${style('red', `ERROR${errMsg}`)}`;
355
+ text += ` ${style('red', `ERROR${errMsg}`)}`;
327
356
  } else if (statusCode && statusCode >= 400) {
328
- line += ` ${style('yellow', String(statusCode))}`;
357
+ text += ` ${style('yellow', String(statusCode))}`;
329
358
  }
330
359
 
331
- return line;
360
+ return { head, tail: text };
332
361
  }
333
362
 
334
363
  /** An access gate's result from its span: ` → DENY 403 (app/admin/access.ts)`. */
@@ -344,13 +373,14 @@ function accessOutcome(span: ReadableSpan): string {
344
373
  * Format one row: its line, then its cache annotations.
345
374
  *
346
375
  * 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.
376
+ * for the work. When the chain ends in a fetch, the row names the outer span
377
+ * and then the fetch (`await getArtistDirectory() → fetch GET …`): the code
378
+ * that asked, and the I/O it did. Otherwise it reads as the outer span. Cache
379
+ * events from every span in the row are kept.
350
380
  */
351
381
  function formatRow(
352
382
  row: WaterfallRow<LogSpan>,
353
- lines: string[],
383
+ lines: ColumnLine[],
354
384
  prefix: string,
355
385
  connector: string,
356
386
  bodies: ReadonlyMap<string | undefined, readonly LogSpan[]>,
@@ -363,19 +393,14 @@ function formatRow(
363
393
  const leaf = row.folded.at(-1);
364
394
  const startMs = Math.round(relativeMs(outer.startTime, rootStart));
365
395
  const endMs = Math.round(relativeMs(outer.endTime, rootStart));
366
- const durationMs = endMs - startMs;
367
- const slow = (text: string) => (durationMs > slowPhaseMs ? style('yellow', text) : text);
368
396
  const envTag = (span: ReadableSpan) =>
369
397
  `${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}`;
398
+ // A span's name as its row shows it: an await's label already starts with
399
+ // `await`, so it gets no environment tag.
400
+ const named = (span: ReadableSpan) =>
401
+ `${span.name === AWAIT_SPAN_NAME ? '' : envTag(span)}${devSpanLabel(span.name, span.attributes).label}`;
378
402
  const outcome = accessOutcome(outer);
403
+ const lead = `${prefix}${connector} `;
379
404
 
380
405
  if (leaf?.name === FETCH_SPAN_NAME || outer.name === FETCH_SPAN_NAME) {
381
406
  const fetch = leaf?.name === FETCH_SPAN_NAME ? leaf : row.span;
@@ -383,33 +408,52 @@ function formatRow(
383
408
  // The reads' own time: work the app did between headers and reading
384
409
  // the body is not body time. Codex review on #1290.
385
410
  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),
411
+ const lastReadEnd = reads.reduce((end, r) => Math.max(end, r.endMs), -Infinity);
412
+ // The row runs to the end of the body read, past the fetch span's end.
413
+ const end =
414
+ lastReadEnd > -Infinity
415
+ ? Math.max(endMs, Math.round(lastReadEnd - hrTimeToMs(rootStart)))
416
+ : endMs;
417
+ // The parenthesized time is the fetch's own: an outer loader's duration
418
+ // already includes the body read, so adding `+ body` to it counted the
419
+ // body twice. Codex review on #1290. Rounded from the same relative
420
+ // times as the columns, so an unfolded fetch's note never contradicts
421
+ // its duration column by a rounding.
422
+ const fetchStart = Math.round(relativeMs(fetch.span.startTime, rootStart));
423
+ const fetchEnd = Math.round(relativeMs(fetch.span.endTime, rootStart));
424
+ const fetchParts = formatFetchParts(fetch.span, {
425
+ headersMs: fetchEnd - fetchStart,
402
426
  bodyMs,
427
+ rowMs: end - startMs,
428
+ });
429
+ // The outer span of a folded chain names the code that asked for the
430
+ // fetch; an access gate that folded into its fetch keeps its outcome.
431
+ // Codex review on #1290.
432
+ // `await fetch(url)` is the fetch itself: naming it would say it twice.
433
+ const askerName = named(outer);
434
+ const asker =
435
+ row.folded.length > 0 && !askerName.startsWith('await fetch(') ? `${askerName} → ` : '';
436
+ lines.push({
437
+ startMs,
438
+ durationMs: end - startMs,
439
+ slow: end - startMs > slowPhaseMs,
440
+ text: `${lead}${asker}${fetchParts.head}`,
441
+ tail: `${fetchParts.tail}${outcome ? style('dim', outcome) : ''}`,
403
442
  });
404
- lines.push(outcome ? `${fetchLine}${style('dim', outcome)}` : fetchLine);
405
443
  } 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)}`);
444
+ // A framework span folded into its await keeps both names:
445
+ // `[proxy] proxy.ts → await next()`. Otherwise the row reads as its
446
+ // first await, the code that asked for the work.
447
+ const first = row.folded[0]?.span;
448
+ const frame = outer.name !== AWAIT_SPAN_NAME && first ? `${named(outer)} → ` : '';
449
+ const label = frame && first ? named(first) : named(outer);
450
+ lines.push({
451
+ startMs,
452
+ durationMs: endMs - startMs,
453
+ slow: endMs - startMs > slowPhaseMs,
454
+ text: `${lead}${frame}${label}`,
455
+ tail: outcome ? style('dim', outcome) : '',
456
+ });
413
457
  }
414
458
 
415
459
  // Span events (cache hits/misses) as child annotations
@@ -421,9 +465,9 @@ function formatRow(
421
465
  const durMs = event.attributes?.['duration_ms'] as number | undefined;
422
466
  const durStr = durMs !== undefined ? ` ${durMs < 1 ? '<1' : Math.round(durMs)}ms` : '';
423
467
  const stale = event.attributes?.['stale'] ? ' (stale)' : '';
424
- lines.push(
425
- `${childPrefix}${style('dim', `└── ${key} timber.cache ${hitMiss}${durStr}${stale}`)}`
426
- );
468
+ lines.push({
469
+ text: `${childPrefix}${style('dim', `└── ${key} timber.cache ${hitMiss}${durStr}${stale}`)}`,
470
+ });
427
471
  }
428
472
  }
429
473
  }
@@ -154,6 +154,15 @@ function slotPrefix(attrs: SpanAttributes): string {
154
154
  return slot ? `${String(slot)} ` : '';
155
155
  }
156
156
 
157
+ /**
158
+ * A fetch URL as the terminal tree and the pill show it: without its scheme,
159
+ * which is `https://` for nearly every fetch and only makes the line longer
160
+ * (TIM-1631).
161
+ */
162
+ export function fetchDisplayUrl(url: string): string {
163
+ return url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '');
164
+ }
165
+
157
166
  /**
158
167
  * Map a span to its display label and environment tag. One mapping for the
159
168
  * terminal tree and the dev request pill, so the two never name a span
@@ -203,7 +212,10 @@ export function devSpanLabel(name: string, attrs: SpanAttributes): { label: stri
203
212
  case FETCH_SPAN_NAME: {
204
213
  const fetchMethod = attrs['http.request.method'] ?? 'GET';
205
214
  const fetchUrl = attrs['http.url'] ?? '';
206
- return { label: `fetch ${String(fetchMethod)} ${String(fetchUrl)}`, env: 'fetch' };
215
+ return {
216
+ label: `fetch ${String(fetchMethod)} ${fetchDisplayUrl(String(fetchUrl))}`,
217
+ env: 'fetch',
218
+ };
207
219
  }
208
220
  default:
209
221
  return { label: name, env: 'rsc' };
@@ -177,10 +177,38 @@ export function buildWaterfall<T extends WaterfallSpan>(
177
177
  const hidden = (s: T) => hideWaits && waits.has(s.spanId);
178
178
 
179
179
  /** Shown children, with an unkept child's shown descendants in its place. */
180
- const visibleChildren = (parent: string | undefined): T[] =>
180
+ const shownUnder = (parent: string | undefined): T[] =>
181
181
  (children.get(parent) ?? []).flatMap((s) =>
182
- hidden(s) ? [] : kept(s) ? [s] : visibleChildren(s.spanId)
182
+ hidden(s) ? [] : kept(s) ? [s] : shownUnder(s.spanId)
183
183
  );
184
+ /**
185
+ * The same, in start order: a skipped span's descendants are drawn among
186
+ * its siblings by when they started, not at the skipped span's place (a
187
+ * sub-1ms layout's pages above an await that started 1.6s earlier,
188
+ * TIM-1631).
189
+ */
190
+ const visibleChildren = (parent: string | undefined): T[] =>
191
+ shownUnder(parent).sort((a, b) => a.startMs - b.startMs);
192
+
193
+ /**
194
+ * When a span's I/O ended: its own end, or later through the awaits,
195
+ * fetches and body reads under it. A fetch span ends at the headers and its
196
+ * body read is a child, so a fetch's I/O runs to the end of the read, even
197
+ * when the read happens after the `await fetch(url)` around it returned.
198
+ * Waits and framework spans don't count: they did no I/O of their own.
199
+ */
200
+ const ioEnds = new Map<string, number>();
201
+ const ioEnd = (span: T): number => {
202
+ let end = ioEnds.get(span.spanId);
203
+ if (end === undefined) {
204
+ const io = (children.get(span.spanId) ?? []).filter(
205
+ (kid) => IO_SPANS.has(kid.name) && kid.attributes[AWAIT_WAIT_ATTRIBUTE] !== true
206
+ );
207
+ end = Math.max(span.endMs, ...io.map(ioEnd));
208
+ ioEnds.set(span.spanId, end);
209
+ }
210
+ return end;
211
+ };
184
212
 
185
213
  const origin = Math.min(...spans.map((s) => s.startMs));
186
214
  const rows: WaterfallRow<T>[] = [];
@@ -192,7 +220,11 @@ export function buildWaterfall<T extends WaterfallSpan>(
192
220
  // dimmed row, not vanish into its parent. A child that outlives its
193
221
  // parent (a fetch raced against a timeout) never folds either: the row
194
222
  // draws the parent's interval, which would drop the rest of the child's
195
- // time. Codex review on #1288.
223
+ // time. Codex review on #1288. Coverage counts the child's I/O through
224
+ // the parent's end, so a loader whose fetch spent most of its time on the
225
+ // body read still folds into it (TIM-1631). A body read after the parent
226
+ // returned (`await fetch(url)`, then `res.json()` elsewhere) is the
227
+ // fetch's own row's business, drawn beside it, not a reason not to fold.
196
228
  const foldable = (kid: T | undefined): kid is T =>
197
229
  kid !== undefined &&
198
230
  !waits.has(kid.spanId) &&
@@ -200,7 +232,7 @@ export function buildWaterfall<T extends WaterfallSpan>(
200
232
  (kid.name === AWAIT_SPAN_NAME && !IO_SPANS.has(tail.name))) &&
201
233
  kid.startMs >= tail.startMs &&
202
234
  kid.endMs <= tail.endMs &&
203
- duration(kid) >= FOLD_COVERAGE * duration(tail);
235
+ Math.min(ioEnd(kid), tail.endMs) - kid.startMs >= FOLD_COVERAGE * duration(tail);
204
236
  if (fold && !expanded.has(span.spanId)) {
205
237
  for (
206
238
  let only = kids.length === 1 ? kids[0] : undefined;