From 229e7d83dbaea783e5e5c405e5a9b01ac8b33be5 Mon Sep 17 00:00:00 2001 From: Marc Rousavy Date: Fri, 17 Oct 2025 18:35:16 +0200 Subject: [PATCH] feat: Create `ObjectUtils` for `Object.freeze`, `Object.defineProperty`, ... (#967) * feat: Create `ObjectUtils` for `Object.freeze`, `Object.defineProperty`, ... * Use Object.create * Fix missing obj * fix: Better error * Cache * fix: Actually cache by preventing copy * Object.create is part of RN 78 * Use `defineProperty(...)` for `Dispatcher` too * Optimize Dispatcher install * Create `getGlobalFunction` * feat: Use `defineGlobal(...)` to define our global props * fix: Move the globals * fix: Don't protect/freeze the globals in JS we already do it in native. --- .../java/com/margelo/nitro/NitroModules.kt | 2 + .../cpp/core/HybridObject.cpp | 28 +-- .../cpp/entrypoint/InstallNitro.cpp | 3 +- .../cpp/jsi/JSICache.cpp | 14 +- .../cpp/prototype/HybridObjectPrototype.cpp | 60 ++++--- .../cpp/threading/Dispatcher.cpp | 10 +- .../cpp/utils/ObjectUtils.cpp | 166 ++++++++++++++++++ .../cpp/utils/ObjectUtils.hpp | 94 ++++++++++ .../turbomodule/NativeNitroModules+NewArch.mm | 15 +- .../src/globals.d.ts | 29 +++ .../src/turbomodule/NativeNitroModules.ts | 26 +-- 11 files changed, 366 insertions(+), 81 deletions(-) create mode 100644 packages/react-native-nitro-modules/cpp/utils/ObjectUtils.cpp create mode 100644 packages/react-native-nitro-modules/cpp/utils/ObjectUtils.hpp create mode 100644 packages/react-native-nitro-modules/src/globals.d.ts diff --git a/packages/react-native-nitro-modules/android/src/main/java/com/margelo/nitro/NitroModules.kt b/packages/react-native-nitro-modules/android/src/main/java/com/margelo/nitro/NitroModules.kt index 23b504da4..25d74a215 100644 --- a/packages/react-native-nitro-modules/android/src/main/java/com/margelo/nitro/NitroModules.kt +++ b/packages/react-native-nitro-modules/android/src/main/java/com/margelo/nitro/NitroModules.kt @@ -1,5 +1,6 @@ package com.margelo.nitro +import android.util.Log import androidx.annotation.Keep import com.facebook.jni.HybridData import com.facebook.proguard.annotations.DoNotStrip @@ -46,6 +47,7 @@ class NitroModules internal constructor( return null } catch (e: Throwable) { // ?. Something went wrong! Maybe a JNI error? + Log.e(NAME, "Failed to install Nitro!", e) return e.message } } diff --git a/packages/react-native-nitro-modules/cpp/core/HybridObject.cpp b/packages/react-native-nitro-modules/cpp/core/HybridObject.cpp index acfed2f89..db12f15d0 100644 --- a/packages/react-native-nitro-modules/cpp/core/HybridObject.cpp +++ b/packages/react-native-nitro-modules/cpp/core/HybridObject.cpp @@ -5,6 +5,7 @@ #include "HybridObject.hpp" #include "JSIConverter.hpp" #include "NitroDefines.hpp" +#include "ObjectUtils.hpp" namespace margelo::nitro { @@ -73,29 +74,32 @@ jsi::Value HybridObject::toObject(jsi::Runtime& runtime) { // 2. Get the object's base prototype (global & shared) jsi::Value prototype = getPrototype(runtime); - // 3. Get the global JS Object.create(...) constructor so we can create an object from the given prototype - jsi::Object objectConstructor = runtime.global().getPropertyAsObject(runtime, "Object"); - jsi::Function create = objectConstructor.getPropertyAsFunction(runtime, "create"); + // 3. Create the object using Object.create(...) + jsi::Object object = ObjectUtils::create(runtime, prototype); - // 4. Create the object using Object.create(...) - jsi::Object object = create.call(runtime, prototype).asObject(runtime); - - // 5. Assign NativeState to the object so the prototype can resolve the native methods + // 4. Assign NativeState to the object so the prototype can resolve the native methods object.setNativeState(runtime, shared()); - // 6. Set memory size so Hermes GC knows about actual memory + // 5. Set memory size so Hermes GC knows about actual memory object.setExternalMemoryPressure(runtime, getExternalMemorySize()); #ifdef NITRO_DEBUG - // 7. Assign a private __type property for debugging - this will be used so users know it's not just an empty object. - object.setProperty(runtime, "__type", jsi::String::createFromUtf8(runtime, "NativeState<" + std::string(_name) + ">")); + // 6. Assign a private __type property for debugging - this will be used so users know it's not just an empty object. + std::string typeName = "HybridObject<" + std::string(_name) + ">"; + ObjectUtils::defineProperty(runtime, object, "__type", + PlainPropertyDescriptor{ + .configurable = false, + .enumerable = true, + .value = jsi::String::createFromUtf8(runtime, typeName), + .writable = false, + }); #endif - // 8. Throw a jsi::WeakObject pointing to our object into cache so subsequent calls can use it from cache + // 7. Throw a jsi::WeakObject pointing to our object into cache so subsequent calls can use it from cache JSICacheReference cache = JSICache::getOrCreateCache(runtime); _objectCache[&runtime] = cache.makeShared(jsi::WeakObject(runtime, object)); - // 9. Return it! + // 8. Return it! return object; } diff --git a/packages/react-native-nitro-modules/cpp/entrypoint/InstallNitro.cpp b/packages/react-native-nitro-modules/cpp/entrypoint/InstallNitro.cpp index 063e7f8ad..5cb9399de 100644 --- a/packages/react-native-nitro-modules/cpp/entrypoint/InstallNitro.cpp +++ b/packages/react-native-nitro-modules/cpp/entrypoint/InstallNitro.cpp @@ -7,6 +7,7 @@ #include "InstallNitro.hpp" #include "HybridNitroModulesProxy.hpp" +#include "ObjectUtils.hpp" namespace margelo::nitro { @@ -22,7 +23,7 @@ void install(jsi::Runtime& runtime, std::shared_ptr dispatcher) { void install(jsi::Runtime& runtime) { // Installs global.NitroModulesProxy auto proxy = std::make_shared(); - runtime.global().setProperty(runtime, "NitroModulesProxy", proxy->toObject(runtime)); + ObjectUtils::defineGlobal(runtime, KnownGlobalPropertyName::NITRO_MODULES_PROXY, proxy->toObject(runtime)); } } // namespace margelo::nitro diff --git a/packages/react-native-nitro-modules/cpp/jsi/JSICache.cpp b/packages/react-native-nitro-modules/cpp/jsi/JSICache.cpp index 7308901e2..62d666530 100644 --- a/packages/react-native-nitro-modules/cpp/jsi/JSICache.cpp +++ b/packages/react-native-nitro-modules/cpp/jsi/JSICache.cpp @@ -8,11 +8,10 @@ #include "JSICache.hpp" #include "JSIHelpers.hpp" #include "NitroDefines.hpp" +#include "ObjectUtils.hpp" namespace margelo::nitro { -static constexpr auto CACHE_PROP_NAME = "__nitroModulesJSICache"; - template inline void destroyReferences(const std::vector>& references) { for (auto& func : references) { @@ -48,12 +47,6 @@ JSICacheReference JSICache::getOrCreateCache(jsi::Runtime& runtime) { Logger::log(LogLevel::Warning, TAG, "JSICache was created, but it is no longer strong!"); } -#ifdef NITRO_DEBUG - if (runtime.global().hasProperty(runtime, CACHE_PROP_NAME)) [[unlikely]] { - throw std::runtime_error("The Runtime \"" + getRuntimeId(runtime) + "\" already has a global cache! (\"" + CACHE_PROP_NAME + "\")"); - } -#endif - // Cache doesn't exist yet. Logger::log(LogLevel::Info, TAG, "Creating new JSICache for runtime %s..", getRuntimeId(runtime).c_str()); // Create new cache @@ -61,8 +54,9 @@ JSICacheReference JSICache::getOrCreateCache(jsi::Runtime& runtime) { // Wrap it in a jsi::Value using NativeState jsi::Object cache(runtime); cache.setNativeState(runtime, nativeState); - // Inject it into the jsi::Runtime's global so it's memory is managed by it - runtime.global().setProperty(runtime, CACHE_PROP_NAME, std::move(cache)); + // Inject it into the jsi::Runtime's global so it's memory is managed by it. + // We pass `allowCache = false` because we are the JSICache, and this would cause recursion. + ObjectUtils::defineGlobal(runtime, KnownGlobalPropertyName::JSI_CACHE, std::move(cache), /* allowCache */ false); // Add it to our map of caches _globalCache[&runtime] = nativeState; // Return it diff --git a/packages/react-native-nitro-modules/cpp/prototype/HybridObjectPrototype.cpp b/packages/react-native-nitro-modules/cpp/prototype/HybridObjectPrototype.cpp index 53dd0150f..1d64f14d5 100644 --- a/packages/react-native-nitro-modules/cpp/prototype/HybridObjectPrototype.cpp +++ b/packages/react-native-nitro-modules/cpp/prototype/HybridObjectPrototype.cpp @@ -9,6 +9,7 @@ #include "NitroDefines.hpp" #include "NitroLogger.hpp" #include "NitroTypeInfo.hpp" +#include "ObjectUtils.hpp" namespace margelo::nitro { @@ -33,16 +34,12 @@ jsi::Value HybridObjectPrototype::createPrototype(jsi::Runtime& runtime, const s } } - // 2. We didn't find the given prototype in cache (either it's a new prototype, or a new runtime), - // so we need to create it. First, we need some helper methods from JS + // 2. Get the base prototype of this prototype (recursively), then create the individual prototypes downwards + // until we reach our current prototype. std::string typeName = TypeInfo::getFriendlyTypename(prototype->getNativeInstanceId(), true); Logger::log(LogLevel::Info, TAG, "Creating new JS prototype for C++ instance type \"%s\"...", typeName.c_str()); - jsi::Object objectConstructor = runtime.global().getPropertyAsObject(runtime, "Object"); - jsi::Function objectCreate = objectConstructor.getPropertyAsFunction(runtime, "create"); - jsi::Function objectDefineProperty = objectConstructor.getPropertyAsFunction(runtime, "defineProperty"); - - // 3. Create an empty JS Object, inheriting from the base prototype (recursively!) - jsi::Object object = objectCreate.call(runtime, createPrototype(runtime, prototype->getBase())).getObject(runtime); + jsi::Value basePrototype = createPrototype(runtime, prototype->getBase()); + jsi::Object object = ObjectUtils::create(runtime, basePrototype); // 4. Add all Hybrid Methods to it for (const auto& method : prototype->getMethods()) { @@ -51,37 +48,48 @@ jsi::Value HybridObjectPrototype::createPrototype(jsi::Runtime& runtime, const s // 5. Add all properties (getter + setter) to it using defineProperty for (const auto& getter : prototype->getGetters()) { - jsi::Object property(runtime); - property.setProperty(runtime, "configurable", false); - property.setProperty(runtime, "enumerable", true); - property.setProperty(runtime, "get", getter.second.toJSFunction(runtime)); - const auto& setter = prototype->getSetters().find(getter.first); - if (setter != prototype->getSetters().end()) { - // there also is a setter for this property! - property.setProperty(runtime, "set", setter->second.toJSFunction(runtime)); + bool isReadonly = setter == prototype->getSetters().end(); + const std::string& name = getter.first; + if (isReadonly) { + // get + ObjectUtils::defineProperty( + runtime, object, name.c_str(), + ComputedReadonlyPropertyDescriptor{.configurable = false, .enumerable = false, .get = getter.second.toJSFunction(runtime)}); + } else { + // get + set + ObjectUtils::defineProperty(runtime, object, name.c_str(), + ComputedPropertyDescriptor{.configurable = false, + .enumerable = false, + .get = getter.second.toJSFunction(runtime), + .set = setter->second.toJSFunction(runtime)}); } - - property.setProperty(runtime, "name", jsi::String::createFromUtf8(runtime, getter.first.c_str())); - objectDefineProperty.call(runtime, - /* obj */ object, - /* propName */ jsi::String::createFromUtf8(runtime, getter.first.c_str()), - /* descriptorObj */ property); } // 6. In DEBUG, add a __type info to the prototype object. #ifdef NITRO_DEBUG - auto prototypeName = "Prototype<" + typeName + ">"; - object.setProperty(runtime, "__type", jsi::String::createFromUtf8(runtime, prototypeName)); + std::string prototypeName = "Prototype<" + typeName + ">"; + ObjectUtils::defineProperty(runtime, object, "__type", + PlainPropertyDescriptor{ + .configurable = false, + .enumerable = true, + .value = jsi::String::createFromUtf8(runtime, prototypeName), + .writable = false, + }); #endif - // 7. Throw it into our cache so the next lookup can be cached and therefore faster + // 7. In DEBUG, freeze the prototype. +#ifdef NITRO_DEBUG + ObjectUtils::freeze(runtime, object); +#endif + + // 8. Throw it into our cache so the next lookup can be cached and therefore faster JSICacheReference jsiCache = JSICache::getOrCreateCache(runtime); BorrowingReference sharedObject = jsiCache.makeShared(std::move(object)); auto instanceId = prototype->getNativeInstanceId(); prototypeCache[instanceId] = sharedObject; - // 8. Return it! + // 9. Return it! return jsi::Value(runtime, *sharedObject); } diff --git a/packages/react-native-nitro-modules/cpp/threading/Dispatcher.cpp b/packages/react-native-nitro-modules/cpp/threading/Dispatcher.cpp index d10b785e3..11d85bf04 100644 --- a/packages/react-native-nitro-modules/cpp/threading/Dispatcher.cpp +++ b/packages/react-native-nitro-modules/cpp/threading/Dispatcher.cpp @@ -10,13 +10,12 @@ #include "JSIHelpers.hpp" #include "NitroDefines.hpp" #include "NitroLogger.hpp" +#include "ObjectUtils.hpp" namespace margelo::nitro { using namespace facebook; -static constexpr auto GLOBAL_DISPATCHER_HOLDER_NAME = "__nitroDispatcher"; - /** * This map is only statically linked once to this library. * If multiple versions of react-native-nitro-modules are linked, there would be multiple maps. We catch that issue later. @@ -31,7 +30,7 @@ void Dispatcher::installRuntimeGlobalDispatcher(jsi::Runtime& runtime, std::shar // Inject the dispatcher into Runtime global (runtime will hold a strong reference) jsi::Value dispatcherHolder = JSIConverter>::toJSI(runtime, dispatcher); - runtime.global().setProperty(runtime, GLOBAL_DISPATCHER_HOLDER_NAME, std::move(dispatcherHolder)); + ObjectUtils::defineGlobal(runtime, KnownGlobalPropertyName::DISPATCHER, std::move(dispatcherHolder)); } std::shared_ptr Dispatcher::getRuntimeGlobalDispatcher(jsi::Runtime& runtime) { @@ -58,14 +57,15 @@ std::shared_ptr Dispatcher::getRuntimeGlobalDispatcher(jsi::Runtime& } jsi::Value Dispatcher::getRuntimeGlobalDispatcherHolder(jsi::Runtime& runtime) { - if (!runtime.global().hasProperty(runtime, GLOBAL_DISPATCHER_HOLDER_NAME)) [[unlikely]] { + const char* dispatcherHolderName = ObjectUtils::getKnownGlobalPropertyNameString(KnownGlobalPropertyName::DISPATCHER); + if (!runtime.global().hasProperty(runtime, dispatcherHolderName)) [[unlikely]] { throw std::runtime_error("The `jsi::Runtime` \"" + getRuntimeId(runtime) + "\" does not support Callbacks or Promises because it does not have a `Dispatcher` installed!\n" "To use Callbacks and Promises follow these steps;\n" "1. Subclass `Dispatcher` with your implementation of `runAsync`/`runSync` for your Thread.\n" "2. Call `Dispatcher::installRuntimeGlobalDispatcher(...)` with your `Runtime` and your `Dispatcher`."); } - return runtime.global().getProperty(runtime, GLOBAL_DISPATCHER_HOLDER_NAME); + return runtime.global().getProperty(runtime, dispatcherHolderName); } } // namespace margelo::nitro diff --git a/packages/react-native-nitro-modules/cpp/utils/ObjectUtils.cpp b/packages/react-native-nitro-modules/cpp/utils/ObjectUtils.cpp new file mode 100644 index 000000000..15568f9fe --- /dev/null +++ b/packages/react-native-nitro-modules/cpp/utils/ObjectUtils.cpp @@ -0,0 +1,166 @@ +// +// ObjectUtils.cpp +// react-native-nitro +// +// Created by Marc Rousavy on 17.10.25. +// + +#include "ObjectUtils.hpp" +#include "JSICache.hpp" +#include "JSIHelpers.hpp" +#include "NitroDefines.hpp" + +#if __has_include() +#include +#if REACT_NATIVE_VERSION_MINOR >= 78 +#define ENABLE_NATIVE_OBJECT_CREATE +#endif +#endif + +namespace margelo::nitro { + +using namespace facebook; + +std::unordered_map ObjectUtils::_cache; + +jsi::Object ObjectUtils::create(jsi::Runtime& runtime, const jsi::Value& prototype, bool allowCache) { +#ifdef ENABLE_NATIVE_OBJECT_CREATE + return jsi::Object::create(runtime, prototype); +#else + BorrowingReference createFn = getGlobalFunction(runtime, "Object.create", [](jsi::Runtime& runtime) { + return runtime.global().getPropertyAsObject(runtime, "Object").getPropertyAsFunction(runtime, "create"); + }); + return createFn->call(runtime, prototype).getObject(runtime); +#endif +} + +const char* ObjectUtils::getKnownGlobalPropertyNameString(KnownGlobalPropertyName name) { + switch (name) { + case KnownGlobalPropertyName::DISPATCHER: + return "__nitroDispatcher"; + case KnownGlobalPropertyName::JSI_CACHE: + return "__nitroJsiCache"; + case KnownGlobalPropertyName::NITRO_MODULES_PROXY: + return "NitroModulesProxy"; + } +} + +void ObjectUtils::defineGlobal(jsi::Runtime& runtime, KnownGlobalPropertyName name, jsi::Value&& value, bool allowCache) { + const char* nameString = getKnownGlobalPropertyNameString(name); + +#ifdef NITRO_DEBUG + // In debug, let's perform additional safety checks. + if (runtime.global().hasProperty(runtime, nameString)) [[unlikely]] { + throw std::runtime_error("Failed to set `global." + std::string(nameString) + "` - it already exists for Runtime \"" + + getRuntimeId(runtime) + "\"! Did you call `defineGlobal(\"" + std::string(nameString) + + "\")` twice? Did you link Nitro Modules twice?"); + } + defineProperty(runtime, runtime.global(), nameString, + PlainPropertyDescriptor{.configurable = false, .enumerable = true, .value = std::move(value), .writable = false}, + allowCache); +#else + // In release, just set the property. + runtime.global().setProperty(runtime, nameString, std::move(value)); +#endif +} + +void ObjectUtils::defineProperty(jsi::Runtime& runtime, const jsi::Object& object, const char* propertyName, + PlainPropertyDescriptor&& descriptor, bool allowCache) { + BorrowingReference definePropertyFn = getGlobalFunction( + runtime, "Object.defineProperty", + [](jsi::Runtime& runtime) { + return runtime.global().getPropertyAsObject(runtime, "Object").getPropertyAsFunction(runtime, "defineProperty"); + }, + allowCache); + + jsi::String nameJs = jsi::String::createFromAscii(runtime, propertyName); + + jsi::Object descriptorJs(runtime); + descriptorJs.setProperty(runtime, "configurable", jsi::Value(descriptor.configurable)); + descriptorJs.setProperty(runtime, "enumerable", jsi::Value(descriptor.enumerable)); + descriptorJs.setProperty(runtime, "value", std::move(descriptor.value)); + descriptorJs.setProperty(runtime, "writable", jsi::Value(descriptor.writable)); + + definePropertyFn->call(runtime, object, std::move(nameJs), std::move(descriptorJs)); +} + +void ObjectUtils::defineProperty(jsi::Runtime& runtime, const jsi::Object& object, const char* propertyName, + ComputedReadonlyPropertyDescriptor&& descriptor, bool allowCache) { + BorrowingReference definePropertyFn = getGlobalFunction( + runtime, "Object.defineProperty", + [](jsi::Runtime& runtime) { + return runtime.global().getPropertyAsObject(runtime, "Object").getPropertyAsFunction(runtime, "defineProperty"); + }, + allowCache); + + jsi::String nameJs = jsi::String::createFromAscii(runtime, propertyName); + + jsi::Object descriptorJs(runtime); + descriptorJs.setProperty(runtime, "configurable", jsi::Value(descriptor.configurable)); + descriptorJs.setProperty(runtime, "enumerable", jsi::Value(descriptor.enumerable)); + descriptorJs.setProperty(runtime, "get", std::move(descriptor.get)); + + definePropertyFn->call(runtime, object, std::move(nameJs), std::move(descriptorJs)); +} + +void ObjectUtils::defineProperty(jsi::Runtime& runtime, const jsi::Object& object, const char* propertyName, + ComputedPropertyDescriptor&& descriptor, bool allowCache) { + BorrowingReference definePropertyFn = getGlobalFunction( + runtime, "Object.defineProperty", + [](jsi::Runtime& runtime) { + return runtime.global().getPropertyAsObject(runtime, "Object").getPropertyAsFunction(runtime, "defineProperty"); + }, + allowCache); + + jsi::String nameJs = jsi::String::createFromAscii(runtime, propertyName); + + jsi::Object descriptorJs(runtime); + descriptorJs.setProperty(runtime, "configurable", jsi::Value(descriptor.configurable)); + descriptorJs.setProperty(runtime, "enumerable", jsi::Value(descriptor.enumerable)); + descriptorJs.setProperty(runtime, "get", std::move(descriptor.get)); + descriptorJs.setProperty(runtime, "set", std::move(descriptor.set)); + + definePropertyFn->call(runtime, object, std::move(nameJs), std::move(descriptorJs)); +} + +void ObjectUtils::freeze(jsi::Runtime& runtime, const jsi::Object& object, bool allowCache) { + BorrowingReference freezeFn = getGlobalFunction( + runtime, "Object.freeze", + [](jsi::Runtime& runtime) { + return runtime.global().getPropertyAsObject(runtime, "Object").getPropertyAsFunction(runtime, "freeze"); + }, + allowCache); + + freezeFn->call(runtime, object); +} + +BorrowingReference ObjectUtils::getGlobalFunction(jsi::Runtime& runtime, const char* key, + std::function getFunction, bool allowCache) { + if (allowCache) [[likely]] { + // Let's try to find the function in cache + FunctionCache& functionCache = _cache[&runtime]; + std::string stringKey = key; + auto iterator = functionCache.find(stringKey); + if (iterator != functionCache.end()) { + // We found it! Copy & return the reference + BorrowingReference function = iterator->second; + return function; + } + } + // We haven't found the function with the given key in cache - so let's get it: + jsi::Function function = getFunction(runtime); + if (allowCache) [[likely]] { + // Let's throw it in cache! + FunctionCache& functionCache = _cache[&runtime]; + JSICacheReference jsiCache = JSICache::getOrCreateCache(runtime); + BorrowingReference sharedFunction = jsiCache.makeShared(std::move(function)); + functionCache[std::string(key)] = sharedFunction; + return sharedFunction; + } else { + // We are not allowed to use cache - so let's just wrap it in a BorrowingReference to match the return type. + jsi::Function* heapFunction = new jsi::Function(std::move(function)); + return BorrowingReference(heapFunction); + } +} + +} // namespace margelo::nitro diff --git a/packages/react-native-nitro-modules/cpp/utils/ObjectUtils.hpp b/packages/react-native-nitro-modules/cpp/utils/ObjectUtils.hpp new file mode 100644 index 000000000..864e6e1a1 --- /dev/null +++ b/packages/react-native-nitro-modules/cpp/utils/ObjectUtils.hpp @@ -0,0 +1,94 @@ +// +// ObjectUtils.hpp +// react-native-nitro +// +// Created by Marc Rousavy on 17.10.25. +// + +#pragma once + +#include "BorrowingReference.hpp" +#include +#include + +namespace margelo::nitro { + +using namespace facebook; + +struct PlainPropertyDescriptor { + bool configurable; + bool enumerable; + jsi::Value value; + bool writable; +}; +struct ComputedReadonlyPropertyDescriptor { + bool configurable; + bool enumerable; + jsi::Function get; +}; +struct ComputedPropertyDescriptor { + bool configurable; + bool enumerable; + jsi::Function get; + jsi::Function set; +}; + +enum class KnownGlobalPropertyName { DISPATCHER, JSI_CACHE, NITRO_MODULES_PROXY }; + +class ObjectUtils { +public: + ObjectUtils() = delete; + ~ObjectUtils() = delete; + +public: + /** + * Create a new `jsi::Object` with the given `prototype`. + * Uses a native implementation if possible. + */ + static jsi::Object create(jsi::Runtime& runtime, const jsi::Value& prototype, bool allowCache = true); + + /** + * Define a global value for the given Runtime. + * In debug, this performs additional safety checks such as freezing the property. + */ + static void defineGlobal(jsi::Runtime& runtime, KnownGlobalPropertyName name, jsi::Value&& value, bool allowCache = true); + + /** + * Define a plain property on the given `object` with the given `propertyName`. + * The `descriptor` defines the attributes of this property. + */ + static void defineProperty(jsi::Runtime& runtime, const jsi::Object& object, const char* propertyName, + PlainPropertyDescriptor&& descriptor, bool allowCache = true); + /** + * Define a plain property on the given `object` with the given `propertyName`. + * The `descriptor` defines the attributes of this property. + */ + static void defineProperty(jsi::Runtime& runtime, const jsi::Object& object, const char* propertyName, + ComputedReadonlyPropertyDescriptor&& descriptor, bool allowCache = true); + /** + * Define a plain property on the given `object` with the given `propertyName`. + * The `descriptor` defines the attributes of this property. + */ + static void defineProperty(jsi::Runtime& runtime, const jsi::Object& object, const char* propertyName, + ComputedPropertyDescriptor&& descriptor, bool allowCache = true); + + /** + * Freezes all values of the given `object`. + */ + static void freeze(jsi::Runtime& runtime, const jsi::Object& object, bool allowCache = true); + + /** + * Get a string name for a known global property name. + */ + static const char* getKnownGlobalPropertyNameString(KnownGlobalPropertyName name); + +private: + using FunctionCache = std::unordered_map>; + static std::unordered_map _cache; + + static BorrowingReference getGlobalFunction(jsi::Runtime& runtime, const char* key, + std::function getFunction, + bool allowCache = true); +}; + +} // namespace margelo::nitro diff --git a/packages/react-native-nitro-modules/ios/turbomodule/NativeNitroModules+NewArch.mm b/packages/react-native-nitro-modules/ios/turbomodule/NativeNitroModules+NewArch.mm index 3e0a8c894..2086ac31b 100644 --- a/packages/react-native-nitro-modules/ios/turbomodule/NativeNitroModules+NewArch.mm +++ b/packages/react-native-nitro-modules/ios/turbomodule/NativeNitroModules+NewArch.mm @@ -11,6 +11,7 @@ #import "CallInvokerDispatcher.hpp" #import "InstallNitro.hpp" +#import "NitroLogger.hpp" #import #import @@ -28,6 +29,7 @@ using namespace margelo; */ @implementation NativeNitroModules { bool _didInstall; + NSString* _Nullable _errorMessage; std::weak_ptr _callInvoker; } RCT_EXPORT_MODULE(NitroModules) @@ -43,8 +45,14 @@ RCT_EXPORT_MODULE(NitroModules) auto dispatcher = std::make_shared(callInvoker); // 3. Install Nitro - nitro::install(runtime, dispatcher); - _didInstall = true; + try { + nitro::install(runtime, dispatcher); + _didInstall = true; + } catch (const std::exception& exc) { + nitro::Logger::log(nitro::LogLevel::Error, "NitroModules", "Failed to install Nitro! %s", exc.what()); + _errorMessage = [NSString stringWithCString:exc.what() encoding:kCFStringEncodingUTF8]; + _didInstall = false; + } } - (NSString*)install { @@ -52,6 +60,9 @@ RCT_EXPORT_MODULE(NitroModules) // installJSIBindingsWithRuntime ran successfully. return nil; } else { + if (_errorMessage != nil) { + return _errorMessage; + } return @"installJSIBindingsWithRuntime: was not called - JSI Bindings could not be installed!"; } } diff --git a/packages/react-native-nitro-modules/src/globals.d.ts b/packages/react-native-nitro-modules/src/globals.d.ts new file mode 100644 index 000000000..2bb43deae --- /dev/null +++ b/packages/react-native-nitro-modules/src/globals.d.ts @@ -0,0 +1,29 @@ +declare global { + /** + * The native `JSICache` for Nitro. + * This is created on the fly natively when needed. + * @readonly + */ + var __nitroJsiCache: {} | undefined + /** + * The native `Dispatcher` for Nitro. + * + * A `Dispatcher` is only available in a `jsi::Runtime` when + * it was installed using `Dispatcher::installRuntimeGlobalDispatcher(...)`. + * + * If you use a `jsi::Runtime` that does not have a `Dispatcher` ({@linkcode __nitroDispatcher} `==` `null`), + * any asynchronous operations (`Callbacks` or `Promises`) will throw an error. + * You would need to either: + * - A) Install a `Dispatcher` that can safely thread-hop ("dispatch") to this `jsi::Runtime` on the native side + * - B) Only use synchronous methods and no callbacks on this `jsi::Runtime`. + * @readonly + */ + var __nitroDispatcher: {} | undefined + /** + * The global proxy object that can create other autolinked HybridObjects. + */ + var NitroModulesProxy: {} | undefined +} + +// ensures this file is treated as a module +export {} diff --git a/packages/react-native-nitro-modules/src/turbomodule/NativeNitroModules.ts b/packages/react-native-nitro-modules/src/turbomodule/NativeNitroModules.ts index 650769dba..a5e1a1bc5 100644 --- a/packages/react-native-nitro-modules/src/turbomodule/NativeNitroModules.ts +++ b/packages/react-native-nitro-modules/src/turbomodule/NativeNitroModules.ts @@ -47,32 +47,8 @@ if (__DEV__) { } } -// Freeze the globals we need -if (__DEV__) { - function protectGlobal(key: keyof typeof globalThis): void { - const value = globalThis[key] - if (value == null) return - Object.freeze(value) - Object.defineProperty(globalThis, key, { - value: value, - writable: false, - configurable: false, - }) - } - - protectGlobal('__nitroDispatcher') - protectGlobal('__nitroModulesJSICache') - protectGlobal('NitroModulesProxy') -} - -declare global { - var __nitroModulesJSICache: {} - var __nitroDispatcher: {} - var NitroModulesProxy: {} -} - export function isRuntimeAlive() { - const cache = globalThis.__nitroModulesJSICache + const cache = globalThis.__nitroJsiCache const dispatcher = globalThis.__nitroDispatcher return cache != null && dispatcher != null }