Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion packages/react-native/Libraries/Utilities/HMRClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ const invariant = require('invariant');
const MetroHMRClient = require('metro-runtime/src/modules/HMRClient');
const prettyFormat = require('pretty-format');

// Internal to React Native's development tooling; it can change without notice.
declare var global: {
__HMR_UPDATE_REPORTER__?: {
onUpdate: (update: Readonly<{revisionId: ?string, ...}>) => void,
},
...
};

const pendingEntryPoints = [];
let hmrClient = null;
let hmrUnavailableReason: string | null = null;
Expand Down Expand Up @@ -224,6 +232,7 @@ Error: ${e.message}`;
});

let pendingUpdatesCount = 0;
let updatedRevisionIds: Array<?string> = [];
let lastMarkerChangeId: string | null = null;
client.on('update-start', ({isInitialUpdate}) => {
pendingUpdatesCount++;
Expand All @@ -235,15 +244,21 @@ Error: ${e.message}`;
}
});

client.on('update', ({isInitialUpdate}) => {
client.on('update', ({isInitialUpdate, revisionId}) => {
if (client.isEnabled() && !isInitialUpdate) {
dismissRedbox();
LogBox.clearAllLogs();
}
// The client applied the update before this listener runs, or stashed it
// until Fast Refresh is enabled. An update that throws is not recorded.
updatedRevisionIds.push(revisionId);
});

client.on('update-done', body => {
pendingUpdatesCount--;
const revisionIds = updatedRevisionIds;
updatedRevisionIds = [];
revisionIds.forEach(reportUpdate);
if (pendingUpdatesCount === 0) {
DevLoadingView.hide();
const changeId = body?.changeId;
Expand Down Expand Up @@ -396,6 +411,14 @@ function showCompileError() {
throw error;
}

function reportUpdate(revisionId: ?string) {
try {
global.__HMR_UPDATE_REPORTER__?.onUpdate({revisionId});
} catch (error: unknown) {
console.warn('HMR update reporter failed:', error);
}
}

function emitFastRefreshCompleteEvents() {
// Add marker entry in performance timeline
performance.mark('Fast Refresh - Update done', {
Expand Down
160 changes: 160 additions & 0 deletions packages/react-native/Libraries/Utilities/__tests__/HMRClient-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/

'use strict';

type Handler = (payload: unknown) => void;

interface MockClient {
emit(event: string, payload: unknown): void;
}

const mockClients: Array<MockClient> = [];

jest.mock('metro-runtime/src/modules/HMRClient', () => {
return class {
enabled: boolean = false;
handlers: Map<string, Handler> = new Map();
constructor() {
mockClients.push(this);
}
on(event: string, handler: Handler) {
this.handlers.set(event, handler);
}
emit(event: string, payload: unknown) {
this.handlers.get(event)?.(payload);
}
isEnabled(): boolean {
return this.enabled;
}
enable() {
this.enabled = true;
}
disable() {
this.enabled = false;
}
hasPendingUpdates(): boolean {
return false;
}
send() {}
close() {}
};
});
jest.mock('../../Core/Devtools/getDevServer', () => ({
__esModule: true,
default: () => ({
bundleLoadedFromServer: true,
fullBundleUrl: 'http://localhost:8081/index.bundle?platform=ios',
url: 'http://localhost:8081/',
}),
}));
jest.mock('../DevLoadingView', () => ({
__esModule: true,
default: {showMessage: jest.fn(), hide: jest.fn()},
}));
jest.mock('../../LogBox/LogBox', () => ({
__esModule: true,
default: {clearAllLogs: jest.fn()},
}));
jest.mock('../../NativeModules/specs/NativeRedBox', () => ({
__esModule: true,
default: null,
}));
jest.mock('../../Core/NativeExceptionsManager', () => ({
__esModule: true,
default: {dismissRedbox: jest.fn()},
}));

describe('HMRClient', () => {
let onUpdate;

beforeEach(() => {
jest.resetModules();
mockClients.length = 0;
onUpdate = jest.fn();
global.__HMR_UPDATE_REPORTER__ = {onUpdate};
});

afterEach(() => {
delete global.__HMR_UPDATE_REPORTER__;
});

function setUp(isEnabled: boolean) {
const HMRClient = require('../HMRClient').default;
HMRClient.setup('ios', 'index.bundle', 'localhost', 8081, isEnabled);
return mockClients[0];
}

function applyUpdate(client: MockClient, update: unknown) {
client.emit('update-start', {isInitialUpdate: false});
client.emit('update', update);
client.emit('update-done', {changeId: 'change'});
}

it('reports the revision of an applied update once it is done', () => {
const client = setUp(true);

client.emit('update-start', {isInitialUpdate: false});
client.emit('update', {isInitialUpdate: false, revisionId: 'rev-2'});
expect(onUpdate).not.toHaveBeenCalled();
client.emit('update-done', {changeId: 'change'});

expect(onUpdate.mock.calls).toEqual([[{revisionId: 'rev-2'}]]);
});

it('reports an update that Fast Refresh stashed', () => {
const client = setUp(false);

applyUpdate(client, {isInitialUpdate: false, revisionId: 'rev-3'});

expect(onUpdate.mock.calls).toEqual([[{revisionId: 'rev-3'}]]);
});

it('reports the initial update and one without a revision', () => {
const client = setUp(true);

applyUpdate(client, {isInitialUpdate: true, revisionId: 'rev-1'});
applyUpdate(client, {isInitialUpdate: false});

expect(onUpdate.mock.calls).toEqual([
[{revisionId: 'rev-1'}],
[{revisionId: undefined}],
]);
});

it('keeps handling updates when the reporter throws', () => {
onUpdate.mockImplementation(() => {
throw new Error('reporter failed');
});
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
const DevLoadingView = require('../DevLoadingView').default;
const client = setUp(true);

expect(() =>
applyUpdate(client, {isInitialUpdate: false, revisionId: 'rev-2'}),
).not.toThrow();
expect(warn).toHaveBeenCalledTimes(1);
expect(DevLoadingView.hide).toHaveBeenCalled();
warn.mockRestore();
});

it('handles an update as before when no reporter is installed', () => {
delete global.__HMR_UPDATE_REPORTER__;
const client = setUp(true);
const LogBox = require('../../LogBox/LogBox').default;
const NativeExceptionsManager =
require('../../Core/NativeExceptionsManager').default;

applyUpdate(client, {isInitialUpdate: false, revisionId: 'rev-2'});

expect(NativeExceptionsManager.dismissRedbox).toHaveBeenCalledTimes(1);
expect(LogBox.clearAllLogs).toHaveBeenCalledTimes(1);
});
});
7 changes: 7 additions & 0 deletions packages/react-native/React/Base/RCTJavaScriptLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ NS_ENUM(NSInteger){
*/
@property (strong, nonatomic, readonly) NSURL *downloadedBundleFileURL;

/**
* The bundler's identifier for the revision of the module graph this bundle was
* built from, taken from the `X-Metro-Delta-ID` response header. nil when the
* bundle was not served by a bundler that sends one (e.g. read from disk).
*/
@property (copy, nonatomic, readonly) NSString *revisionId;

@end

typedef void (^RCTSourceLoadProgressBlock)(RCTLoadingProgress *progressData);
Expand Down
5 changes: 5 additions & 0 deletions packages/react-native/React/Base/RCTJavaScriptLoader.mm
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ @interface RCTSource () {
NSUInteger _length;
NSInteger _filesChangedCount;
NSURL *_downloadedBundleFileURL;
NSString *_revisionId;
}

@end
Expand Down Expand Up @@ -223,6 +224,10 @@ + (NSData *)attemptSynchronousLoadOfBundleAtURL:(NSURL *)scriptURL
static void parseHeaders(NSDictionary *headers, RCTSource *source)
{
source->_filesChangedCount = [headers[@"X-Metro-Files-Changed-Count"] integerValue];
id revisionId = headers[@"X-Metro-Delta-ID"];
if ([revisionId isKindOfClass:[NSString class]] && [revisionId length] > 0) {
source->_revisionId = revisionId;
}
}

static NSURL *persistDownloadedBundle(NSData *data, NSError **error)
Expand Down
1 change: 1 addition & 0 deletions packages/react-native/ReactAndroid/api/ReactAndroid.api
Original file line number Diff line number Diff line change
Expand Up @@ -1823,6 +1823,7 @@ public final class com/facebook/react/devsupport/BundleDownloader$BundleInfo {
public fun <init> ()V
public static final fun fromJSONString (Ljava/lang/String;)Lcom/facebook/react/devsupport/BundleDownloader$BundleInfo;
public final fun getFilesChangedCount ()I
public final fun getRevisionId ()Ljava/lang/String;
public final fun getUrl ()Ljava/lang/String;
public final fun toJSONString ()Ljava/lang/String;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,17 @@ public class BundleDownloader public constructor(private val client: OkHttpClien
public var filesChangedCount: Int = 0
internal set

/** The dev server's label for the revision it built the bundle from (`X-Metro-Delta-ID`). */
public var revisionId: String? = null
internal set

public fun toJSONString(): String? =
try {
JSONObject()
.apply {
put("url", _url)
put("filesChangedCount", filesChangedCount)
put("revisionId", revisionId)
}
.toString()
} catch (e: JSONException) {
Expand All @@ -63,10 +68,11 @@ public class BundleDownloader public constructor(private val client: OkHttpClien
}
return try {
val obj = JSONObject(jsonStr)
BundleInfo().apply {
_url = obj.getString("url")
filesChangedCount = obj.getInt("filesChangedCount")
}
val info = BundleInfo()
info._url = obj.getString("url")
info.filesChangedCount = obj.getInt("filesChangedCount")
info.revisionId = obj.optString("revisionId").ifEmpty { null }
info
} catch (e: JSONException) {
FLog.e(TAG, "Invalid bundle info: ", e)
null
Expand Down Expand Up @@ -335,6 +341,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien

private fun populateBundleInfo(url: String, headers: Headers, bundleInfo: BundleInfo) {
bundleInfo._url = url
bundleInfo.revisionId = headers["X-Metro-Delta-ID"]?.ifEmpty { null }

val filesChangedCountStr = headers["X-Metro-Files-Changed-Count"]
if (filesChangedCountStr != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

package com.facebook.react.devsupport

import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner

@RunWith(RobolectricTestRunner::class)
class BundleInfoTest {

@Test
fun keepsTheDevServerRevisionAcrossJson() {
val info = BundleDownloader.BundleInfo()
info._url = "http://localhost:8081/index.bundle"
info.revisionId = "rev-1"

val parsed = BundleDownloader.BundleInfo.fromJSONString(info.toJSONString())

assertThat(parsed?.revisionId).isEqualTo("rev-1")
}

@Test
fun readsAMissingRevisionAsNull() {
val parsed = BundleDownloader.BundleInfo.fromJSONString("""{"url":"u","filesChangedCount":0}""")

assertThat(parsed?.revisionId).isNull()
}
}
Loading
Loading