@timber-js/app 0.2.0-alpha.229 → 0.2.0-alpha.230
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.
- package/dist/_chunks/dev-span-_NzMX-au.js.map +1 -1
- package/dist/client/dev-pill/store.d.ts +11 -2
- package/dist/client/dev-pill/store.d.ts.map +1 -1
- package/dist/client/dev-pill/view.d.ts.map +1 -1
- package/dist/dev-tools/await-span.d.ts +1 -1
- package/dist/dev-tools/await-span.d.ts.map +1 -1
- package/dist/index.js +122 -21
- package/dist/index.js.map +1 -1
- package/dist/plugins/dev-await.d.ts +43 -2
- package/dist/plugins/dev-await.d.ts.map +1 -1
- package/dist/shared/dev-span.d.ts +3 -1
- package/dist/shared/dev-span.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/client/dev-pill/store.ts +34 -11
- package/src/client/dev-pill/view.ts +68 -20
- package/src/dev-tools/await-span.ts +40 -11
- package/src/plugins/dev-await.ts +168 -21
- package/src/shared/dev-span.ts +7 -1
package/src/plugins/dev-await.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* const rows = await db.select().from(users);
|
|
8
8
|
* // becomes
|
|
9
|
-
* const rows = await __timber_await$(
|
|
9
|
+
* const rows = await __timber_await$(() => (db.select().from(users)),
|
|
10
10
|
* "db.select().from(users)", "app/users/page.tsx:12");
|
|
11
11
|
*
|
|
12
12
|
* `__timber_await$` is declared once per module and looks the wrapper up on
|
|
@@ -15,6 +15,11 @@
|
|
|
15
15
|
* global rather than an injected import, so the rewrite needs no resolvable
|
|
16
16
|
* specifier from a workspace package outside the app.
|
|
17
17
|
*
|
|
18
|
+
* Vite 8 compiles TS/JSX before any plugin transform runs (`enforce: 'pre'`
|
|
19
|
+
* included), so the module this sees has moved lines and reprinted text.
|
|
20
|
+
* Labels and locations are mapped back through the module's combined source
|
|
21
|
+
* map (`originalFromMap`), so they are the code and lines as written.
|
|
22
|
+
*
|
|
18
23
|
* Scope: the RSC environment, `vite dev` only; every module outside
|
|
19
24
|
* node_modules and outside timber itself, so a monorepo's `packages/db`
|
|
20
25
|
* (where the query actually is) is covered. Skipped: `'use client'`
|
|
@@ -26,7 +31,8 @@
|
|
|
26
31
|
* See design/50-dev-request-pill.md §"Phase 2".
|
|
27
32
|
*/
|
|
28
33
|
|
|
29
|
-
import { existsSync } from 'node:fs';
|
|
34
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
35
|
+
import { SourceMap } from 'node:module';
|
|
30
36
|
import { dirname, join, relative } from 'node:path';
|
|
31
37
|
import { fileURLToPath } from 'node:url';
|
|
32
38
|
import MagicString from 'magic-string';
|
|
@@ -37,7 +43,7 @@ import type { PluginContext } from '../plugin-context.ts';
|
|
|
37
43
|
const HELPER = '__timber_await$';
|
|
38
44
|
|
|
39
45
|
/** Longest label kept, in characters. */
|
|
40
|
-
const LABEL_MAX =
|
|
46
|
+
const LABEL_MAX = 140;
|
|
41
47
|
|
|
42
48
|
const SCRIPT_RE = /\.[cm]?[jt]sx?$/;
|
|
43
49
|
|
|
@@ -76,6 +82,20 @@ const FUNCTION_TYPES = new Set([
|
|
|
76
82
|
'ArrowFunctionExpression',
|
|
77
83
|
]);
|
|
78
84
|
|
|
85
|
+
/** An await in the operand itself (not in a nested function) needs an async thunk. */
|
|
86
|
+
function containsAwait(node: Node): boolean {
|
|
87
|
+
if (node.type === 'AwaitExpression') return true;
|
|
88
|
+
if (FUNCTION_TYPES.has(node.type)) return false;
|
|
89
|
+
return children(node).some(containsAwait);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Parser dialect for a module path: the transform sees original source. */
|
|
93
|
+
export function langFor(file: string): 'ts' | 'tsx' | 'jsx' {
|
|
94
|
+
if (/\.tsx$/.test(file)) return 'tsx';
|
|
95
|
+
if (/\.[cm]?ts$/.test(file)) return 'ts';
|
|
96
|
+
return 'jsx';
|
|
97
|
+
}
|
|
98
|
+
|
|
79
99
|
function containsYield(node: Node): boolean {
|
|
80
100
|
if (node.type === 'YieldExpression') return true;
|
|
81
101
|
// A nested function's yields belong to it.
|
|
@@ -166,41 +186,104 @@ function label(source: string): string {
|
|
|
166
186
|
return collapsed.length > LABEL_MAX ? `${collapsed.slice(0, LABEL_MAX - 1)}…` : collapsed;
|
|
167
187
|
}
|
|
168
188
|
|
|
189
|
+
/**
|
|
190
|
+
* The module as the developer wrote it, for labels and line numbers.
|
|
191
|
+
*
|
|
192
|
+
* Vite 8 compiles TS/JSX before any plugin's `transform` runs, `enforce:
|
|
193
|
+
* 'pre'` included, so the code the transform sees has moved lines and
|
|
194
|
+
* reprinted text (a real report: fetcher.ts:12 shown as :11, :13 as :16,
|
|
195
|
+
* single quotes printed as double). The plugin maps positions back through
|
|
196
|
+
* the module's combined source map.
|
|
197
|
+
*/
|
|
198
|
+
export interface OriginalSource {
|
|
199
|
+
code: string;
|
|
200
|
+
lang: 'ts' | 'tsx' | 'jsx';
|
|
201
|
+
/** Offset in `code` for an offset in the transformed module, or null if unmapped. */
|
|
202
|
+
offsetOf(generatedOffset: number): number | null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function lineStartsOf(text: string): number[] {
|
|
206
|
+
const starts = [0];
|
|
207
|
+
for (let i = 0; i < text.length; i++) if (text[i] === '\n') starts.push(i + 1);
|
|
208
|
+
return starts;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 1-based line of an offset. */
|
|
212
|
+
function lineAt(starts: number[], offset: number): number {
|
|
213
|
+
let lo = 0;
|
|
214
|
+
let hi = starts.length - 1;
|
|
215
|
+
while (lo < hi) {
|
|
216
|
+
const mid = (lo + hi + 1) >> 1;
|
|
217
|
+
if (starts[mid]! <= offset) lo = mid;
|
|
218
|
+
else hi = mid - 1;
|
|
219
|
+
}
|
|
220
|
+
return lo + 1;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The operand's label from the original source, redacted. Null when the
|
|
225
|
+
* mapping doesn't give a sane slice; the caller falls back to the
|
|
226
|
+
* transformed text.
|
|
227
|
+
*/
|
|
228
|
+
function originalLabel(original: OriginalSource, arg: Node): string | null {
|
|
229
|
+
const start = original.offsetOf(arg.start);
|
|
230
|
+
const last = original.offsetOf(arg.end - 1);
|
|
231
|
+
if (start === null || last === null || last < start) return null;
|
|
232
|
+
const slice = original.code.slice(start, last + 1);
|
|
233
|
+
if (slice.length > (arg.end - arg.start) * 4 + 40) return null;
|
|
234
|
+
try {
|
|
235
|
+
const parsed: unknown = parseAst(`(${slice});`, { lang: original.lang });
|
|
236
|
+
if (!isNode(parsed)) return null;
|
|
237
|
+
const stmt = (parsed.body as Node[] | undefined)?.[0];
|
|
238
|
+
let expr = stmt?.expression;
|
|
239
|
+
if (isNode(expr) && expr.type === 'ParenthesizedExpression') expr = expr.expression;
|
|
240
|
+
if (!isNode(expr)) return null;
|
|
241
|
+
return label(redactedSource(`(${slice});`, expr));
|
|
242
|
+
} catch {
|
|
243
|
+
return null; // Mapped to something that isn't an expression.
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
169
247
|
/**
|
|
170
248
|
* Rewrite the awaits in one module. Returns null when nothing changed.
|
|
171
249
|
* Exported for tests; `relPath` is the location prefix shown in the pill.
|
|
250
|
+
* With `original`, labels and lines come from the source as written.
|
|
172
251
|
*/
|
|
173
252
|
export function instrumentAwaits(
|
|
174
253
|
code: string,
|
|
175
|
-
relPath: string
|
|
254
|
+
relPath: string,
|
|
255
|
+
options: { lang?: 'ts' | 'tsx' | 'jsx'; original?: () => OriginalSource | null } = {}
|
|
176
256
|
): { code: string; map: ReturnType<MagicString['generateMap']> } | null {
|
|
177
257
|
if (!code.includes('await')) return null;
|
|
178
258
|
|
|
179
259
|
let parsed: unknown;
|
|
180
260
|
try {
|
|
181
|
-
|
|
182
|
-
// anything that reaches it untransformed.
|
|
183
|
-
parsed = parseAst(code, { lang: 'jsx' });
|
|
261
|
+
parsed = parseAst(code, { lang: options.lang ?? langFor(relPath) });
|
|
184
262
|
} catch {
|
|
185
263
|
return null; // Not ours to report; the module's own parse will.
|
|
186
264
|
}
|
|
187
265
|
if (!isNode(parsed)) return null;
|
|
188
266
|
const program = parsed;
|
|
189
267
|
|
|
268
|
+
// Built on the first await found: modules without one never pay for it.
|
|
269
|
+
let original: OriginalSource | null | undefined;
|
|
270
|
+
let originalStarts: number[] = [];
|
|
271
|
+
const getOriginal = () => {
|
|
272
|
+
if (original === undefined) {
|
|
273
|
+
original = options.original?.() ?? null;
|
|
274
|
+
if (original) originalStarts = lineStartsOf(original.code);
|
|
275
|
+
}
|
|
276
|
+
return original;
|
|
277
|
+
};
|
|
278
|
+
|
|
190
279
|
const prologue = directives(program);
|
|
191
280
|
if (prologue.names.includes('use client')) return null;
|
|
192
281
|
|
|
193
|
-
const lineStarts =
|
|
194
|
-
for (let i = 0; i < code.length; i++) if (code[i] === '\n') lineStarts.push(i + 1);
|
|
282
|
+
const lineStarts = lineStartsOf(code);
|
|
195
283
|
const lineOf = (offset: number) => {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const mid = (lo + hi + 1) >> 1;
|
|
200
|
-
if (lineStarts[mid]! <= offset) lo = mid;
|
|
201
|
-
else hi = mid - 1;
|
|
202
|
-
}
|
|
203
|
-
return lo + 1;
|
|
284
|
+
const source = getOriginal();
|
|
285
|
+
const mapped = source?.offsetOf(offset) ?? null;
|
|
286
|
+
return mapped === null ? lineAt(lineStarts, offset) : lineAt(originalStarts, mapped);
|
|
204
287
|
};
|
|
205
288
|
|
|
206
289
|
const s = new MagicString(code);
|
|
@@ -219,11 +302,17 @@ export function instrumentAwaits(
|
|
|
219
302
|
// its CSS virtual module into layouts, which read as a slow app await.
|
|
220
303
|
if (arg.type === 'ImportExpression') return;
|
|
221
304
|
|
|
222
|
-
const
|
|
305
|
+
const source = getOriginal();
|
|
306
|
+
const text = JSON.stringify(
|
|
307
|
+
(source && originalLabel(source, arg)) ?? label(redactedSource(code, arg))
|
|
308
|
+
);
|
|
223
309
|
const location = JSON.stringify(`${relPath}:${lineOf(node.start)}`);
|
|
224
310
|
// Parenthesized: the operand may be a sequence or an object literal.
|
|
225
|
-
// Async
|
|
226
|
-
s
|
|
311
|
+
// Async only when the operand itself awaits: a plain arrow hands the
|
|
312
|
+
// wrapper the operand's own value, so it can tell a shared promise
|
|
313
|
+
// (React.cache, an in-flight load) from new work.
|
|
314
|
+
const thunk = containsAwait(arg) ? 'async () => (' : '() => (';
|
|
315
|
+
s.prependRight(arg.start, `${HELPER}(${thunk}`);
|
|
227
316
|
s.appendLeft(arg.end, `), ${text}, ${location})`);
|
|
228
317
|
count++;
|
|
229
318
|
};
|
|
@@ -240,6 +329,60 @@ export function instrumentAwaits(
|
|
|
240
329
|
return { code: s.toString(), map: s.generateMap({ hires: true }) };
|
|
241
330
|
}
|
|
242
331
|
|
|
332
|
+
/** The slice of a Rollup/Vite combined source map this reads. */
|
|
333
|
+
interface CombinedMap {
|
|
334
|
+
version: number;
|
|
335
|
+
file?: string | null;
|
|
336
|
+
sources: (string | null)[];
|
|
337
|
+
sourcesContent?: (string | null)[] | null;
|
|
338
|
+
names: string[];
|
|
339
|
+
mappings: string;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Map the transformed module back to its original text through its combined
|
|
344
|
+
* source map, using Node's built-in `module.SourceMap`.
|
|
345
|
+
*/
|
|
346
|
+
export function originalFromMap(
|
|
347
|
+
map: CombinedMap,
|
|
348
|
+
file: string,
|
|
349
|
+
generated: string
|
|
350
|
+
): OriginalSource | null {
|
|
351
|
+
const text = map.sourcesContent?.[0] ?? (existsSync(file) ? readFileSync(file, 'utf8') : null);
|
|
352
|
+
if (!text || !map.mappings) return null;
|
|
353
|
+
let consumer: SourceMap;
|
|
354
|
+
try {
|
|
355
|
+
consumer = new SourceMap({
|
|
356
|
+
version: map.version,
|
|
357
|
+
file: map.file ?? file,
|
|
358
|
+
sources: map.sources.map((source) => source ?? ''),
|
|
359
|
+
sourcesContent: (map.sourcesContent ?? []).map((content) => content ?? ''),
|
|
360
|
+
names: map.names,
|
|
361
|
+
mappings: map.mappings,
|
|
362
|
+
sourceRoot: '',
|
|
363
|
+
});
|
|
364
|
+
} catch {
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
const originalStarts = lineStartsOf(text);
|
|
368
|
+
const generatedStarts = lineStartsOf(generated);
|
|
369
|
+
return {
|
|
370
|
+
code: text,
|
|
371
|
+
lang: langFor(file),
|
|
372
|
+
offsetOf(offset) {
|
|
373
|
+
const line = lineAt(generatedStarts, offset) - 1;
|
|
374
|
+
const column = offset - generatedStarts[line]!;
|
|
375
|
+
const entry = consumer.findEntry(line, column);
|
|
376
|
+
if (!('originalLine' in entry)) return null;
|
|
377
|
+
// Within one mapped segment the text is copied as-is, so the original
|
|
378
|
+
// column advances with the generated one.
|
|
379
|
+
const delta = entry.generatedLine === line ? column - entry.generatedColumn : 0;
|
|
380
|
+
const lineStart = originalStarts[entry.originalLine];
|
|
381
|
+
return lineStart === undefined ? null : lineStart + entry.originalColumn + delta;
|
|
382
|
+
},
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
243
386
|
/** Directory of the nearest package.json above this file: timber itself. */
|
|
244
387
|
function findTimberRoot(): string {
|
|
245
388
|
let dir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -262,7 +405,11 @@ export function timberDevAwait(ctx: PluginContext): Plugin {
|
|
|
262
405
|
const file = id.split('?')[0]!;
|
|
263
406
|
if (!SCRIPT_RE.test(file) || file.includes('/node_modules/')) return;
|
|
264
407
|
if (file.startsWith(`${timberRoot}/`)) return;
|
|
265
|
-
|
|
408
|
+
const original = () => originalFromMap(this.getCombinedSourcemap(), file, code);
|
|
409
|
+
// Vite has compiled the module by now, so parse it as JS.
|
|
410
|
+
return (
|
|
411
|
+
instrumentAwaits(code, relative(ctx.root, file), { lang: 'jsx', original }) ?? undefined
|
|
412
|
+
);
|
|
266
413
|
},
|
|
267
414
|
};
|
|
268
415
|
}
|
package/src/shared/dev-span.ts
CHANGED
|
@@ -67,6 +67,8 @@ export const DEV_SPAN_ATTRIBUTES = [
|
|
|
67
67
|
'timber.await_label',
|
|
68
68
|
/** `path/relative/to/root.ts:line` of the await. */
|
|
69
69
|
'timber.await_location',
|
|
70
|
+
/** The awaited promise was already awaited elsewhere: a wait on shared work, not new work. */
|
|
71
|
+
'timber.await_shared',
|
|
70
72
|
] as const;
|
|
71
73
|
|
|
72
74
|
export type DevSpanAttribute = (typeof DEV_SPAN_ATTRIBUTES)[number];
|
|
@@ -170,7 +172,11 @@ export function devSpanLabel(name: string, attrs: SpanAttributes): { label: stri
|
|
|
170
172
|
return { label: `page ${slotPrefix(attrs)}${String(route)}`, env: 'rsc' };
|
|
171
173
|
}
|
|
172
174
|
case AWAIT_SPAN_NAME:
|
|
173
|
-
|
|
175
|
+
// Shared: waited on a promise another await already took — no new work.
|
|
176
|
+
return {
|
|
177
|
+
label: `await ${String(attrs['timber.await_label'] ?? '')}${attrs['timber.await_shared'] === true ? ' (shared)' : ''}`,
|
|
178
|
+
env: 'await',
|
|
179
|
+
};
|
|
174
180
|
case 'timber.fetch': {
|
|
175
181
|
const fetchMethod = attrs['http.request.method'] ?? 'GET';
|
|
176
182
|
const fetchUrl = attrs['http.url'] ?? '';
|