@onekeyfe/react-native-background-thread 1.1.7

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.
@@ -0,0 +1,20 @@
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 = "BackgroundThread"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported }
14
+ s.source = { :git => "https://github.com/OneKeyHQ/app-modules/react-native-background-thread.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = "ios/**/*.{h,m,mm,swift,cpp}"
17
+ s.public_header_files = "ios/**/*.h"
18
+
19
+ install_modules_dependencies(s)
20
+ end
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 @onekeyhq
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # react-native-background-thread
2
+
3
+ react-native-background-thread
4
+
5
+ ## Installation
6
+
7
+
8
+ ```sh
9
+ npm install react-native-background-thread
10
+ ```
11
+
12
+
13
+ ## Usage
14
+
15
+
16
+ ```js
17
+ import { multiply } from 'react-native-background-thread';
18
+
19
+ // ...
20
+
21
+ const result = multiply(3, 7);
22
+ ```
23
+
24
+
25
+ ## Contributing
26
+
27
+ - [Development workflow](CONTRIBUTING.md#development-workflow)
28
+ - [Sending a pull request](CONTRIBUTING.md#sending-a-pull-request)
29
+ - [Code of conduct](CODE_OF_CONDUCT.md)
30
+
31
+ ## License
32
+
33
+ MIT
34
+
35
+ ---
36
+
37
+ Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
@@ -0,0 +1,77 @@
1
+ buildscript {
2
+ ext.getExtOrDefault = {name ->
3
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['BackgroundThread_' + name]
4
+ }
5
+
6
+ repositories {
7
+ google()
8
+ mavenCentral()
9
+ }
10
+
11
+ dependencies {
12
+ classpath "com.android.tools.build:gradle:8.7.2"
13
+ // noinspection DifferentKotlinGradleVersion
14
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
15
+ }
16
+ }
17
+
18
+
19
+ apply plugin: "com.android.library"
20
+ apply plugin: "kotlin-android"
21
+
22
+ apply plugin: "com.facebook.react"
23
+
24
+ def getExtOrIntegerDefault(name) {
25
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["BackgroundThread_" + name]).toInteger()
26
+ }
27
+
28
+ android {
29
+ namespace "com.backgroundthread"
30
+
31
+ compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
32
+
33
+ defaultConfig {
34
+ minSdkVersion getExtOrIntegerDefault("minSdkVersion")
35
+ targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
36
+ }
37
+
38
+ buildFeatures {
39
+ buildConfig true
40
+ }
41
+
42
+ buildTypes {
43
+ release {
44
+ minifyEnabled false
45
+ }
46
+ }
47
+
48
+ lintOptions {
49
+ disable "GradleCompatible"
50
+ }
51
+
52
+ compileOptions {
53
+ sourceCompatibility JavaVersion.VERSION_1_8
54
+ targetCompatibility JavaVersion.VERSION_1_8
55
+ }
56
+
57
+ sourceSets {
58
+ main {
59
+ java.srcDirs += [
60
+ "generated/java",
61
+ "generated/jni"
62
+ ]
63
+ }
64
+ }
65
+ }
66
+
67
+ repositories {
68
+ mavenCentral()
69
+ google()
70
+ }
71
+
72
+ def kotlin_version = getExtOrDefault("kotlinVersion")
73
+
74
+ dependencies {
75
+ implementation "com.facebook.react:react-android"
76
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
77
+ }
@@ -0,0 +1,5 @@
1
+ BackgroundThread_kotlinVersion=2.0.21
2
+ BackgroundThread_minSdkVersion=24
3
+ BackgroundThread_targetSdkVersion=34
4
+ BackgroundThread_compileSdkVersion=35
5
+ BackgroundThread_ndkVersion=27.1.12297006
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,23 @@
1
+ package com.backgroundthread
2
+
3
+ import com.facebook.react.bridge.ReactApplicationContext
4
+ import com.facebook.react.module.annotations.ReactModule
5
+
6
+ @ReactModule(name = BackgroundThreadModule.NAME)
7
+ class BackgroundThreadModule(reactContext: ReactApplicationContext) :
8
+ NativeBackgroundThreadSpec(reactContext) {
9
+
10
+ override fun getName(): String {
11
+ return NAME
12
+ }
13
+
14
+ // Example method
15
+ // See https://reactnative.dev/docs/native-modules-android
16
+ override fun multiply(a: Double, b: Double): Double {
17
+ return a * b
18
+ }
19
+
20
+ companion object {
21
+ const val NAME = "BackgroundThread"
22
+ }
23
+ }
@@ -0,0 +1,33 @@
1
+ package com.backgroundthread
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+ import java.util.HashMap
9
+
10
+ class BackgroundThreadPackage : BaseReactPackage() {
11
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
12
+ return if (name == BackgroundThreadModule.NAME) {
13
+ BackgroundThreadModule(reactContext)
14
+ } else {
15
+ null
16
+ }
17
+ }
18
+
19
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {
20
+ return ReactModuleInfoProvider {
21
+ val moduleInfos: MutableMap<String, ReactModuleInfo> = HashMap()
22
+ moduleInfos[BackgroundThreadModule.NAME] = ReactModuleInfo(
23
+ BackgroundThreadModule.NAME,
24
+ BackgroundThreadModule.NAME,
25
+ false, // canOverrideExistingModule
26
+ false, // needsEagerInit
27
+ false, // isCxxModule
28
+ true // isTurboModule
29
+ )
30
+ moduleInfos
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,53 @@
1
+ #import <Foundation/Foundation.h>
2
+ #import <UIKit/UIKit.h>
3
+
4
+ #if __has_include(<React-RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>)
5
+ #import <React-RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>
6
+ #elif __has_include(<React_RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>)
7
+ #import <React_RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>
8
+ #else
9
+ #import "RCTDefaultReactNativeFactoryDelegate.h"
10
+ #endif
11
+
12
+ #import <React/RCTComponent.h>
13
+
14
+ #include <string>
15
+ #include <vector>
16
+
17
+ NS_ASSUME_NONNULL_BEGIN
18
+
19
+ @interface BackgroundReactNativeDelegate : RCTDefaultReactNativeFactoryDelegate
20
+
21
+ //@property (nonatomic) std::shared_ptr<const facebook::react::SandboxReactNativeViewEventEmitter> eventEmitter;
22
+ @property (nonatomic, assign) BOOL hasOnMessageHandler;
23
+ @property (nonatomic, assign) BOOL hasOnErrorHandler;
24
+
25
+ @property (nonatomic, readwrite) std::string jsBundleSource;
26
+
27
+ @property (nonatomic, readwrite) std::string origin;
28
+
29
+ @property (nonatomic, copy) void (^onMessageCallback)(NSString *message);
30
+
31
+ /**
32
+ * Initializes the delegate.
33
+ * @return Initialized delegate instance with filtered module access
34
+ */
35
+ - (instancetype)init;
36
+
37
+ /**
38
+ * Posts a message to the JavaScript runtime.
39
+ * @param message C++ string containing the JSON.stringified message
40
+ */
41
+ - (void)postMessage:(const std::string &)message;
42
+
43
+ /**
44
+ * Routes a message to a specific sandbox delegate.
45
+ * @param message The message to route
46
+ * @param targetId The ID of the target sandbox
47
+ * @return true if the message was successfully routed, false otherwise
48
+ */
49
+ - (bool)routeMessage:(const std::string &)message toSandbox:(const std::string &)targetId;
50
+
51
+ @end
52
+
53
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,342 @@
1
+ #import "BackgroundRunnerReactNativeDelegate.h"
2
+
3
+ #include <jsi/JSIDynamic.h>
4
+ #include <jsi/decorator.h>
5
+ #include <react/utils/jsi-utils.h>
6
+ #include <map>
7
+ #include <memory>
8
+ #include <mutex>
9
+
10
+ #import <React/RCTBridge.h>
11
+ #import <React/RCTBundleURLProvider.h>
12
+
13
+ #if __has_include(<react/utils/FollyConvert.h>)
14
+ // static libs / header maps (no use_frameworks!)
15
+ #import <react/utils/FollyConvert.h>
16
+ #elif __has_include("FollyConvert.h")
17
+ /// `use_frameworks! :linkage => :static` users will need to import FollyConvert this way
18
+ #import "FollyConvert.h"
19
+ #elif __has_include("RCTFollyConvert.h")
20
+ #import "RCTFollyConvert.h"
21
+ #else
22
+ #error "FollyConvert.h not found. Ensure React-utils & RCT-Folly pods are installed."
23
+ #endif
24
+
25
+ #if __has_include(<React-RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>)
26
+ #import <React-RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>
27
+ #elif __has_include(<React_RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>)
28
+ #import React_RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h
29
+ #endif
30
+
31
+ #import <ReactAppDependencyProvider/RCTAppDependencyProvider.h>
32
+ #import <ReactCommon/RCTTurboModule.h>
33
+
34
+ #import <objc/runtime.h>
35
+
36
+ #include <fmt/format.h>
37
+
38
+ namespace jsi = facebook::jsi;
39
+ namespace TurboModuleConvertUtils = facebook::react::TurboModuleConvertUtils;
40
+ using namespace facebook::react;
41
+
42
+ static void stubJsiFunction(jsi::Runtime &runtime, jsi::Object &object, const char *name)
43
+ {
44
+ object.setProperty(
45
+ runtime,
46
+ name,
47
+ jsi::Function::createFromHostFunction(
48
+ runtime, jsi::PropNameID::forUtf8(runtime, name), 1, [](auto &, const auto &, const auto *, size_t) {
49
+ return jsi::Value::undefined();
50
+ }));
51
+ }
52
+
53
+ static std::string safeGetStringProperty(jsi::Runtime &rt, const jsi::Object &obj, const char *key)
54
+ {
55
+ if (!obj.hasProperty(rt, key)) {
56
+ return "";
57
+ }
58
+ jsi::Value value = obj.getProperty(rt, key);
59
+ return value.isString() ? value.getString(rt).utf8(rt) : "";
60
+ }
61
+
62
+ @interface BackgroundReactNativeDelegate () {
63
+ RCTInstance *_rctInstance;
64
+ std::shared_ptr<jsi::Function> _onMessageSandbox;
65
+ std::string _origin;
66
+ std::string _jsBundleSource;
67
+ }
68
+
69
+ - (void)cleanupResources;
70
+
71
+ - (jsi::Function)createPostMessageFunction:(jsi::Runtime &)runtime;
72
+ - (jsi::Function)createSetOnMessageFunction:(jsi::Runtime &)runtime;
73
+ - (void)setupErrorHandler:(jsi::Runtime &)runtime;
74
+
75
+ @end
76
+
77
+ @implementation BackgroundReactNativeDelegate
78
+
79
+ #pragma mark - Instance Methods
80
+
81
+ - (instancetype)init
82
+ {
83
+ if (self = [super init]) {
84
+ _hasOnMessageHandler = NO;
85
+ _hasOnErrorHandler = NO;
86
+ self.dependencyProvider = [[RCTAppDependencyProvider alloc] init];
87
+ }
88
+ return self;
89
+ }
90
+
91
+ - (void)cleanupResources
92
+ {
93
+ _onMessageSandbox.reset();
94
+ _rctInstance = nil;
95
+ }
96
+
97
+ #pragma mark - C++ Property Getters
98
+
99
+ - (std::string)origin
100
+ {
101
+ return _origin;
102
+ }
103
+
104
+ - (std::string)jsBundleSource
105
+ {
106
+ return _jsBundleSource;
107
+ }
108
+
109
+ - (void)setJsBundleSource:(std::string)jsBundleSource
110
+ {
111
+ _jsBundleSource = jsBundleSource;
112
+ }
113
+
114
+ - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
115
+ {
116
+ return [self bundleURL];
117
+ }
118
+
119
+ - (NSURL *)bundleURL
120
+ {
121
+ if (!_jsBundleSource.empty()) {
122
+ NSString *jsBundleSourceNS = [NSString stringWithUTF8String:_jsBundleSource.c_str()];
123
+ NSURL *url = [NSURL URLWithString:jsBundleSourceNS];
124
+ if (url && url.scheme) {
125
+ return url;
126
+ }
127
+
128
+ if ([jsBundleSourceNS hasSuffix:@".jsbundle"]) {
129
+ return [[NSBundle mainBundle] URLForResource:jsBundleSourceNS withExtension:nil];
130
+ }
131
+ }
132
+
133
+ return [[NSBundle mainBundle] URLForResource: @"background" withExtension: @"bundle"];
134
+ }
135
+
136
+ - (void)postMessage:(const std::string &)message
137
+ {
138
+ if (!_onMessageSandbox || !_rctInstance) {
139
+ return;
140
+ }
141
+
142
+ [_rctInstance callFunctionOnBufferedRuntimeExecutor:[=](jsi::Runtime &runtime) {
143
+ try {
144
+ // Validate runtime before any JSI operations
145
+ runtime.global(); // Test if runtime is accessible
146
+
147
+ // Double-check the JSI function is still valid
148
+ if (!_onMessageSandbox) {
149
+ return;
150
+ }
151
+
152
+ jsi::Value parsedValue = runtime.global()
153
+ .getPropertyAsObject(runtime, "JSON")
154
+ .getPropertyAsFunction(runtime, "parse")
155
+ .call(runtime, jsi::String::createFromUtf8(runtime, message));
156
+
157
+ _onMessageSandbox->call(runtime, {std::move(parsedValue)});
158
+ } catch (const jsi::JSError &e) {
159
+ // if (self.eventEmitter && self.hasOnErrorHandler) {
160
+ // SandboxReactNativeViewEventEmitter::OnError errorEvent = {
161
+ // .isFatal = false, .name = "JSError", .message = e.getMessage(), .stack = e.getStack()};
162
+ // self.eventEmitter->onError(errorEvent);
163
+ // }
164
+ } catch (const std::exception &e) {
165
+ // if (self.eventEmitter && self.hasOnErrorHandler) {
166
+ // SandboxReactNativeViewEventEmitter::OnError errorEvent = {
167
+ // .isFatal = false, .name = "RuntimeError", .message = e.what(), .stack = ""};
168
+ // self.eventEmitter->onError(errorEvent);
169
+ // }
170
+ } catch (...) {
171
+ NSLog(@"[BackgroundReactNativeDelegate] Runtime invalid during postMessage for sandbox %s", _origin.c_str());
172
+ }
173
+ }];
174
+ }
175
+
176
+ - (bool)routeMessage:(const std::string &)message toSandbox:(const std::string &)targetId
177
+ {
178
+ // auto &registry = SandboxRegistry::getInstance();
179
+ // auto target = registry.find(targetId);
180
+ // if (!target) {
181
+ // return false;
182
+ // }
183
+
184
+ // // Check if the current sandbox is permitted to send messages to the target
185
+ // if (!registry.isPermittedFrom(_origin, targetId)) {
186
+ // // if (self.eventEmitter && self.hasOnErrorHandler) {
187
+ // // std::string errorMessage =
188
+ // // fmt::format("Access denied: Sandbox '{}' is not permitted to send messages to '{}'", _origin, targetId);
189
+ // // SandboxReactNativeViewEventEmitter::OnError errorEvent = {
190
+ // // .isFatal = false, .name = "AccessDeniedError", .message = errorMessage, .stack = ""};
191
+ // // self.eventEmitter->onError(errorEvent);
192
+ // // }
193
+ // return false;
194
+ // }
195
+
196
+ // target->postMessage(message);
197
+ return true;
198
+ }
199
+
200
+ - (void)hostDidStart:(RCTHost *)host
201
+ {
202
+ if (!host) {
203
+ return;
204
+ }
205
+
206
+ // Safely clear any existing JSI function and instance before new runtime setup
207
+ // This prevents crash on reload when old function is tied to invalid runtime
208
+ _onMessageSandbox.reset();
209
+ _onMessageSandbox = nullptr;
210
+
211
+ // Clear old instance reference before setting new one
212
+ _rctInstance = nil;
213
+
214
+ Ivar ivar = class_getInstanceVariable([host class], "_instance");
215
+ _rctInstance = object_getIvar(host, ivar);
216
+
217
+ if (!_rctInstance) {
218
+ return;
219
+ }
220
+
221
+ [_rctInstance callFunctionOnBufferedRuntimeExecutor:[=](jsi::Runtime &runtime) {
222
+ facebook::react::defineReadOnlyGlobal(runtime, "postHostMessage", [self createPostMessageFunction:runtime]);
223
+ facebook::react::defineReadOnlyGlobal(runtime, "onHostMessage", [self createSetOnMessageFunction:runtime]);
224
+ [self setupErrorHandler:runtime];
225
+ }];
226
+ }
227
+
228
+ #pragma mark - RCTTurboModuleManagerDelegate
229
+
230
+ - (id<RCTModuleProvider>)getModuleProvider:(const char *)name
231
+ {
232
+ return [super getModuleProvider:name];
233
+ }
234
+
235
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
236
+ jsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
237
+ {
238
+ return [super getTurboModule:name jsInvoker:jsInvoker];
239
+ }
240
+
241
+ - (jsi::Function)createPostMessageFunction:(jsi::Runtime &)runtime
242
+ {
243
+ return jsi::Function::createFromHostFunction(
244
+ runtime,
245
+ jsi::PropNameID::forAscii(runtime, "postMessage"),
246
+ 2, // Updated to accept up to 2 arguments
247
+ [=](jsi::Runtime &rt, const jsi::Value &, const jsi::Value *args, size_t count) {
248
+ // Validate runtime before any JSI operations
249
+ try {
250
+ rt.global(); // Test if runtime is accessible
251
+ } catch (...) {
252
+ return jsi::Value::undefined();
253
+ }
254
+
255
+ if (count < 1 || count > 2) {
256
+ throw jsi::JSError(rt, "Expected 1 or 2 arguments: postMessage(message, targetOrigin?)");
257
+ }
258
+
259
+ const jsi::Value &messageArg = args[0];
260
+ if (!messageArg.isString()) {
261
+ throw jsi::JSError(rt, "Expected an string as the first argument");
262
+ }
263
+ // jsi::Object jsonObject = rt.global().getPropertyAsObject(rt, "JSON");
264
+ // jsi::Function jsonStringify = jsonObject.getPropertyAsFunction(rt, "stringify");
265
+ // jsi::Value jsonResult = jsonStringify.call(rt, messageArg);
266
+ std::string messageJson = messageArg.getString(rt).utf8(rt);
267
+ NSString *messageNS = [NSString stringWithUTF8String:messageJson.c_str()];
268
+ dispatch_async(dispatch_get_main_queue(), ^{
269
+ if (self.onMessageCallback) {
270
+ self.onMessageCallback(messageNS);
271
+ }
272
+ });
273
+ return jsi::Value::undefined();
274
+ });
275
+ }
276
+
277
+ - (jsi::Function)createSetOnMessageFunction:(jsi::Runtime &)runtime
278
+ {
279
+ return jsi::Function::createFromHostFunction(
280
+ runtime,
281
+ jsi::PropNameID::forAscii(runtime, "setOnMessage"),
282
+ 1,
283
+ [=](jsi::Runtime &rt, const jsi::Value &, const jsi::Value *args, size_t count) {
284
+ if (count != 1) {
285
+ throw jsi::JSError(rt, "Expected exactly one argument");
286
+ }
287
+
288
+ const jsi::Value &arg = args[0];
289
+ if (!arg.isObject() || !arg.asObject(rt).isFunction(rt)) {
290
+ throw jsi::JSError(rt, "Expected a function as the first argument");
291
+ }
292
+
293
+ jsi::Function fn = arg.asObject(rt).asFunction(rt);
294
+
295
+ _onMessageSandbox.reset();
296
+ _onMessageSandbox = std::make_shared<jsi::Function>(std::move(fn));
297
+
298
+ return jsi::Value::undefined();
299
+ });
300
+ }
301
+
302
+ - (void)setupErrorHandler:(jsi::Runtime &)runtime
303
+ {
304
+ // Get ErrorUtils
305
+ jsi::Object global = runtime.global();
306
+ jsi::Value errorUtilsVal = global.getProperty(runtime, "ErrorUtils");
307
+ if (!errorUtilsVal.isObject()) {
308
+ throw std::runtime_error("ErrorUtils is not available on global object");
309
+ }
310
+
311
+ jsi::Object errorUtils = errorUtilsVal.asObject(runtime);
312
+
313
+ std::shared_ptr<jsi::Value> originalHandler = std::make_shared<jsi::Value>(
314
+ errorUtils.getProperty(runtime, "getGlobalHandler").asObject(runtime).asFunction(runtime).call(runtime));
315
+
316
+ auto handlerFunc = jsi::Function::createFromHostFunction(
317
+ runtime,
318
+ jsi::PropNameID::forAscii(runtime, "customGlobalErrorHandler"),
319
+ 2,
320
+ [=, originalHandler = std::move(originalHandler)](
321
+ jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value {
322
+ if (count < 2) {
323
+ return jsi::Value::undefined();
324
+ }
325
+
326
+ if (originalHandler->isObject() && originalHandler->asObject(rt).isFunction(rt)) {
327
+ jsi::Function original = originalHandler->asObject(rt).asFunction(rt);
328
+ original.call(rt, args, count);
329
+ }
330
+
331
+ return jsi::Value::undefined();
332
+ });
333
+
334
+ // Set the new global error handler
335
+ jsi::Function setHandler = errorUtils.getProperty(runtime, "setGlobalHandler").asObject(runtime).asFunction(runtime);
336
+ setHandler.call(runtime, {std::move(handlerFunc)});
337
+
338
+ // Disable further setGlobalHandler from sandbox
339
+ stubJsiFunction(runtime, errorUtils, "setGlobalHandler");
340
+ }
341
+
342
+ @end
@@ -0,0 +1,8 @@
1
+ #import <BackgroundThreadSpec/BackgroundThreadSpec.h>
2
+
3
+ @interface BackgroundThread : NativeBackgroundThreadSpecBase <NativeBackgroundThreadSpec>
4
+
5
+ - (void)startBackgroundRunner;
6
+ - (void)startBackgroundRunnerWithEntryURL:(NSString *)entryURL;
7
+
8
+ @end
@@ -0,0 +1,39 @@
1
+ #import "BackgroundThread.h"
2
+ #import "BackgroundThreadManager.h"
3
+
4
+
5
+ @implementation BackgroundThread
6
+
7
+
8
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
9
+ (const facebook::react::ObjCTurboModule::InitParams &)params
10
+ {
11
+ return std::make_shared<facebook::react::NativeBackgroundThreadSpecJSI>(params);
12
+ }
13
+
14
+ - (void)startBackgroundRunner {
15
+ [[BackgroundThreadManager sharedInstance] startBackgroundRunner];
16
+ }
17
+
18
+ - (void)startBackgroundRunnerWithEntryURL:(NSString *)entryURL {
19
+ BackgroundThreadManager *manager = [BackgroundThreadManager sharedInstance];
20
+
21
+ // Set up message callback to bridge it back through this instance
22
+ __weak __typeof__(self) weakSelf = self;
23
+ [manager setOnMessageCallback:^(NSString *message) {
24
+ [weakSelf emitOnBackgroundMessage:message];
25
+ }];
26
+
27
+ [manager startBackgroundRunnerWithEntryURL:entryURL];
28
+ }
29
+
30
+ - (void)postBackgroundMessage:(nonnull NSString *)message {
31
+ [[BackgroundThreadManager sharedInstance] postBackgroundMessage:message];
32
+ }
33
+
34
+ + (NSString *)moduleName
35
+ {
36
+ return @"BackgroundThread";
37
+ }
38
+
39
+ @end
@@ -0,0 +1,33 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ NS_ASSUME_NONNULL_BEGIN
4
+
5
+ @class BackgroundReactNativeDelegate;
6
+ @class RCTReactNativeFactory;
7
+
8
+ @interface BackgroundThreadManager : NSObject
9
+
10
+ /// Shared instance for singleton pattern
11
+ + (instancetype)sharedInstance;
12
+
13
+ /// Start background runner with default entry URL
14
+ - (void)startBackgroundRunner;
15
+
16
+ /// Start background runner with custom entry URL
17
+ /// @param entryURL The custom entry URL for the background runner
18
+ - (void)startBackgroundRunnerWithEntryURL:(NSString *)entryURL;
19
+
20
+ /// Post message to background runner
21
+ /// @param message The message to post
22
+ - (void)postBackgroundMessage:(NSString *)message;
23
+
24
+ /// Set callback for handling background messages
25
+ /// @param callback The callback block to handle messages
26
+ - (void)setOnMessageCallback:(void (^)(NSString *message))callback;
27
+
28
+ /// Check if background runner is started
29
+ @property (nonatomic, readonly) BOOL isStarted;
30
+
31
+ @end
32
+
33
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,95 @@
1
+ #import "BackgroundThreadManager.h"
2
+ #import <React/RCTBridge.h>
3
+ #import <React/RCTBundleURLProvider.h>
4
+ #if __has_include(<ReactAppDependencyProvider/RCTAppDependencyProvider.h>)
5
+ #import <ReactAppDependencyProvider/RCTAppDependencyProvider.h>
6
+ #endif
7
+ #if __has_include(<ReactAppDependencyProvider/RCTReactNativeFactory.h>)
8
+ #import <ReactAppDependencyProvider/RCTReactNativeFactory.h>
9
+ #endif
10
+ #if __has_include(<ReactAppDependencyProvider/RCTAppDependencyProvider.h>)
11
+ #import <ReactAppDependencyProvider/RCTAppDependencyProvider.h>
12
+ #elif __has_include("RCTAppDependencyProvider.h")
13
+ #import "RCTAppDependencyProvider.h"
14
+ #endif
15
+ #import "BackgroundRunnerReactNativeDelegate.h"
16
+
17
+ @interface BackgroundThreadManager ()
18
+ @property (nonatomic, strong) BackgroundReactNativeDelegate *reactNativeFactoryDelegate;
19
+ @property (nonatomic, strong) RCTReactNativeFactory *reactNativeFactory;
20
+ @property (nonatomic, assign) BOOL hasListeners;
21
+ @property (nonatomic, assign, readwrite) BOOL isStarted;
22
+ @property (nonatomic, copy) void (^onMessageCallback)(NSString *message);
23
+ @end
24
+
25
+ @implementation BackgroundThreadManager
26
+
27
+ static BackgroundThreadManager *_sharedInstance = nil;
28
+ static dispatch_once_t onceToken;
29
+ static NSString *const MODULE_NAME = @"background";
30
+ static NSString *const MODULE_DEBUG_URL = @"http://localhost:8082/apps/mobile/background.bundle?platform=ios&dev=true&lazy=false&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=so.onekey.wallet&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable";
31
+
32
+ #pragma mark - Singleton
33
+
34
+ + (instancetype)sharedInstance {
35
+ dispatch_once(&onceToken, ^{
36
+ _sharedInstance = [[self alloc] init];
37
+ });
38
+ return _sharedInstance;
39
+ }
40
+
41
+ - (instancetype)init {
42
+ self = [super init];
43
+ if (self) {
44
+ _isStarted = NO;
45
+ _hasListeners = NO;
46
+ }
47
+ return self;
48
+ }
49
+
50
+ #pragma mark - Public Methods
51
+
52
+ - (void)startBackgroundRunner {
53
+ [self startBackgroundRunnerWithEntryURL:MODULE_DEBUG_URL];
54
+ }
55
+
56
+ - (void)startBackgroundRunnerWithEntryURL:(NSString *)entryURL {
57
+ if (self.isStarted) {
58
+ return;
59
+ }
60
+ self.isStarted = YES;
61
+
62
+ dispatch_async(dispatch_get_main_queue(), ^{
63
+ NSDictionary *initialProperties = @{};
64
+ NSDictionary *launchOptions = @{};
65
+ self.reactNativeFactoryDelegate = [[BackgroundReactNativeDelegate alloc] init];
66
+ self.reactNativeFactory = [[RCTReactNativeFactory alloc] initWithDelegate:self.reactNativeFactoryDelegate];
67
+
68
+ #if DEBUG
69
+ [self.reactNativeFactoryDelegate setJsBundleSource:std::string([entryURL UTF8String])];
70
+ #endif
71
+
72
+ [self.reactNativeFactory.rootViewFactory viewWithModuleName:MODULE_NAME
73
+ initialProperties:initialProperties
74
+ launchOptions:launchOptions];
75
+
76
+ __weak __typeof__(self) weakSelf = self;
77
+ [self.reactNativeFactoryDelegate setOnMessageCallback:^(NSString *message) {
78
+ if (weakSelf.onMessageCallback) {
79
+ weakSelf.onMessageCallback(message);
80
+ }
81
+ }];
82
+ });
83
+ }
84
+
85
+ - (void)postBackgroundMessage:(NSString *)message {
86
+ if (self.reactNativeFactoryDelegate) {
87
+ [self.reactNativeFactoryDelegate postMessage:std::string([message UTF8String])];
88
+ }
89
+ }
90
+
91
+ - (void)setOnMessageCallback:(void (^)(NSString *message))callback {
92
+ self.onMessageCallback = callback;
93
+ }
94
+
95
+ @end
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+
3
+ import { TurboModuleRegistry } from 'react-native';
4
+ export default TurboModuleRegistry.getEnforcing('BackgroundThread');
5
+ //# sourceMappingURL=NativeBackgroundThread.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["TurboModuleRegistry","getEnforcing"],"sourceRoot":"../../src","sources":["NativeBackgroundThread.ts"],"mappings":";;AAAA,SAASA,mBAAmB,QAAQ,cAAc;AASlD,eAAeA,mBAAmB,CAACC,YAAY,CAAO,kBAAkB,CAAC","ignoreList":[]}
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+
3
+ import NativeBackgroundThread from "./NativeBackgroundThread.js";
4
+ export const BackgroundThread = NativeBackgroundThread;
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["NativeBackgroundThread","BackgroundThread"],"sourceRoot":"../../src","sources":["index.tsx"],"mappings":";;AAAA,OAAOA,sBAAsB,MAAM,6BAA0B;AAE7D,OAAO,MAAMC,gBAAgB,GAAGD,sBAAsB","ignoreList":[]}
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,9 @@
1
+ import type { CodegenTypes, TurboModule } from 'react-native';
2
+ export interface Spec extends TurboModule {
3
+ readonly onBackgroundMessage: CodegenTypes.EventEmitter<string>;
4
+ postBackgroundMessage(message: string): void;
5
+ startBackgroundRunnerWithEntryURL(entryURL: string): void;
6
+ }
7
+ declare const _default: Spec;
8
+ export default _default;
9
+ //# sourceMappingURL=NativeBackgroundThread.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NativeBackgroundThread.d.ts","sourceRoot":"","sources":["../../../src/NativeBackgroundThread.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC9D,MAAM,WAAW,IAAK,SAAQ,WAAW;IACvC,QAAQ,CAAC,mBAAmB,EAAE,YAAY,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IAChE,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7C,iCAAiC,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3D;;AAED,wBAA0E"}
@@ -0,0 +1,2 @@
1
+ export declare const BackgroundThread: import("./NativeBackgroundThread").Spec;
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.tsx"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB,yCAAyB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,169 @@
1
+ {
2
+ "name": "@onekeyfe/react-native-background-thread",
3
+ "version": "1.1.7",
4
+ "description": "react-native-background-thread",
5
+ "main": "./lib/module/index.js",
6
+ "types": "./lib/typescript/src/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "source": "./src/index.tsx",
10
+ "types": "./lib/typescript/src/index.d.ts",
11
+ "default": "./lib/module/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "lib",
18
+ "android",
19
+ "ios",
20
+ "cpp",
21
+ "*.podspec",
22
+ "react-native.config.js",
23
+ "!ios/build",
24
+ "!android/build",
25
+ "!android/gradle",
26
+ "!android/gradlew",
27
+ "!android/gradlew.bat",
28
+ "!android/local.properties",
29
+ "!**/__tests__",
30
+ "!**/__fixtures__",
31
+ "!**/__mocks__",
32
+ "!**/.*"
33
+ ],
34
+ "scripts": {
35
+ "example": "yarn workspace react-native-background-thread-example",
36
+ "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build lib",
37
+ "prepare": "bob build",
38
+ "typecheck": "tsc",
39
+ "lint": "eslint \"**/*.{js,ts,tsx}\"",
40
+ "test": "jest",
41
+ "release": "yarn prepare && npm whoami && npm publish --access public"
42
+ },
43
+ "keywords": [
44
+ "react-native",
45
+ "ios",
46
+ "android"
47
+ ],
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/OneKeyHQ/app-modules/react-native-background-thread.git"
51
+ },
52
+ "author": "@onekeyhq <huanming@onekey.so> (https://github.com/OneKeyHQ/app-modules)",
53
+ "license": "MIT",
54
+ "bugs": {
55
+ "url": "https://github.com/OneKeyHQ/app-modules/react-native-background-thread/issues"
56
+ },
57
+ "homepage": "https://github.com/OneKeyHQ/app-modules/react-native-background-thread#readme",
58
+ "publishConfig": {
59
+ "registry": "https://registry.npmjs.org/"
60
+ },
61
+ "devDependencies": {
62
+ "@commitlint/config-conventional": "^19.8.1",
63
+ "@eslint/compat": "^1.3.2",
64
+ "@eslint/eslintrc": "^3.3.1",
65
+ "@eslint/js": "^9.35.0",
66
+ "@react-native/babel-preset": "0.83.0",
67
+ "@react-native/eslint-config": "0.83.0",
68
+ "@release-it/conventional-changelog": "^10.0.1",
69
+ "@types/jest": "^29.5.14",
70
+ "@types/react": "^19.2.0",
71
+ "commitlint": "^19.8.1",
72
+ "del-cli": "^6.0.0",
73
+ "eslint": "^9.35.0",
74
+ "eslint-config-prettier": "^10.1.8",
75
+ "eslint-plugin-prettier": "^5.5.4",
76
+ "jest": "^29.7.0",
77
+ "lefthook": "^2.0.3",
78
+ "prettier": "^2.8.8",
79
+ "react": "19.2.0",
80
+ "react-native": "0.83.0",
81
+ "react-native-builder-bob": "^0.40.17",
82
+ "release-it": "^19.0.4",
83
+ "turbo": "^2.5.6",
84
+ "typescript": "^5.9.2"
85
+ },
86
+ "peerDependencies": {
87
+ "react": "*",
88
+ "react-native": "*"
89
+ },
90
+ "workspaces": [
91
+ "example"
92
+ ],
93
+ "packageManager": "yarn@4.11.0",
94
+ "react-native-builder-bob": {
95
+ "source": "src",
96
+ "output": "lib",
97
+ "targets": [
98
+ [
99
+ "module",
100
+ {
101
+ "esm": true
102
+ }
103
+ ],
104
+ [
105
+ "typescript",
106
+ {
107
+ "project": "tsconfig.build.json"
108
+ }
109
+ ]
110
+ ]
111
+ },
112
+ "codegenConfig": {
113
+ "name": "BackgroundThreadSpec",
114
+ "type": "modules",
115
+ "jsSrcsDir": "src",
116
+ "android": {
117
+ "javaPackageName": "com.backgroundthread"
118
+ }
119
+ },
120
+ "prettier": {
121
+ "quoteProps": "consistent",
122
+ "singleQuote": true,
123
+ "tabWidth": 2,
124
+ "trailingComma": "es5",
125
+ "useTabs": false
126
+ },
127
+ "jest": {
128
+ "preset": "react-native",
129
+ "modulePathIgnorePatterns": [
130
+ "<rootDir>/example/node_modules",
131
+ "<rootDir>/lib/"
132
+ ]
133
+ },
134
+ "commitlint": {
135
+ "extends": [
136
+ "@commitlint/config-conventional"
137
+ ]
138
+ },
139
+ "release-it": {
140
+ "git": {
141
+ "commitMessage": "chore: release ${version}",
142
+ "tagName": "v${version}"
143
+ },
144
+ "npm": {
145
+ "publish": true
146
+ },
147
+ "github": {
148
+ "release": true
149
+ },
150
+ "plugins": {
151
+ "@release-it/conventional-changelog": {
152
+ "preset": {
153
+ "name": "angular"
154
+ }
155
+ }
156
+ }
157
+ },
158
+ "create-react-native-library": {
159
+ "type": "turbo-module",
160
+ "languages": "kotlin-objc",
161
+ "tools": [
162
+ "eslint",
163
+ "jest",
164
+ "lefthook",
165
+ "release-it"
166
+ ],
167
+ "version": "0.56.0"
168
+ }
169
+ }
@@ -0,0 +1,10 @@
1
+ import { TurboModuleRegistry } from 'react-native';
2
+
3
+ import type { CodegenTypes, TurboModule } from 'react-native';
4
+ export interface Spec extends TurboModule {
5
+ readonly onBackgroundMessage: CodegenTypes.EventEmitter<string>;
6
+ postBackgroundMessage(message: string): void;
7
+ startBackgroundRunnerWithEntryURL(entryURL: string): void;
8
+ }
9
+
10
+ export default TurboModuleRegistry.getEnforcing<Spec>('BackgroundThread');
package/src/index.tsx ADDED
@@ -0,0 +1,3 @@
1
+ import NativeBackgroundThread from './NativeBackgroundThread';
2
+
3
+ export const BackgroundThread = NativeBackgroundThread;