react-nitro-runtime
v0.0.1-alpha.17
Published
The iOS JavaScript runtime and JavaScript environment for React Nitro. Add this directory as a local Swift package and link the `ReactNitroRuntime` product.
Readme
react-nitro-runtime
The iOS JavaScript runtime and JavaScript environment for React Nitro. Add this directory as a local Swift package and link the ReactNitroRuntime product.
In your JavaScript entry point, install the runtime globals before importing application code:
import 'react-nitro-runtime'Importing the runtime installs performance, timers, animation-frame callbacks, native console logging, URL, URLSearchParams, fetch, and microtasks. The import also loads TypeScript declarations for those globals. On iOS and Android, the URL globals use Ada through shared C++ Nitro bindings. Global installation and console argument formatting are internal to the package.
For application TypeScript configs, use "lib": ["ESNext"] and "types": [] to exclude browser and automatically included Node/Bun globals. In this repository, extend config/tsconfig.hermes.json; keep build tools in a separate TypeScript project with their own environment types.
The declarations describe the APIs currently installed by the runtime:
ReadableStreamfor consuming streams and checking response body types.performance.now()andperformance.timeOrigin.console.log,debug,info,warn,error, andassert.URLandURLSearchParamsfor resolving relative URLs and reading or editing query parameters.URL.canParse()andURL.parse()support validation without exceptions.fetch(url, options?)accepts a string or URL, request headers and an HTTP method with a text, binary, URL-encoded, or multipart body. See the networking package for supported inputs.response.headers.get(name)looks up headers case-insensitively. Clone an unread response to consume it independently. Each response reads its body once throughjson(),text()orarrayBuffer(). The clones share the lazy native byte storage.- Pass an
AbortSignalfrom the runtime, a browser, or a compatible polyfill tofetch(url, { signal }). Aborting rejects pending fetches and body reads with the signal’s reason, including reads on response clones. If a Blob is still preparing, aborting prevents the upload. UseAbortSignal.timeout(ms)to set a deadline. Headersaccepts an existingHeaders, a polyfill withgetandforEach, a string record or name/value pairs. You can set, append, delete and iterate request headers. Response headers are read-only. Useresponse.headers.getSetCookie()to read individual cookies.setTimeoutandsetIntervalwith a callback and a required delay in milliseconds, returning numeric IDs;clearTimeoutandclearIntervalaccept those IDs.requestAnimationFrame,cancelAnimationFrame, andqueueMicrotask.
Do not add DOM, @types/node, or @types/bun to the application's environment: they advertise APIs that Hermes does not provide. Importing the runtime does not remove declarations loaded by other dependencies. Run bun run typecheck from the repository root to check the app and runtime packages.
import ReactNitroRuntime
// Keep the runtime alive for as long as the app uses JavaScript.
@MainActor
final class Application {
private let runtime = JSRuntime()
func start() throws {
let url = Bundle.main.bundleURL.appendingPathComponent("main.js")
let result = try runtime.runJavaScript(fromFileURL: url, sourceURL: url)
print(result)
}
}Include the JavaScript file in the consuming app's resources. Loading and execution errors are thrown to Swift; successful results are stringified as before.
Hermes reads fileURL and uses sourceURL in error stacks. For a downloaded script, pass its local file and its original URL.
For separate preparation and execution, use try runtime.prepareJavaScript(fromFile:) and try runtime.runPreparedJavaScript(preparedJavaScript:). prepareJavaScript(fromFile:) resolves files relative to Bundle.main by default; pass JSRuntime(bundle: ...) to load resources from another bundle. Keep memory-mapped source files unchanged while prepared JavaScript is alive.
ReactNitroRuntimeCxx owns Hermes, memory-mapped file loading, Nitro installation, and registration of the core, networking, and renderer HybridObjects. ReactNitroRuntime provides the main-actor Swift API and bundle path resolution. Registration currently lists core, networking, and renderer explicitly; it is not generated automatically.
The app no longer needs a bridging header. Consuming Swift targets still need C++ interoperability enabled (SWIFT_OBJC_INTEROP_MODE = objcxx in Xcode or .interoperabilityMode(.Cxx) in SwiftPM), as required by Swift's mixed-language package setup. Apps using RegisterRootCallback in their scene delegate should also link ReactNitroRenderer.
Our Swift targets use -Xfrontend -clang-header-expose-decls=has-expose-attr-or-stdlib to export declarations to C++ only when annotated with @_expose(Cxx), while preserving standard-library wrappers such as swift::String. Annotating a type also exports its public members. Nitrogen annotates the generated bridge wrappers and helpers for constructors and static methods; Swift application APIs can stay public without being exported. This uses a hidden compiler flag and an underscored attribute.
Android runtime
The standalone Android library builds the pinned Hermes, the selected layout engine, Nitro Core, and generated bindings without React Native. It includes the native clock, logging, timers, animation frames, microtasks, fetch, and WebSockets. JavaScript runs on the main Looper; the clock, logging, and layout bindings stay in C++.
Install JavaScript dependencies, initialize the Git submodules with
git submodule update --init --recursive, and use JDK 17,
Android SDK 36, NDK 29.0.14206865, CMake 3.22.1, Ninja, Python 3, and Bun. From
apps/React Nitro Example/android, build the library with:
./gradlew :runtime:assembleDebugThe default ABIs are arm64-v8a and x86_64. Use
-PreactNitroAbis=arm64-v8a to build only that architecture. JSRuntime evaluates
a JavaScript file and must be accessed and closed on the main Looper.
Subclass com.margelo.reactnitro.runtime.NitroActivity to host the application.
Its bundleAsset defaults to main.js; use Application.registerRoot in the JS
entry point. A retained session preserves Hermes, React state, views, and scroll
positions across Activity recreation and rebuilds their Fragment hosts. Process
death starts a new session. Work destined for JavaScript waits while the host is
detached. Reloading or ending the session closes its native resources.
The example application bundles its JavaScript and image assets through Gradle.
./gradlew :app:assembleRelease links the natively compiled React framework
into libReactNitroRuntime.so and packages the app components as Hermes
bytecode. Imported PNG and JPEG variants become native bitmap resources;
SVGs are converted to native VectorDrawable resources at build time. The same JS
entry point runs on iOS and Android.
