Repository navigation
Expand file tree
/
Copy pathRCTInstance.mm
More file actions
628 lines (539 loc) · 23.2 KB
/
Copy pathRCTInstance.mm
File metadata and controls
628 lines (539 loc) · 23.2 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
* 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 "RCTInstance.h"
#import <memory>
#import <FBReactNativeSpec/FBReactNativeSpec.h>
#import <React/NSDataBigString.h>
#import <React/RCTAssert.h>
#import <React/RCTBridge+Inspector.h>
#import <React/RCTBridge+Private.h>
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTBridgeModuleDecorator.h>
#import <React/RCTBridgeProxy+Cxx.h>
#import <React/RCTBridgeProxy.h>
#import <React/RCTComponentViewFactory.h>
#import <React/RCTConstants.h>
#import <React/RCTCxxUtils.h>
#import <React/RCTDevSettings.h>
#import <React/RCTDisplayLink.h>
#import <React/RCTEventDispatcherProtocol.h>
#import <React/RCTFollyConvert.h>
#import <React/RCTLog.h>
#import <React/RCTLogBox.h>
#import <React/RCTModuleData.h>
#import <React/RCTPerformanceLogger.h>
#import <React/RCTRedBox.h>
#import <React/RCTSurfacePresenter.h>
#import <ReactCommon/RCTTurboModule.h>
#import <ReactCommon/RCTTurboModuleManager.h>
#import <ReactCommon/RuntimeExecutor.h>
#import <cxxreact/ReactMarker.h>
#import <jsinspector-modern/ReactCdp.h>
#import <jsireact/JSIExecutor.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
#import <react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h>
#import <react/utils/ContextContainer.h>
#import <react/utils/ManagedObjectWrapper.h>
#import "ObjCTimerRegistry.h"
#import "RCTJSThreadManager.h"
#import "RCTLegacyUIManagerConstantsProvider.h"
#import "RCTPerformanceLoggerUtils.h"
#if RCT_DEV_MENU && __has_include(<React/RCTDevLoadingViewProtocol.h>)
#import <React/RCTDevLoadingViewProtocol.h>
#endif
using namespace facebook;
using namespace facebook::react;
static NSString *sRuntimeDiagnosticFlags = nil;
NSString *RCTInstanceRuntimeDiagnosticFlags(void)
{
return sRuntimeDiagnosticFlags ? [sRuntimeDiagnosticFlags copy] : [NSString new];
}
void RCTInstanceSetRuntimeDiagnosticFlags(NSString *flags)
{
if (!flags) {
return;
}
sRuntimeDiagnosticFlags = [flags copy];
}
@interface RCTInstance () <RCTTurboModuleManagerDelegate>
@end
@implementation RCTInstance {
std::unique_ptr<ReactInstance> _reactInstance;
std::shared_ptr<JSRuntimeFactory> _jsRuntimeFactory;
__weak id<RCTTurboModuleManagerDelegate> _appTMMDelegate;
__weak id<RCTInstanceDelegate> _delegate;
RCTSurfacePresenter *_surfacePresenter;
RCTPerformanceLogger *_performanceLogger;
RCTDisplayLink *_displayLink;
RCTTurboModuleManager *_turboModuleManager;
std::mutex _invalidationMutex;
std::atomic<bool> _valid;
RCTJSThreadManager *_jsThreadManager;
NSDictionary *_launchOptions;
void (^_waitUntilModuleSetupComplete)();
// APIs supporting interop with native modules and view managers
RCTBridgeModuleDecorator *_bridgeModuleDecorator;
jsinspector_modern::HostTarget *_parentInspectorTarget;
}
#pragma mark - Public
- (instancetype)initWithDelegate:(id<RCTInstanceDelegate>)delegate
jsRuntimeFactory:(std::shared_ptr<facebook::react::JSRuntimeFactory>)jsRuntimeFactory
bundleManager:(RCTBundleManager *)bundleManager
turboModuleManagerDelegate:(id<RCTTurboModuleManagerDelegate>)tmmDelegate
moduleRegistry:(RCTModuleRegistry *)moduleRegistry
parentInspectorTarget:(jsinspector_modern::HostTarget *)parentInspectorTarget
launchOptions:(nullable NSDictionary *)launchOptions
{
if (self = [super init]) {
_performanceLogger = [RCTPerformanceLogger new];
registerPerformanceLoggerHooks(_performanceLogger);
[_performanceLogger markStartForTag:RCTPLReactInstanceInit];
_delegate = delegate;
_jsRuntimeFactory = jsRuntimeFactory;
_appTMMDelegate = tmmDelegate;
_jsThreadManager = [RCTJSThreadManager new];
_bridgeModuleDecorator = [[RCTBridgeModuleDecorator alloc] initWithViewRegistry:[RCTViewRegistry new]
moduleRegistry:moduleRegistry
bundleManager:bundleManager
callableJSModules:[RCTCallableJSModules new]];
_parentInspectorTarget = parentInspectorTarget;
{
__weak __typeof(self) weakSelf = self;
[_bridgeModuleDecorator.callableJSModules
setBridgelessJSModuleMethodInvoker:^(
NSString *moduleName, NSString *methodName, NSArray *args, dispatch_block_t onComplete) {
[weakSelf callFunctionOnJSModule:moduleName method:methodName args:args];
if (onComplete) {
[weakSelf
callFunctionOnBufferedRuntimeExecutor:[onComplete](facebook::jsi::Runtime &_) { onComplete(); }];
}
}];
}
_launchOptions = launchOptions;
if (ReactNativeFeatureFlags::enableJSRuntimeGCOnMemoryPressureOnIOS()) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_handleMemoryWarning)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
[self _start];
}
return self;
}
- (void)dealloc
{
if (ReactNativeFeatureFlags::enableJSRuntimeGCOnMemoryPressureOnIOS()) {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
}
- (void)callFunctionOnJSModule:(NSString *)moduleName method:(NSString *)method args:(NSArray *)args
{
if (_valid) {
_reactInstance->callFunctionOnModule(
[moduleName UTF8String], [method UTF8String], convertIdToFollyDynamic(args ? args : @[]));
}
}
- (void)invalidate
{
std::lock_guard<std::mutex> lock(_invalidationMutex);
_valid = false;
if (_reactInstance) {
_reactInstance->unregisterFromInspector();
}
[_surfacePresenter suspend];
[_jsThreadManager dispatchToJSThread:^{
/**
* Every TurboModule is invalidated on its own method queue.
* TurboModuleManager invalidate blocks the calling thread until all TurboModules are invalidated.
*/
[self->_turboModuleManager invalidate];
// Clean up all the Resources
self->_reactInstance = nullptr;
self->_jsRuntimeFactory = nullptr;
self->_appTMMDelegate = nil;
self->_delegate = nil;
[self->_displayLink invalidate];
self->_displayLink = nil;
self->_turboModuleManager = nil;
self->_performanceLogger = nil;
// Terminate the JavaScript thread, so that no other work executes after this block.
self->_jsThreadManager = nil;
}];
}
- (void)registerSegmentWithId:(NSNumber *)segmentId path:(NSString *)path
{
if (_valid) {
_reactInstance->registerSegment(static_cast<uint32_t>([segmentId unsignedIntValue]), path.UTF8String);
}
}
#pragma mark - RCTTurboModuleManagerDelegate
- (Class)getModuleClassFromName:(const char *)name
{
return [_appTMMDelegate getModuleClassFromName:name];
}
- (id<RCTTurboModule>)getModuleInstanceFromClass:(Class)moduleClass
{
id<RCTTurboModule> module = [_appTMMDelegate getModuleInstanceFromClass:moduleClass];
if (!module) {
module = [moduleClass new];
}
[self _attachBridgelessAPIsToModule:module];
return module;
}
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
jsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
if ([_appTMMDelegate respondsToSelector:@selector(getTurboModule:jsInvoker:)]) {
return [_appTMMDelegate getTurboModule:name jsInvoker:jsInvoker];
}
return nullptr;
}
- (NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(RCTBridge *)bridge
{
if ([_appTMMDelegate respondsToSelector:@selector(extraModulesForBridge:)]) {
return [_appTMMDelegate extraModulesForBridge:nil];
}
return @[];
}
- (nullable id<RCTModuleProvider>)getModuleProvider:(const char *)name
{
if ([_appTMMDelegate respondsToSelector:@selector(getModuleProvider:)]) {
return [_appTMMDelegate getModuleProvider:name];
}
return nil;
}
#pragma mark - Private
- (void)_start
{
// Set up timers
auto objCTimerRegistry = std::make_unique<ObjCTimerRegistry>();
auto timing = objCTimerRegistry->timing;
auto *objCTimerRegistryRawPtr = objCTimerRegistry.get();
auto timerManager = std::make_shared<TimerManager>(std::move(objCTimerRegistry));
objCTimerRegistryRawPtr->setTimerManager(timerManager);
__weak __typeof(self) weakSelf = self;
auto onJsError = [=](jsi::Runtime &runtime, const JsErrorHandler::ProcessedError &error) {
[weakSelf _handleJSError:error withRuntime:runtime];
};
// Create the React Instance
_reactInstance = std::make_unique<ReactInstance>(
_jsRuntimeFactory->createJSRuntime(_jsThreadManager.jsMessageThread),
_jsThreadManager.jsMessageThread,
timerManager,
onJsError,
_parentInspectorTarget);
_valid = true;
RuntimeExecutor bufferedRuntimeExecutor = _reactInstance->getBufferedRuntimeExecutor();
timerManager->setRuntimeExecutor(bufferedRuntimeExecutor);
auto jsCallInvoker = make_shared<RuntimeSchedulerCallInvoker>(_reactInstance->getRuntimeScheduler());
RCTBridgeProxy *bridgeProxy =
[[RCTBridgeProxy alloc] initWithViewRegistry:_bridgeModuleDecorator.viewRegistry_DEPRECATED
moduleRegistry:_bridgeModuleDecorator.moduleRegistry
bundleManager:_bridgeModuleDecorator.bundleManager
callableJSModules:_bridgeModuleDecorator.callableJSModules
dispatchToJSThread:^(dispatch_block_t block) {
__strong __typeof(self) strongSelf = weakSelf;
if (strongSelf && strongSelf->_valid) {
strongSelf->_reactInstance->getBufferedRuntimeExecutor()([=](jsi::Runtime &runtime) { block(); });
}
}
registerSegmentWithId:^(NSNumber *segmentId, NSString *path) {
__strong __typeof(self) strongSelf = weakSelf;
if (strongSelf && strongSelf->_valid) {
[strongSelf registerSegmentWithId:segmentId path:path];
}
}
runtime:_reactInstance->getJavaScriptContext()
launchOptions:_launchOptions];
bridgeProxy.jsCallInvoker = jsCallInvoker;
[RCTBridge setCurrentBridge:(RCTBridge *)bridgeProxy];
// Set up TurboModules
_turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridgeProxy:bridgeProxy
bridgeModuleDecorator:_bridgeModuleDecorator
delegate:self
jsInvoker:jsCallInvoker];
#if RCT_DEV
/**
* Instantiating DevMenu has the side-effect of registering
* shortcuts for CMD + d, CMD + i, and CMD + n via RCTDevMenu.
* Therefore, when TurboModules are enabled, we must manually create this
* NativeModule.
*/
[_turboModuleManager moduleForName:"RCTDevMenu"];
#endif // end RCT_DEV
// Initialize RCTModuleRegistry so that TurboModules can require other TurboModules.
[_bridgeModuleDecorator.moduleRegistry setTurboModuleRegistry:_turboModuleManager];
if (ReactNativeFeatureFlags::enableMainQueueModulesOnIOS()) {
/**
* Some native modules need to capture uikit objects on the main thread.
* Start initializing those modules on the main queue here. The JavaScript thread
* will wait until this module init finishes, before executing the js bundle.
*/
NSArray<NSString *> *modulesRequiringMainQueueSetup = [_delegate unstableModulesRequiringMainQueueSetup];
std::shared_ptr<std::mutex> mutex = std::make_shared<std::mutex>();
std::shared_ptr<std::condition_variable> cv = std::make_shared<std::condition_variable>();
std::shared_ptr<bool> isReady = std::make_shared<bool>(false);
_waitUntilModuleSetupComplete = ^{
std::unique_lock<std::mutex> lock(*mutex);
cv->wait(lock, [isReady] { return *isReady; });
};
// TODO(T218039767): Integrate perf logging into main queue module init
RCTExecuteOnMainQueue(^{
for (NSString *moduleName in modulesRequiringMainQueueSetup) {
[self->_bridgeModuleDecorator.moduleRegistry moduleForName:[moduleName UTF8String]];
}
RCTScreenSize();
RCTScreenScale();
std::lock_guard<std::mutex> lock(*mutex);
*isReady = true;
cv->notify_all();
});
}
RCTLogSetBridgelessModuleRegistry(_bridgeModuleDecorator.moduleRegistry);
RCTLogSetBridgelessCallableJSModules(_bridgeModuleDecorator.callableJSModules);
auto contextContainer = std::make_shared<ContextContainer>();
[_delegate didCreateContextContainer:contextContainer];
contextContainer->insert(
"RCTImageLoader", facebook::react::wrapManagedObject([_turboModuleManager moduleForName:"RCTImageLoader"]));
contextContainer->insert(
"RCTEventDispatcher",
facebook::react::wrapManagedObject([_turboModuleManager moduleForName:"RCTEventDispatcher"]));
contextContainer->insert("RCTBridgeModuleDecorator", facebook::react::wrapManagedObject(_bridgeModuleDecorator));
contextContainer->insert(RuntimeSchedulerKey, std::weak_ptr<RuntimeScheduler>(_reactInstance->getRuntimeScheduler()));
contextContainer->insert("RCTBridgeProxy", facebook::react::wrapManagedObject(bridgeProxy));
_surfacePresenter = [[RCTSurfacePresenter alloc]
initWithContextContainer:contextContainer
runtimeExecutor:bufferedRuntimeExecutor
bridgelessBindingsExecutor:std::optional(_reactInstance->getUnbufferedRuntimeExecutor())];
// This enables RCTViewRegistry in modules to return UIViews from its viewForReactTag method
__weak RCTSurfacePresenter *weakSurfacePresenter = _surfacePresenter;
[_bridgeModuleDecorator.viewRegistry_DEPRECATED setBridgelessComponentViewProvider:^UIView *(NSNumber *reactTag) {
RCTSurfacePresenter *strongSurfacePresenter = weakSurfacePresenter;
if (strongSurfacePresenter == nil) {
return nil;
}
return [strongSurfacePresenter findComponentViewWithTag_DO_NOT_USE_DEPRECATED:reactTag.integerValue];
}];
// DisplayLink is used to call timer callbacks.
_displayLink = [RCTDisplayLink new];
ReactInstance::JSRuntimeFlags options = {
.isProfiling = false, .runtimeDiagnosticFlags = [RCTInstanceRuntimeDiagnosticFlags() UTF8String]};
_reactInstance->initializeRuntime(options, [=](jsi::Runtime &runtime) {
__strong __typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
[strongSelf->_turboModuleManager installJSBindings:runtime];
facebook::react::bindNativeLogger(runtime, [](const std::string &message, unsigned int logLevel) {
_RCTLogJavaScriptInternal(static_cast<RCTLogLevel>(logLevel), [NSString stringWithUTF8String:message.c_str()]);
});
RCTInstallNativeComponentRegistryBinding(runtime);
if (ReactNativeFeatureFlags::useNativeViewConfigsInBridgelessMode()) {
installLegacyUIManagerConstantsProviderBinding(runtime);
}
[strongSelf->_delegate instance:strongSelf didInitializeRuntime:runtime];
// Set up Display Link
RCTModuleData *timingModuleData = [[RCTModuleData alloc] initWithModuleInstance:timing
bridge:nil
moduleRegistry:nil
viewRegistry_DEPRECATED:nil
bundleManager:nil
callableJSModules:nil];
[strongSelf->_displayLink registerModuleForFrameUpdates:timing withModuleData:timingModuleData];
[strongSelf->_displayLink addToRunLoop:[NSRunLoop currentRunLoop]];
// Attempt to load bundle synchronously, fallback to asynchronously.
[strongSelf->_performanceLogger markStartForTag:RCTPLScriptDownload];
[strongSelf _loadJSBundle:[strongSelf->_bridgeModuleDecorator.bundleManager bundleURL]];
});
[_performanceLogger markStopForTag:RCTPLReactInstanceInit];
}
- (void)_attachBridgelessAPIsToModule:(id<RCTTurboModule>)module
{
__weak RCTInstance *weakSelf = self;
if ([module respondsToSelector:@selector(setDispatchToJSThread:)]) {
((id<RCTJSDispatcherModule>)module).dispatchToJSThread = ^(dispatch_block_t block) {
__strong __typeof(self) strongSelf = weakSelf;
if (strongSelf && strongSelf->_valid) {
strongSelf->_reactInstance->getBufferedRuntimeExecutor()([=](jsi::Runtime &runtime) { block(); });
}
};
}
if ([module respondsToSelector:@selector(setSurfacePresenter:)]) {
[module performSelector:@selector(setSurfacePresenter:) withObject:_surfacePresenter];
}
// Replaces bridge.isInspectable
if ([module respondsToSelector:@selector(setIsInspectable:)]) {
#if RCT_DEV_MENU
if (_valid) {
_reactInstance->getBufferedRuntimeExecutor()([module](jsi::Runtime &runtime) {
((id<RCTDevSettingsInspectable>)module).isInspectable = runtime.isInspectable();
});
}
#endif
}
}
- (void)callFunctionOnBufferedRuntimeExecutor:(std::function<void(facebook::jsi::Runtime &)> &&)executor
{
_reactInstance->getBufferedRuntimeExecutor()([=](jsi::Runtime &runtime) {
if (executor) {
executor(runtime);
}
});
}
- (void)handleBundleLoadingError:(NSError *)error
{
if (!_valid) {
return;
}
RCTRedBox *redBox = [_turboModuleManager moduleForName:"RedBox"];
RCTExecuteOnMainQueue(^{
[[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidFailToLoadNotification
object:self
userInfo:@{@"error" : error}];
[redBox showErrorMessage:[error localizedDescription]];
RCTFatal(error);
});
}
- (void)_loadJSBundle:(NSURL *)sourceURL
{
#if RCT_DEV_MENU && __has_include(<React/RCTDevLoadingViewProtocol.h>)
{
id<RCTDevLoadingViewProtocol> loadingView =
(id<RCTDevLoadingViewProtocol>)[_turboModuleManager moduleForName:"DevLoadingView"];
[loadingView showWithURL:sourceURL];
}
#endif
__weak __typeof(self) weakSelf = self;
[_delegate loadBundleAtURL:sourceURL
onProgress:^(RCTLoadingProgress *progressData) {
__typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
#if RCT_DEV_MENU && __has_include(<React/RCTDevLoadingViewProtocol.h>)
id<RCTDevLoadingViewProtocol> loadingView =
(id<RCTDevLoadingViewProtocol>)[strongSelf->_turboModuleManager moduleForName:"DevLoadingView"];
[loadingView updateProgress:progressData];
#endif
}
onComplete:^(NSError *error, RCTSource *source) {
__typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
if (error) {
[strongSelf handleBundleLoadingError:error];
return;
}
// DevSettings module is needed by _loadScriptFromSource's callback so prior initialization is required
RCTDevSettings *const devSettings =
(RCTDevSettings *)[strongSelf->_turboModuleManager moduleForName:"DevSettings"];
[strongSelf _loadScriptFromSource:source];
// Set up hot module reloading in Dev only.
[strongSelf->_performanceLogger markStopForTag:RCTPLScriptDownload];
[devSettings setupHMRClientWithBundleURL:sourceURL];
#if RCT_DEV
[strongSelf _logOldArchitectureWarnings];
#endif
}];
}
- (void)_logOldArchitectureWarnings
{
if (!RCTAreLegacyLogsEnabled()) {
return;
}
NSArray<NSString *> *modulesInOldArchMode = [getModulesLoadedWithOldArch() copy];
if (modulesInOldArchMode.count > 0) {
NSMutableString *moduleList = [NSMutableString new];
for (NSString *moduleName in modulesInOldArchMode) {
[moduleList appendFormat:@"- %@\n", moduleName];
}
RCTLogWarn(
@"The following modules have been registered using a RCT_EXPORT_MODULE. That's a Legacy Architecture API. Please migrate to the new approach as described in the https://reactnative.dev/docs/next/turbo-native-modules-introduction#register-the-native-module-in-your-app website or open a PR in the library repository:\n%@",
moduleList);
}
}
- (void)_loadScriptFromSource:(RCTSource *)source
{
std::lock_guard<std::mutex> lock(_invalidationMutex);
if (!_valid) {
return;
}
auto script = std::make_unique<NSDataBigString>(source.data);
const auto *url = deriveSourceURL(source.url).UTF8String;
auto beforeLoad = [waitUntilModuleSetupComplete = self->_waitUntilModuleSetupComplete](jsi::Runtime &_) {
if (waitUntilModuleSetupComplete) {
waitUntilModuleSetupComplete();
}
};
auto afterLoad = [](jsi::Runtime &_) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"RCTInstanceDidLoadBundle" object:nil];
};
_reactInstance->loadScript(std::move(script), url, beforeLoad, afterLoad);
}
- (void)_handleJSError:(const JsErrorHandler::ProcessedError &)error withRuntime:(jsi::Runtime &)runtime
{
NSMutableDictionary<NSString *, id> *errorData = [NSMutableDictionary new];
errorData[@"message"] = @(error.message.c_str());
if (error.originalMessage) {
errorData[@"originalMessage"] = @(error.originalMessage->c_str());
}
if (error.name) {
errorData[@"name"] = @(error.name->c_str());
}
if (error.componentStack) {
errorData[@"componentStack"] = @(error.componentStack->c_str());
}
NSMutableArray<NSDictionary<NSString *, id> *> *stack = [NSMutableArray new];
for (const JsErrorHandler::ProcessedError::StackFrame &frame : error.stack) {
NSMutableDictionary<NSString *, id> *stackFrame = [NSMutableDictionary new];
if (frame.file) {
stackFrame[@"file"] = @(frame.file->c_str());
}
stackFrame[@"methodName"] = @(frame.methodName.c_str());
if (frame.lineNumber) {
stackFrame[@"lineNumber"] = @(*frame.lineNumber);
}
if (frame.column) {
stackFrame[@"column"] = @(*frame.column);
}
[stack addObject:stackFrame];
}
errorData[@"stack"] = stack;
errorData[@"id"] = @(error.id);
errorData[@"isFatal"] = @(error.isFatal);
id extraData =
TurboModuleConvertUtils::convertJSIValueToObjCObject(runtime, jsi::Value(runtime, error.extraData), nullptr);
if (extraData) {
errorData[@"extraData"] = extraData;
}
if (![_delegate instance:self
didReceiveJSErrorStack:errorData[@"stack"]
message:errorData[@"message"]
originalMessage:errorData[@"originalMessage"]
name:errorData[@"name"]
componentStack:errorData[@"componentStack"]
exceptionId:error.id
isFatal:[errorData[@"isFatal"] boolValue]
extraData:errorData[@"extraData"]]) {
JS::NativeExceptionsManager::ExceptionData jsErrorData{errorData};
id<NativeExceptionsManagerSpec> exceptionsManager = [_turboModuleManager moduleForName:"ExceptionsManager"];
[exceptionsManager reportException:jsErrorData];
}
}
- (void)_handleMemoryWarning
{
if (_valid) {
// Memory Pressure Unloading Level 15 represents TRIM_MEMORY_RUNNING_CRITICAL.
static constexpr int unloadLevel = 15;
_reactInstance->handleMemoryPressureJs(unloadLevel);
}
}
@end