diff --git a/packages/react-native/Libraries/Utilities/HMRClient.js b/packages/react-native/Libraries/Utilities/HMRClient.js index 2fb04e361ac7..7a8a92683f94 100644 --- a/packages/react-native/Libraries/Utilities/HMRClient.js +++ b/packages/react-native/Libraries/Utilities/HMRClient.js @@ -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; @@ -224,6 +232,7 @@ Error: ${e.message}`; }); let pendingUpdatesCount = 0; + let updatedRevisionIds: Array = []; let lastMarkerChangeId: string | null = null; client.on('update-start', ({isInitialUpdate}) => { pendingUpdatesCount++; @@ -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; @@ -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', { diff --git a/packages/react-native/Libraries/Utilities/__tests__/HMRClient-test.js b/packages/react-native/Libraries/Utilities/__tests__/HMRClient-test.js new file mode 100644 index 000000000000..d900c9bb0791 --- /dev/null +++ b/packages/react-native/Libraries/Utilities/__tests__/HMRClient-test.js @@ -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 = []; + +jest.mock('metro-runtime/src/modules/HMRClient', () => { + return class { + enabled: boolean = false; + handlers: Map = 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); + }); +}); diff --git a/packages/react-native/React/Base/RCTJavaScriptLoader.h b/packages/react-native/React/Base/RCTJavaScriptLoader.h index 370af209a8f7..b42e6cd986e6 100755 --- a/packages/react-native/React/Base/RCTJavaScriptLoader.h +++ b/packages/react-native/React/Base/RCTJavaScriptLoader.h @@ -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); diff --git a/packages/react-native/React/Base/RCTJavaScriptLoader.mm b/packages/react-native/React/Base/RCTJavaScriptLoader.mm index b8f353cd9cab..678dbfa9d10c 100755 --- a/packages/react-native/React/Base/RCTJavaScriptLoader.mm +++ b/packages/react-native/React/Base/RCTJavaScriptLoader.mm @@ -27,6 +27,7 @@ @interface RCTSource () { NSUInteger _length; NSInteger _filesChangedCount; NSURL *_downloadedBundleFileURL; + NSString *_revisionId; } @end @@ -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) diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index e5609d383c48..a855ac6426c2 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -1823,6 +1823,7 @@ public final class com/facebook/react/devsupport/BundleDownloader$BundleInfo { public fun ()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; } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt index 61f559a869c2..2bf5fd77c80a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt @@ -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) { @@ -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 @@ -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) { diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/BundleInfoTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/BundleInfoTest.kt new file mode 100644 index 000000000000..429037ed5a66 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/BundleInfoTest.kt @@ -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() + } +} diff --git a/packages/react-native/ReactCommon/react/runtime/iostests/RCTJavaScriptLoaderTests.mm b/packages/react-native/ReactCommon/react/runtime/iostests/RCTJavaScriptLoaderTests.mm new file mode 100644 index 000000000000..5feca3337e2a --- /dev/null +++ b/packages/react-native/ReactCommon/react/runtime/iostests/RCTJavaScriptLoaderTests.mm @@ -0,0 +1,171 @@ +/* + * 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. + */ + +#import +#import + +#import + +static NSString *const kStubHost = @"rct-javascript-loader-tests.invalid"; +static NSString *const kDeltaIdParameter = @"deltaId"; + +// Answers requests to kStubHost with a JavaScript body. The request's deltaId +// query parameter, when present, is sent back as the X-Metro-Delta-ID header. +@interface RCTJavaScriptLoaderTestsURLProtocol : NSURLProtocol +@end + +@implementation RCTJavaScriptLoaderTestsURLProtocol + ++ (BOOL)canInitWithRequest:(NSURLRequest *)request +{ + return [request.URL.host isEqualToString:kStubHost]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request +{ + return request; +} + +- (void)startLoading +{ + NSURL *url = self.request.URL; + if (url == nil) { + return; + } + NSMutableDictionary *headers = + [NSMutableDictionary dictionaryWithObject:@"application/javascript" forKey:@"Content-Type"]; + for (NSURLQueryItem *item in [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO].queryItems) { + if ([item.name isEqualToString:kDeltaIdParameter] && item.value != nil) { + headers[@"X-Metro-Delta-ID"] = item.value; + } + } + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url + statusCode:200 + HTTPVersion:@"HTTP/1.1" + headerFields:headers]; + if (response == nil) { + return; + } + [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [self.client URLProtocol:self didLoadData:[NSData dataWithBytes:"var loaded = true;" length:18]]; + [self.client URLProtocolDidFinishLoading:self]; +} + +- (void)stopLoading +{ +} + +@end + +@implementation NSURLSessionConfiguration (RCTJavaScriptLoaderTests) + +// Swapped with +defaultSessionConfiguration while a test runs, so this call reaches the original. ++ (NSURLSessionConfiguration *)rct_javaScriptLoaderTestsDefaultSessionConfiguration +{ + NSURLSessionConfiguration *configuration = [self rct_javaScriptLoaderTestsDefaultSessionConfiguration]; + configuration.protocolClasses = [@[ [RCTJavaScriptLoaderTestsURLProtocol class] ] + arrayByAddingObjectsFromArray:configuration.protocolClasses ?: @[]]; + return configuration; +} + +@end + +@interface RCTJavaScriptLoaderTests : XCTestCase +@end + +@implementation RCTJavaScriptLoaderTests + ++ (void)swapDefaultSessionConfiguration +{ + Class configurationClass = [NSURLSessionConfiguration class]; + Method original = class_getClassMethod(configurationClass, @selector(defaultSessionConfiguration)); + Method replacement = + class_getClassMethod(configurationClass, @selector(rct_javaScriptLoaderTestsDefaultSessionConfiguration)); + if (original != nullptr && replacement != nullptr) { + method_exchangeImplementations(original, replacement); + } +} + +- (void)setUp +{ + [super setUp]; + // The loader downloads with a session of its own, which only sees protocol + // classes listed in its configuration. + [RCTJavaScriptLoaderTests swapDefaultSessionConfiguration]; +} + +- (void)tearDown +{ + [RCTJavaScriptLoaderTests swapDefaultSessionConfiguration]; + [super tearDown]; +} + +// NOLINTBEGIN(cppcoreguidelines-pro-type-vararg, misc-throw-by-value-catch-by-reference) +- (RCTSource *)loadBundleAtURL:(NSURL *)url +{ + XCTestExpectation *loaded = [self expectationWithDescription:@"bundle loaded"]; + __block RCTSource *result; + [RCTJavaScriptLoader loadBundleAtURL:url + onProgress:^(RCTLoadingProgress *progressData) { + } + onComplete:^(NSError *error, RCTSource *source) { + XCTAssertNil(error); + result = source; + [loaded fulfill]; + }]; + [self waitForExpectations:@[ loaded ] timeout:10]; + return result; +} + +- (NSURL *)stubBundleURLWithDeltaId:(NSString *)deltaId +{ + NSURLComponents *components = [NSURLComponents new]; + components.scheme = @"http"; + components.host = kStubHost; + components.path = @"/index.bundle"; + NSMutableArray *query = + [NSMutableArray arrayWithObject:[NSURLQueryItem queryItemWithName:@"platform" value:@"ios"]]; + if (deltaId != nil) { + [query addObject:[NSURLQueryItem queryItemWithName:kDeltaIdParameter value:deltaId]]; + } + components.queryItems = query; + return components.URL; +} + +- (void)testTakesTheRevisionFromTheServersDeltaIdHeader +{ + RCTSource *source = [self loadBundleAtURL:[self stubBundleURLWithDeltaId:@"4f2c9a1b7e3d5608"]]; + + XCTAssertNotNil(source.downloadedBundleFileURL); + XCTAssertEqualObjects(source.revisionId, @"4f2c9a1b7e3d5608"); +} + +- (void)testHasNoRevisionWhenTheServerSendsNoDeltaId +{ + XCTAssertNil([self loadBundleAtURL:[self stubBundleURLWithDeltaId:nil]].revisionId); +} + +- (void)testHasNoRevisionForAnEmptyDeltaId +{ + XCTAssertNil([self loadBundleAtURL:[self stubBundleURLWithDeltaId:@""]].revisionId); +} + +- (void)testHasNoRevisionForABundleReadFromDisk +{ + NSURL *file = + [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSUUID UUID].UUIDString]]; + XCTAssertTrue([[@"var loaded = true;" dataUsingEncoding:NSUTF8StringEncoding] writeToURL:file atomically:YES]); + + RCTSource *source = [self loadBundleAtURL:file]; + + XCTAssertEqualObjects(source.url, file); + XCTAssertNil(source.revisionId); + [[NSFileManager defaultManager] removeItemAtURL:file error:nil]; +} +// NOLINTEND(cppcoreguidelines-pro-type-vararg, misc-throw-by-value-catch-by-reference) + +@end diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 5fb34f123790..a52ae294e523 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -1733,6 +1733,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index c191f3f7f57e..2481f3e9df93 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -1776,6 +1776,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index 9f2987431905..11ab116a7b38 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -1732,6 +1732,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 1bfb2638d899..3c9f668429d7 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -1733,6 +1733,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url;