Repository navigation
Expand file tree
/
Copy pathreact-profile-command.ts
More file actions
462 lines (432 loc) · 15.9 KB
/
Copy pathreact-profile-command.ts
File metadata and controls
462 lines (432 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import fs from 'node:fs';
import path from 'node:path';
import { parseArgs } from 'node:util';
import { AppError } from '@agent-device/kernel/errors';
import { safeSessionName } from '@agent-device/host-kit/session-paths';
import type { CliFlags } from '@agent-device/contracts/command';
import { resolveMetroServerUrl } from '../../metro/metro-reload-endpoints.ts';
import { readMetroSessionHints } from '../../metro/metro-session-hints.ts';
import { isRemoteBridgeBackend } from '../commands/remote-bridge.ts';
import {
InspectorSession,
listMetroInspectorTargets,
selectReactNativeTarget,
targetAppId,
type MetroInspectorTarget,
} from './metro-inspector.ts';
import {
REACT_PROFILER_RUNTIME_GLOBAL,
REACT_PROFILER_RUNTIME_SOURCE,
REACT_PROFILER_RUNTIME_VERSION,
} from './react-profiler-runtime.ts';
import { analyzeReactProfile, type ReactProfileAnalysis } from './react-profile-analysis.ts';
import {
selectPropKindRequests,
type CommitProfile,
type ComponentProfile,
type PropKindsById,
type RawReactProfile,
} from './react-profile-renders.ts';
import {
componentsByRenders,
DEFAULT_FINDING_LIMIT,
findComponent,
formatSeconds,
formatCommit,
formatComponentReport,
formatProfileSummary,
formatRerenders,
formatSlowComponents,
formatTimeline,
timelineCommits,
} from './react-profile-format.ts';
const REACT_PROFILE_SUBCOMMANDS = [
'start',
'stop',
'status',
'slow',
'rerenders',
'report',
'timeline',
'commit',
] as const;
type ReactProfileSubcommand = (typeof REACT_PROFILE_SUBCOMMANDS)[number];
export type ReactProfileCommandOptions = {
flags?: Partial<Pick<CliFlags, 'json' | 'leaseBackend' | 'metroPublicBaseUrl'>>;
stateDir: string;
session: string;
};
type ProfileArgs = {
subcommand: ReactProfileSubcommand;
target?: string;
limit?: number;
app?: string;
metroDevice?: string;
metroHost?: string;
metroPort?: string;
bundleUrl?: string;
sort?: 'timeline' | 'duration';
};
/** Analysis plus the runtime it came from, as `profile stop` saves it for the drill-down views. */
type SavedReactProfile = {
savedAt: string;
appId?: string;
deviceName?: string;
analysis: ReactProfileAnalysis;
};
type RuntimeFailure = { ok: false; reason: string; elapsedMs?: number };
type StartResult = { ok: true; attach: string } | RuntimeFailure;
type StopResult = ({ ok: true } & RawReactProfile) | RuntimeFailure;
type StatusResult = { profiling: boolean; elapsedMs: number | null };
const SUBCOMMANDS_WITH_TARGET = new Set<ReactProfileSubcommand>(['report', 'commit']);
const POSITIVE_INTEGER = /^[1-9]\d*$/;
function isReactProfileSubcommand(value: string | undefined): value is ReactProfileSubcommand {
return REACT_PROFILE_SUBCOMMANDS.includes(value as ReactProfileSubcommand);
}
const PROFILE_OPTIONS = {
limit: { type: 'string' },
app: { type: 'string' },
'metro-device': { type: 'string' },
'metro-host': { type: 'string' },
'metro-port': { type: 'string' },
'bundle-url': { type: 'string' },
sort: { type: 'string' },
} as const;
function parseProfileOptions(args: string[]) {
try {
return parseArgs({ args, allowPositionals: true, strict: true, options: PROFILE_OPTIONS });
} catch (error) {
throw new AppError('INVALID_ARGS', error instanceof Error ? error.message : String(error));
}
}
function parseProfileArgs(args: string[]): ProfileArgs {
const [subcommand, ...rest] = args;
if (!isReactProfileSubcommand(subcommand)) {
throw new AppError(
'INVALID_ARGS',
`Unknown react-devtools profile command: ${subcommand ?? '(none)'}.`,
{ hint: `Use one of: ${REACT_PROFILE_SUBCOMMANDS.join(', ')}.` },
);
}
const { values, positionals } = parseProfileOptions(rest);
const expected = SUBCOMMANDS_WITH_TARGET.has(subcommand) ? 1 : 0;
if (positionals.length > expected) {
throw new AppError(
'INVALID_ARGS',
`Unexpected argument for react-devtools profile ${subcommand}: ${positionals[expected]}.`,
);
}
if (values.limit !== undefined && !POSITIVE_INTEGER.test(values.limit)) {
throw new AppError('INVALID_ARGS', `Invalid --limit: ${values.limit}. Use a positive integer.`);
}
const limit = values.limit === undefined ? undefined : Number(values.limit);
if (values.sort !== undefined && values.sort !== 'timeline' && values.sort !== 'duration') {
throw new AppError('INVALID_ARGS', `Invalid --sort: ${values.sort}. Use timeline or duration.`);
}
return {
subcommand,
target: positionals[0],
limit,
app: values.app,
metroDevice: values['metro-device'],
metroHost: values['metro-host'],
metroPort: values['metro-port'],
bundleUrl: values['bundle-url'],
sort: values.sort as ProfileArgs['sort'],
};
}
/** Explicit flags, then a remote bridge's public dev-server URL, then the session's Metro binding. */
function resolveDevServerUrl(args: ProfileArgs, options: ReactProfileCommandOptions): URL {
const publicBaseUrl = options.flags?.metroPublicBaseUrl?.trim();
const explicit =
args.metroHost !== undefined || args.metroPort !== undefined || args.bundleUrl !== undefined;
if (!explicit && publicBaseUrl && isRemoteBridgeBackend(options.flags?.leaseBackend)) {
return resolveMetroServerUrl({ bundleUrl: publicBaseUrl });
}
const binding = explicit
? undefined
: readMetroSessionHints({ stateDir: options.stateDir, session: options.session });
return resolveMetroServerUrl({
metroHost: args.metroHost,
metroPort: args.metroPort,
bundleUrl: args.bundleUrl,
runtime: binding ? { bundleUrl: binding.controlBaseUrl } : undefined,
});
}
async function withAppRuntime<T>(
args: ProfileArgs,
options: ReactProfileCommandOptions,
action: (session: InspectorSession, target: MetroInspectorTarget) => Promise<T>,
): Promise<T> {
const serverUrl = resolveDevServerUrl(args, options);
const target = selectReactNativeTarget(await listMetroInspectorTargets(serverUrl), {
appId: args.app,
device: args.metroDevice,
});
const session: InspectorSession = await InspectorSession.connect(target.webSocketDebuggerUrl);
try {
await session.evaluate(
`(${REACT_PROFILER_RUNTIME_SOURCE})(${JSON.stringify(REACT_PROFILER_RUNTIME_VERSION)})`,
);
return await action(session, target);
} finally {
session.close();
}
}
async function callRuntime<T>(
session: InspectorSession,
method: string,
argument?: unknown,
): Promise<T> {
const call = `${REACT_PROFILER_RUNTIME_GLOBAL}.${method}(${argument === undefined ? '' : JSON.stringify(argument)})`;
const value = await session.evaluate(call);
if (typeof value !== 'string') {
throw new AppError('COMMAND_FAILED', `The profiler runtime returned no result for ${method}.`);
}
return JSON.parse(value) as T;
}
const RUNTIME_FAILURES: Record<string, { message: string; hint: string }> = {
'no-devtools-hook': {
message: 'The app runtime has no React DevTools hook.',
hint: 'Profile a development build; release builds do not include React DevTools.',
},
'no-react-renderer': {
message: 'React has not rendered in this app runtime yet.',
hint: 'Wait for the app to finish loading its bundle, then retry.',
},
'no-devtools-backend': {
message: 'This React Native version exposes no React DevTools backend to attach to.',
hint: 'React Native 0.74 or newer is required.',
},
'backend-attach-failed': {
message: 'The React DevTools backend did not attach to the app renderer.',
hint: 'Reload the app and retry.',
},
'start-failed': {
message: 'The React renderer refused to start profiling.',
hint: 'Profile a development build; production renderers do not record render timings.',
},
'not-profiling': {
message: 'No React profile is recording in this app runtime.',
hint: 'Run react-devtools profile start first. A reload or app restart discards a recording.',
},
};
function runtimeFailure(result: RuntimeFailure): AppError {
const known = RUNTIME_FAILURES[result.reason];
return new AppError(
'COMMAND_FAILED',
known?.message ?? `React profiling failed: ${result.reason}.`,
{
reason: result.reason,
...(known ? { hint: known.hint } : {}),
},
);
}
function savedProfilePath(options: ReactProfileCommandOptions): string {
return path.join(options.stateDir, 'react-profiles', `${safeSessionName(options.session)}.json`);
}
function writeSavedProfile(
options: ReactProfileCommandOptions,
profile: SavedReactProfile,
): string {
const filePath = savedProfilePath(options);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, `${JSON.stringify(profile)}\n`, 'utf8');
return filePath;
}
function isSavedProfile(value: SavedReactProfile | undefined): value is SavedReactProfile {
const analysis = value?.analysis;
return (
analysis?.version === 1 &&
Array.isArray(analysis.components) &&
Array.isArray(analysis.commits) &&
Array.isArray(analysis.findings)
);
}
function readSavedProfile(options: ReactProfileCommandOptions): SavedReactProfile {
let raw: string;
try {
raw = fs.readFileSync(savedProfilePath(options), 'utf8');
} catch {
throw new AppError('COMMAND_FAILED', `No React profile saved for session ${options.session}.`, {
hint: 'Run react-devtools profile start, perform the interaction, then react-devtools profile stop.',
});
}
let saved: SavedReactProfile | undefined;
try {
saved = JSON.parse(raw) as SavedReactProfile;
} catch {
saved = undefined;
}
if (!isSavedProfile(saved)) {
throw new AppError('COMMAND_FAILED', 'The saved React profile has an unsupported format.', {
hint: 'Record a new profile with react-devtools profile start and stop.',
});
}
return saved;
}
const elapsed = (elapsedMs: number) => formatSeconds(Math.max(0, elapsedMs));
async function startProfile(
args: ProfileArgs,
options: ReactProfileCommandOptions,
): Promise<{ app: string; message: string }> {
return await withAppRuntime(args, options, async (session, target) => {
const result = await callRuntime<StartResult>(session, 'start');
const app = targetAppId(target);
if (!result.ok && result.reason === 'already-profiling') {
return {
app,
alreadyProfiling: true,
message: `Already profiling ${app} for ${elapsed(result.elapsedMs ?? 0)}; run react-devtools profile stop to read it.`,
};
}
if (!result.ok) throw runtimeFailure(result);
return {
app,
attach: result.attach,
message: `Profiling React renders in ${app}. Perform the interaction, then run react-devtools profile stop.`,
};
});
}
/**
* Classifies changed prop values on mounted instances. The recording has already left the app, so
* a failure here costs only that detail and is reported as a note on the analysis.
*/
async function describeChangedProps(
session: InspectorSession,
profile: RawReactProfile,
): Promise<{ propKinds: PropKindsById; notes: string[] }> {
const request = selectPropKindRequests(profile);
if (Object.keys(request).length === 0) return { propKinds: {}, notes: [] };
try {
return {
propKinds: await callRuntime<PropKindsById>(session, 'describeProps', request),
notes: [],
};
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
return { propKinds: {}, notes: [`Changed prop values could not be inspected: ${reason}`] };
}
}
async function stopProfile(
args: ProfileArgs,
options: ReactProfileCommandOptions,
): Promise<SavedReactProfile> {
return await withAppRuntime(args, options, async (session, target) => {
const result = await callRuntime<StopResult>(session, 'stop');
if (!result.ok) throw runtimeFailure(result);
const { propKinds, notes } = await describeChangedProps(session, result);
const saved: SavedReactProfile = {
savedAt: new Date().toISOString(),
appId: targetAppId(target),
deviceName: target.deviceName,
analysis: analyzeReactProfile(result, propKinds, notes),
};
writeSavedProfile(options, saved);
return saved;
});
}
function formatStatus(status: StatusResult, app: string): string {
return status.profiling && status.elapsedMs !== null
? `Profiling ${app} for ${elapsed(status.elapsedMs)}.`
: `Not profiling ${app}.`;
}
type Emit = (text: string, data: unknown) => void;
type SubcommandHandler = (
args: ProfileArgs,
options: ReactProfileCommandOptions,
emit: Emit,
) => Promise<void>;
function requireComponent(
analysis: ReactProfileAnalysis,
name: string | undefined,
): ComponentProfile {
if (!name)
throw new AppError('INVALID_ARGS', 'react-devtools profile report requires a component name.');
const component = findComponent(analysis, name);
if (!component) {
throw new AppError('COMMAND_FAILED', `No renders of ${name} in the saved profile.`, {
hint: 'Use a name from react-devtools profile slow or profile rerenders.',
});
}
return component;
}
function requireCommit(analysis: ReactProfileAnalysis, target: string | undefined): CommitProfile {
const digits = (target ?? '').replace(/^#/, '');
const commit = /^\d+$/.test(digits) ? analysis.commits[Number(digits)] : undefined;
if (!commit) {
throw new AppError('INVALID_ARGS', `No commit ${target ?? '(none)'} in the saved profile.`, {
hint: `Use a commit index from 0 to ${Math.max(analysis.commits.length - 1, 0)}.`,
});
}
return commit;
}
const SUBCOMMAND_HANDLERS: Record<ReactProfileSubcommand, SubcommandHandler> = {
start: async (args, options, emit) => {
const started = await startProfile(args, options);
emit(started.message, started);
},
status: async (args, options, emit) => {
const status = await withAppRuntime(args, options, async (session, target) => ({
app: targetAppId(target),
...(await callRuntime<StatusResult>(session, 'status')),
}));
emit(formatStatus(status, status.app), status);
},
stop: async (args, options, emit) => {
const saved = await stopProfile(args, options);
const { analysis } = saved;
emit(formatProfileSummary(analysis, args.limit ?? DEFAULT_FINDING_LIMIT), {
appId: saved.appId,
wallMs: analysis.wallMs,
commitCount: analysis.commitCount,
renderMs: analysis.renderMs,
slowCommitCount: analysis.slowCommitCount,
worstCommit: analysis.worstCommit,
findings: analysis.findings.slice(0, args.limit ?? analysis.findings.length),
savedTo: savedProfilePath(options),
});
},
slow: async (args, options, emit) => {
const { analysis } = readSavedProfile(options);
const limit = args.limit ?? 10;
emit(formatSlowComponents(analysis, limit), analysis.components.slice(0, limit));
},
rerenders: async (args, options, emit) => {
const { analysis } = readSavedProfile(options);
const limit = args.limit ?? 10;
emit(formatRerenders(analysis, limit), componentsByRenders(analysis).slice(0, limit));
},
report: async (args, options, emit) => {
const { analysis } = readSavedProfile(options);
const component = requireComponent(analysis, args.target);
emit(formatComponentReport(analysis, component), component);
},
timeline: async (args, options, emit) => {
const { analysis } = readSavedProfile(options);
const limit = args.limit ?? 20;
const byDuration = args.sort === 'duration';
emit(
formatTimeline(analysis, limit, byDuration),
timelineCommits(analysis, byDuration).slice(0, limit),
);
},
commit: async (args, options, emit) => {
const { analysis } = readSavedProfile(options);
const commit = requireCommit(analysis, args.target);
emit(formatCommit(commit, args.limit ?? 10), commit);
},
};
export async function runReactProfileCommand(
args: string[],
options: ReactProfileCommandOptions,
): Promise<number> {
const json = options.flags?.json === true;
const parsed = parseProfileArgs(args);
await SUBCOMMAND_HANDLERS[parsed.subcommand](parsed, options, (text, data) => {
process.stdout.write(
json ? `${JSON.stringify({ success: true, data }, null, 2)}\n` : `${text}\n`,
);
});
return 0;
}