@rnperf/sdk 0.0.0-stage → 0.1.0

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/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # @rnperf/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ In-app performance probe for React Native. Streams JS-thread metrics to the
4
+ [rnperf](../../README.md) daemon, which analyses them and exposes the results over MCP.
5
+
6
+ ```bash
7
+ npm install @rnperf/sdk
8
+ cd ios && pod install # iOS; Android autolinks on the next build
9
+ ```
10
+
11
+ ```ts
12
+ // index.js, before AppRegistry.registerComponent
13
+ import { startPerfMonitor } from '@rnperf/sdk';
14
+
15
+ startPerfMonitor();
16
+ ```
17
+
18
+ No-op in release builds unless `enableInRelease: true`. Everything it does is wrapped in
19
+ try/catch — if the daemon is not running, or an internal React API has moved, the app
20
+ behaves exactly as if the SDK were not installed.
21
+
22
+ ## What it reports
23
+
24
+ - **UI FPS and jank** — real frame cadence from the UI thread, measured in-process on both platforms.
25
+ - **JS FPS** — animation frames the JS thread actually serviced.
26
+ - **JS stalls** — how late a fixed-period timer fires, i.e. the longest synchronous block.
27
+ - **JS heap** — Hermes allocator stats, or `performance.memory` elsewhere.
28
+ - **Component renders** — count, self-time and *wasted* renders (props unchanged from the
29
+ previous commit), read from React's own commit data.
30
+ - **Bridge calls** — legacy bridge traffic, via MessageQueue's spy hook.
31
+ - **Memory** — physical footprint on iOS; Java and native heap on Android.
32
+ - **TTI, screens, marks, measures, crashes.**
33
+
34
+ ## UI-thread frames
35
+
36
+ The package ships a small native module, `RNPerfFrameMonitor`, on both platforms:
37
+
38
+ | | Mechanism | Also reports |
39
+ |---|---|---|
40
+ | **iOS** | `CADisplayLink` on the main run loop, in `NSRunLoopCommonModes` | physical footprint |
41
+ | **Android** | `Choreographer` frame callback, reposted each frame | Java heap, native heap |
42
+
43
+ Autolinking finds it. On iOS run `pod install`; on Android just rebuild.
44
+
45
+ **Why it exists.** On iOS this is the only way to get the number at all — a simulator exposes no
46
+ Core Animation frame stats and a physical device needs an Instruments GUI trace. On Android the
47
+ daemon already reads richer per-frame data over `adb`, so the module is for the case `adb`
48
+ cannot reach: a device on Wi-Fi, a tester's phone, or CI where only the app reports back.
49
+ **When both are available the device-side values win**, since `dumpsys` sees the whole render
50
+ pipeline and the app can only see its own main thread.
51
+
52
+ Both implementations work the same way:
53
+
54
+ - **Frames accumulate natively and JavaScript drains them once per interval.** A bridge event per
55
+ frame would itself cause the jank this is measuring.
56
+ - **Jank is judged against the display's real budget** — 8.3ms on ProMotion, 11.1ms on a 90Hz
57
+ panel — read from `UIScreen.maximumFramesPerSecond` and `Display.getRefreshRate()`. The rate is
58
+ reported alongside as `uiRefreshHz`.
59
+ - **A frame counts as dropped when the interval exceeds 1.5x the budget**, so ordinary vsync
60
+ jitter is not reported as jank.
61
+ - **Measurement pauses in the background**, so a backgrounded app does not report a multi-second
62
+ stall that never happened.
63
+ - **The buffer is capped at 600 intervals.** If JavaScript is blocked longer than that it is not
64
+ draining anyway; frames past the cap still count towards FPS so a stalled app does not look idle.
65
+
66
+ Caveats:
67
+
68
+ - **Expo Go cannot load it.** Run `npx expo prebuild` and use a development build; everything else
69
+ in the SDK still works in Expo Go.
70
+ - **iOS and Android `jankPercent` are not comparable to `adb gfxinfo`'s.** Both modules count
71
+ refreshes actually missed; `gfxinfo` counts frames whose total latency exceeded budget. Compare
72
+ `uiFps` across platforms instead.
73
+ - **Android reports Java and native heap, not PSS.** `Debug.getMemoryInfo()` takes well over a
74
+ frame to return and would cause the jank the module exists to measure; the daemon reads PSS over
75
+ `adb` instead.
76
+ - **Reposting a frame callback keeps requesting vsync**, which costs a little power — the same
77
+ approach React Native's own FPS monitor uses, and only while the monitor is running.
78
+
79
+ Turn it off with `startPerfMonitor({ trackUiFrames: false })`.
80
+
81
+ ## Options
82
+
83
+ ```ts
84
+ startPerfMonitor({
85
+ host: 'auto', // 'auto' derives it from the Metro bundle URL
86
+ port: 8139,
87
+ intervalMs: 1000,
88
+ trackRenders: true,
89
+ trackBridge: true,
90
+ trackUiFrames: true, // native frame module; no-op where it is absent
91
+ enableInRelease: false,
92
+ bundleId: 'com.example.app',
93
+ onStatus: (s) => console.log('[rnperf]', s),
94
+ });
95
+ ```
96
+
97
+ ## API
98
+
99
+ | Export | Purpose |
100
+ |---|---|
101
+ | `startPerfMonitor(options?)` | Begin reporting |
102
+ | `stopPerfMonitor()` | Stop and disconnect |
103
+ | `setScreen(name)` | Attribute following metrics to a screen |
104
+ | `createNavigationTracker(getRouteName)` | Drop-in for React Navigation's `onStateChange` |
105
+ | `mark(name)` / `measure(name, startMark?)` | Custom timings |
106
+ | `reportTTI(screen?, durationMs?)` | Time to interactive |
107
+ | `trackInteraction(name, durationMs)` | Custom interaction timing |
108
+ | `isPerfMonitorConnected()` | Connection state, for a debug overlay |
109
+
110
+ ## Troubleshooting
111
+
112
+ **iOS build fails in `fmt` with "call to consteval function ... is not a constant expression".**
113
+ This is a React Native issue, not this package: RN 0.81 pins fmt 11.0.2, whose consteval
114
+ format-string checks Xcode 27's clang rejects. It happens with or without this SDK installed.
115
+ Force fmt's detection to the no-consteval branch from your Podfile:
116
+
117
+ ```ruby
118
+ post_install do |installer|
119
+ react_native_post_install(installer, config[:reactNativePath], :mac_catalyst_enabled => false)
120
+
121
+ fmt_base = File.join(installer.sandbox.root, 'fmt', 'include', 'fmt', 'base.h')
122
+ if File.exist?(fmt_base)
123
+ text = File.read(fmt_base)
124
+ patched = text.gsub('# define FMT_USE_CONSTEVAL 1', '# define FMT_USE_CONSTEVAL 0')
125
+ File.write(fmt_base, patched) if patched != text
126
+ end
127
+ end
128
+ ```
129
+
130
+ **Nothing connects from a physical iPhone.** Two things iOS requires that a simulator does not:
131
+
132
+ 1. **Local network permission.** Reaching a daemon on your Mac's LAN address counts as local
133
+ network access. Add to `ios/<App>/Info.plist`, or iOS denies it silently with no prompt:
134
+
135
+ ```xml
136
+ <key>NSLocalNetworkUsageDescription</key>
137
+ <string>Connects to the rnperf daemon on your development machine to report performance metrics.</string>
138
+ ```
139
+
140
+ The first connection then prompts; tap **Allow**. If you declined once, re-enable it under
141
+ Settings → Privacy & Security → Local Network.
142
+
143
+ 2. **An explicit host.** A device cannot reach `localhost`, and with an embedded bundle there is no
144
+ Metro URL to infer from, so pass your Mac's LAN address:
145
+ `startPerfMonitor({ host: '192.168.1.21' })`.
146
+
147
+ **The app crashes instantly on iOS 26 or newer**, in
148
+ `__UIApplicationEvaluateRuntimeIssueForNoSceneLifecycleAdoption`. Not this SDK: iOS 26 traps apps
149
+ that never adopt the UIScene lifecycle, and the React Native 0.81 template still creates its window
150
+ in `didFinishLaunchingWithOptions`. Move that into a `UIWindowSceneDelegate` and declare it in
151
+ `UIApplicationSceneManifest`.
152
+
153
+ **`nativeModule=MISSING` on iOS.** Run `cd ios && pod install` and rebuild; autolinking only
154
+ picks the pod up at install time.
155
+
156
+ **`nativeModule=MISSING` on Android.** Check `npx react-native config` reports a non-null
157
+ `dependencies['@rnperf/sdk'].platforms.android`, then rebuild.
158
+
159
+ ## Caveats
160
+
161
+ - Render tracking requires a **development build**: React only populates timing data in its
162
+ profiling build.
163
+ - Under the new architecture most native calls are synchronous JSI and never cross the
164
+ bridge, so `bridgeCalls` reads zero there — that means "nothing on the bridge", not
165
+ "nothing happening".
166
+ - UI-thread frame data needs the native module and therefore a rebuild (plus `pod install` on
167
+ iOS). Without it the SDK still reports everything JS-side; `uiFps` is simply absent.
168
+ - The Android module requires React Native 0.71 or newer, where the `react-android` Maven
169
+ artifact is published. The JavaScript half works from 0.70.
170
+ - `startPerfMonitor()` must run **after** React is imported, so it can attach to React's
171
+ commit hook.
@@ -0,0 +1,21 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "RNPerfSDK"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.license = "MIT"
10
+ s.authors = "rnperf"
11
+ s.homepage = "https://github.com/rnperf/react-native-performance-monitor"
12
+ s.platforms = { :ios => "13.0" }
13
+ s.source = { :path => "." }
14
+ s.source_files = "ios/**/*.{h,m}"
15
+ s.frameworks = "UIKit", "QuartzCore"
16
+
17
+ # React-Core brings in RCTBridgeModule. The module is a classic bridge module,
18
+ # which the new architecture still supports through its interop layer, so one
19
+ # implementation covers both the old and the bridgeless runtime.
20
+ s.dependency "React-Core"
21
+ end
@@ -0,0 +1,46 @@
1
+ apply plugin: 'com.android.library'
2
+
3
+ /**
4
+ * Read a property from the host app's rootProject.ext when it defines one, so
5
+ * this module compiles against the same SDK levels as the app including it,
6
+ * and still builds standalone when it does not.
7
+ */
8
+ def safeExtGet(String prop, fallback) {
9
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
10
+ }
11
+
12
+ android {
13
+ // `namespace` replaced the manifest's package attribute in AGP 7.3 and is
14
+ // required by AGP 8. Guarded so older toolchains do not fail on it.
15
+ if (project.android.hasProperty('namespace')) {
16
+ namespace 'com.rnperf.sdk'
17
+ }
18
+
19
+ compileSdk safeExtGet('compileSdkVersion', 34)
20
+
21
+ defaultConfig {
22
+ minSdk safeExtGet('minSdkVersion', 21)
23
+ targetSdk safeExtGet('targetSdkVersion', 34)
24
+ }
25
+
26
+ compileOptions {
27
+ sourceCompatibility JavaVersion.VERSION_1_8
28
+ targetCompatibility JavaVersion.VERSION_1_8
29
+ }
30
+
31
+ // A profiling helper must never be the reason an app build fails.
32
+ lint {
33
+ abortOnError false
34
+ }
35
+ }
36
+
37
+ repositories {
38
+ google()
39
+ mavenCentral()
40
+ }
41
+
42
+ dependencies {
43
+ // Version is supplied by the host app's React Native Gradle plugin.
44
+ //noinspection GradleDynamicVersion
45
+ implementation 'com.facebook.react:react-android'
46
+ }
@@ -0,0 +1,3 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <!-- The package namespace lives in build.gradle; AGP 8 forbids it here. -->
3
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,345 @@
1
+ package com.rnperf.sdk;
2
+
3
+ import android.app.Activity;
4
+ import android.content.Context;
5
+ import android.os.Build;
6
+ import android.os.Debug;
7
+ import android.view.Choreographer;
8
+ import android.view.Display;
9
+ import android.view.WindowManager;
10
+
11
+ import com.facebook.react.bridge.Arguments;
12
+ import com.facebook.react.bridge.LifecycleEventListener;
13
+ import com.facebook.react.bridge.Promise;
14
+ import com.facebook.react.bridge.ReactApplicationContext;
15
+ import com.facebook.react.bridge.ReactContextBaseJavaModule;
16
+ import com.facebook.react.bridge.ReactMethod;
17
+ import com.facebook.react.bridge.UiThreadUtil;
18
+ import com.facebook.react.bridge.WritableMap;
19
+ import com.facebook.react.module.annotations.ReactModule;
20
+
21
+ import java.util.Arrays;
22
+
23
+ /**
24
+ * Samples the Android UI thread's frame cadence with Choreographer.
25
+ *
26
+ * The daemon already reads richer per-frame data over adb when a cable is
27
+ * attached. This exists for the case adb cannot reach: a physical device on
28
+ * Wi-Fi, a tester's phone, or CI where only the app itself reports back. It is
29
+ * the same measurement the iOS module makes, so the two platforms produce
30
+ * directly comparable numbers.
31
+ *
32
+ * Reposting a frame callback each frame schedules the next vsync, so the loop
33
+ * runs at the display's cadence even when nothing on screen changes — the same
34
+ * approach React Native's own FPS monitor uses.
35
+ */
36
+ @ReactModule(name = RNPerfFrameMonitorModule.NAME)
37
+ public class RNPerfFrameMonitorModule extends ReactContextBaseJavaModule
38
+ implements LifecycleEventListener, Choreographer.FrameCallback {
39
+
40
+ public static final String NAME = "RNPerfFrameMonitor";
41
+
42
+ /**
43
+ * At 120Hz this is five seconds of frames. If JavaScript is blocked for
44
+ * longer it is not draining us either, and an unbounded buffer would grow
45
+ * while the app is already in trouble.
46
+ */
47
+ private static final int MAX_BUFFERED_FRAMES = 600;
48
+
49
+ /**
50
+ * An interval beyond this many refresh periods counts as a dropped frame.
51
+ * Inter-frame deltas straddle the budget at steady state, so an exact
52
+ * comparison would flag ordinary vsync jitter.
53
+ */
54
+ private static final double JANK_FACTOR = 1.5;
55
+
56
+ private static final double NANOS_PER_MS = 1_000_000.0;
57
+ private static final double BYTES_PER_MB = 1024.0 * 1024.0;
58
+
59
+ private final double[] intervalsMs = new double[MAX_BUFFERED_FRAMES];
60
+ private int intervalCount = 0;
61
+ private int overflowedFrames = 0;
62
+ private int droppedFrames = 0;
63
+
64
+ private long lastFrameTimeNanos = 0L;
65
+ private long windowStartNanos = 0L;
66
+ private double refreshHz = 60.0;
67
+
68
+ /** The app asked us to measure. Survives a pause, unlike {@link #running}. */
69
+ private boolean enabled = false;
70
+ /** A frame callback is currently scheduled. */
71
+ private boolean running = false;
72
+ private boolean listening = false;
73
+
74
+ public RNPerfFrameMonitorModule(ReactApplicationContext context) {
75
+ super(context);
76
+ // Deliberately no listener registration here: handing `this` to the context
77
+ // from a constructor publishes a reference to a half-built object. Nothing
78
+ // needs lifecycle events until measurement actually starts.
79
+ }
80
+
81
+ @Override
82
+ public String getName() {
83
+ return NAME;
84
+ }
85
+
86
+ /* ------------------------------------------------------------- exported */
87
+
88
+ @ReactMethod
89
+ public void start() {
90
+ UiThreadUtil.runOnUiThread(new Runnable() {
91
+ @Override
92
+ public void run() {
93
+ enabled = true;
94
+ if (!listening) {
95
+ getReactApplicationContext().addLifecycleEventListener(RNPerfFrameMonitorModule.this);
96
+ listening = true;
97
+ }
98
+ startLoop();
99
+ }
100
+ });
101
+ }
102
+
103
+ @ReactMethod
104
+ public void stop() {
105
+ UiThreadUtil.runOnUiThread(new Runnable() {
106
+ @Override
107
+ public void run() {
108
+ enabled = false;
109
+ stopLoop();
110
+ }
111
+ });
112
+ }
113
+
114
+ /**
115
+ * Returns the window accumulated since the previous call and starts a new
116
+ * one. Resolved from the UI thread so the frame buffers are only ever
117
+ * touched by one thread, with no locking on the hot path.
118
+ */
119
+ @ReactMethod
120
+ public void getMetrics(final Promise promise) {
121
+ UiThreadUtil.runOnUiThread(new Runnable() {
122
+ @Override
123
+ public void run() {
124
+ try {
125
+ promise.resolve(buildMetrics());
126
+ } catch (Exception error) {
127
+ promise.reject("E_RNPERF_METRICS", error);
128
+ }
129
+ }
130
+ });
131
+ }
132
+
133
+ @ReactMethod
134
+ public void isAvailable(Promise promise) {
135
+ promise.resolve(Boolean.TRUE);
136
+ }
137
+
138
+ /* ------------------------------------------------------------ collection */
139
+
140
+ private WritableMap buildMetrics() {
141
+ WritableMap result = Arguments.createMap();
142
+ result.putDouble("refreshHz", refreshHz);
143
+ putMemory(result);
144
+
145
+ if (!running || windowStartNanos == 0L) {
146
+ return result;
147
+ }
148
+
149
+ long now = System.nanoTime();
150
+ double elapsedMs = (now - windowStartNanos) / NANOS_PER_MS;
151
+ int frames = intervalCount + overflowedFrames;
152
+
153
+ // Too short a window makes frames-per-second meaningless.
154
+ if (elapsedMs < 100.0 || frames == 0) {
155
+ return result;
156
+ }
157
+
158
+ result.putInt("framesRendered", frames);
159
+ result.putDouble("uiFps", Math.min(refreshHz, frames / (elapsedMs / 1000.0)));
160
+
161
+ if (intervalCount > 0) {
162
+ double[] sorted = Arrays.copyOf(intervalsMs, intervalCount);
163
+ Arrays.sort(sorted);
164
+ result.putDouble("frameP50Ms", quantile(sorted, 0.50));
165
+ result.putDouble("frameP95Ms", quantile(sorted, 0.95));
166
+ result.putDouble("frameP99Ms", quantile(sorted, 0.99));
167
+ }
168
+
169
+ // Express jank as a share of the frames the display could have shown,
170
+ // rather than of the ones it managed to.
171
+ double expected = (elapsedMs / 1000.0) * refreshHz;
172
+ if (expected >= 1.0) {
173
+ double jank = (droppedFrames / expected) * 100.0;
174
+ result.putDouble("jankPercent", Math.max(0.0, Math.min(100.0, jank)));
175
+ }
176
+
177
+ resetWindow();
178
+ return result;
179
+ }
180
+
181
+ /**
182
+ * Java and native heap only. Proportional set size would be the better
183
+ * number, but {@code Debug.getMemoryInfo} takes well over a frame to return
184
+ * and would cause the jank this module exists to measure. The daemon reads
185
+ * PSS over adb instead, when a cable is attached.
186
+ */
187
+ private void putMemory(WritableMap result) {
188
+ try {
189
+ Runtime runtime = Runtime.getRuntime();
190
+ double javaHeapMB = (runtime.totalMemory() - runtime.freeMemory()) / BYTES_PER_MB;
191
+ result.putDouble("javaHeapMB", javaHeapMB);
192
+ result.putDouble("nativeHeapMB", Debug.getNativeHeapAllocatedSize() / BYTES_PER_MB);
193
+ } catch (Throwable ignored) {
194
+ // Memory is a bonus here; never fail a frame report over it.
195
+ }
196
+ }
197
+
198
+ /* --------------------------------------------------------- frame callback */
199
+
200
+ @Override
201
+ public void doFrame(long frameTimeNanos) {
202
+ if (!running) {
203
+ return;
204
+ }
205
+
206
+ if (lastFrameTimeNanos == 0L) {
207
+ // First callback after start or resume: there is no previous frame to
208
+ // measure against, and the gap would read as an enormous stall.
209
+ lastFrameTimeNanos = frameTimeNanos;
210
+ Choreographer.getInstance().postFrameCallback(this);
211
+ return;
212
+ }
213
+
214
+ double intervalMs = (frameTimeNanos - lastFrameTimeNanos) / NANOS_PER_MS;
215
+ lastFrameTimeNanos = frameTimeNanos;
216
+
217
+ if (intervalMs > 0.0) {
218
+ double budgetMs = 1000.0 / refreshHz;
219
+ if (intervalMs > budgetMs * JANK_FACTOR) {
220
+ // One long interval can swallow several refreshes; count each.
221
+ int missed = (int) Math.round(intervalMs / budgetMs) - 1;
222
+ droppedFrames += Math.max(1, missed);
223
+ }
224
+ if (intervalCount < MAX_BUFFERED_FRAMES) {
225
+ intervalsMs[intervalCount++] = intervalMs;
226
+ } else {
227
+ // Still count it towards FPS once the buffer is full, so a long JS
228
+ // stall does not make the app look idle.
229
+ overflowedFrames++;
230
+ }
231
+ }
232
+
233
+ Choreographer.getInstance().postFrameCallback(this);
234
+ }
235
+
236
+ /* -------------------------------------------------------------- lifecycle */
237
+
238
+ @Override
239
+ public void onHostResume() {
240
+ if (enabled) {
241
+ startLoop();
242
+ }
243
+ }
244
+
245
+ @Override
246
+ public void onHostPause() {
247
+ // A backgrounded app receives no frames. Left running, the next window
248
+ // would report zero FPS and a stall of however long it was away.
249
+ stopLoop();
250
+ }
251
+
252
+ @Override
253
+ public void onHostDestroy() {
254
+ enabled = false;
255
+ stopLoop();
256
+ if (listening) {
257
+ getReactApplicationContext().removeLifecycleEventListener(this);
258
+ listening = false;
259
+ }
260
+ }
261
+
262
+ /* ---------------------------------------------------------------- helpers */
263
+
264
+ private void startLoop() {
265
+ if (running) {
266
+ return;
267
+ }
268
+ refreshHz = readRefreshHz();
269
+ lastFrameTimeNanos = 0L;
270
+ resetWindow();
271
+ running = true;
272
+ Choreographer.getInstance().postFrameCallback(this);
273
+ }
274
+
275
+ private void stopLoop() {
276
+ if (!running) {
277
+ return;
278
+ }
279
+ running = false;
280
+ Choreographer.getInstance().removeFrameCallback(this);
281
+ lastFrameTimeNanos = 0L;
282
+ }
283
+
284
+ private void resetWindow() {
285
+ intervalCount = 0;
286
+ overflowedFrames = 0;
287
+ droppedFrames = 0;
288
+ windowStartNanos = System.nanoTime();
289
+ }
290
+
291
+ /**
292
+ * The display's current mode, not its maximum: a 120Hz panel running at 60Hz
293
+ * has a 16.7ms budget, and holding it to 8.3ms would invent jank.
294
+ */
295
+ @SuppressWarnings("deprecation")
296
+ private double readRefreshHz() {
297
+ try {
298
+ Display display = null;
299
+
300
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
301
+ Activity activity = getCurrentActivity();
302
+ if (activity != null) {
303
+ display = activity.getDisplay();
304
+ }
305
+ }
306
+
307
+ if (display == null) {
308
+ Context context = getReactApplicationContext();
309
+ WindowManager windowManager =
310
+ (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
311
+ if (windowManager != null) {
312
+ display = windowManager.getDefaultDisplay();
313
+ }
314
+ }
315
+
316
+ if (display != null) {
317
+ float hz = display.getRefreshRate();
318
+ if (hz > 20.0f) {
319
+ // The platform reports values like 60.000003814697266; two decimals
320
+ // is well beyond what any frame budget needs.
321
+ return Math.round(hz * 100.0) / 100.0;
322
+ }
323
+ }
324
+ } catch (Throwable ignored) {
325
+ // Fall through to the safe default below.
326
+ }
327
+ return 60.0;
328
+ }
329
+
330
+ private static double quantile(double[] sortedAscending, double q) {
331
+ int n = sortedAscending.length;
332
+ if (n == 0) {
333
+ return 0.0;
334
+ }
335
+ if (n == 1) {
336
+ return sortedAscending[0];
337
+ }
338
+ double position = (n - 1) * q;
339
+ int low = (int) Math.floor(position);
340
+ int high = (int) Math.ceil(position);
341
+ double a = sortedAscending[low];
342
+ double b = sortedAscending[high];
343
+ return low == high ? a : a + (b - a) * (position - low);
344
+ }
345
+ }
@@ -0,0 +1,36 @@
1
+ package com.rnperf.sdk;
2
+
3
+ import com.facebook.react.ReactPackage;
4
+ import com.facebook.react.bridge.NativeModule;
5
+ import com.facebook.react.bridge.ReactApplicationContext;
6
+ import com.facebook.react.uimanager.ViewManager;
7
+
8
+ import java.util.ArrayList;
9
+ import java.util.Collections;
10
+ import java.util.List;
11
+
12
+ /**
13
+ * Registers the frame monitor. Found automatically by React Native autolinking.
14
+ *
15
+ * Uses the eager {@code ReactPackage} API rather than {@code BaseReactPackage}:
16
+ * the latter only exists from React Native 0.74, and this package supports 0.70
17
+ * upwards. The eager form is deprecated but still honoured on every version,
18
+ * including the bridgeless runtime, and one module is not worth the lazy path.
19
+ */
20
+ // `rawtypes` is unavoidable: ReactPackage declares a raw List<ViewManager>, so
21
+ // a parameterised override would not match the interface.
22
+ @SuppressWarnings({"deprecation", "rawtypes"})
23
+ public class RNPerfFrameMonitorPackage implements ReactPackage {
24
+
25
+ @Override
26
+ public List<NativeModule> createNativeModules(ReactApplicationContext context) {
27
+ List<NativeModule> modules = new ArrayList<>();
28
+ modules.add(new RNPerfFrameMonitorModule(context));
29
+ return modules;
30
+ }
31
+
32
+ @Override
33
+ public List<ViewManager> createViewManagers(ReactApplicationContext context) {
34
+ return Collections.emptyList();
35
+ }
36
+ }
@@ -0,0 +1,38 @@
1
+ import type { PerfMonitorOptions } from './types.js';
2
+ export type { PerfMonitorOptions, Sample, PerfEvent, ComponentRenderStat } from './types.js';
3
+ /**
4
+ * Start streaming performance data to the rnperf daemon.
5
+ *
6
+ * Call it once, as early as possible but **after** React has loaded, so the
7
+ * render tracker can attach to React's commit hook:
8
+ *
9
+ * ```ts
10
+ * import { startPerfMonitor } from '@rnperf/sdk';
11
+ * import App from './App';
12
+ *
13
+ * startPerfMonitor(); // host is derived from the Metro URL
14
+ * ```
15
+ *
16
+ * In a release build it is a no-op unless `enableInRelease` is set.
17
+ */
18
+ export declare function startPerfMonitor(options?: PerfMonitorOptions): void;
19
+ export declare function stopPerfMonitor(): void;
20
+ /** Tell the monitor which screen is active, so findings can name it. */
21
+ export declare function setScreen(name: string): void;
22
+ export declare function mark(name: string, detail?: unknown): void;
23
+ /** Duration since `mark(startMark ?? name)`, also reported to the daemon. */
24
+ export declare function measure(name: string, startMark?: string, detail?: unknown): number | undefined;
25
+ export declare function reportTTI(screen?: string, durationMs?: number): void;
26
+ export declare function trackInteraction(name: string, durationMs: number): void;
27
+ export declare function perfLog(level: 'debug' | 'info' | 'warn' | 'error', message: string, tag?: string): void;
28
+ export declare function isPerfMonitorConnected(): boolean;
29
+ /**
30
+ * Drop-in for React Navigation: pass to `<NavigationContainer onStateChange>`
31
+ * (or call from your own router) to segment metrics by screen.
32
+ *
33
+ * ```tsx
34
+ * <NavigationContainer onStateChange={() => setScreen(navigationRef.getCurrentRoute()?.name ?? '')}>
35
+ * ```
36
+ */
37
+ export declare function createNavigationTracker(getCurrentRouteName: () => string | undefined): () => void;
38
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAa,kBAAkB,EAAU,MAAM,YAAY,CAAC;AAExE,YAAY,EAAE,kBAAkB,EAAE,MAAM,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AA+N7F;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,IAAI,CAEnE;AAED,wBAAgB,eAAe,IAAI,IAAI,CAEtC;AAED,wEAAwE;AACxE,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAE5C;AAED,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,CAEzD;AAED,6EAA6E;AAC7E,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAE9F;AAED,wBAAgB,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAEpE;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAEvE;AAED,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAEvG;AAED,wBAAgB,sBAAsB,IAAI,OAAO,CAEhD;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,mBAAmB,EAAE,MAAM,MAAM,GAAG,SAAS,cAWpF"}