Bare Kit
Showing every release, with badges on the differences.
Reference for Bare Kit and its bindings: the Worklet API of react-native-bare-kit, bare-kit-swift, bare-kit-kotlin, and bare-kit-python for running an isolated Bare thread inside a native app, the IPC channel between host and worklet, and the C library underneath.
Bare Kit embeds Bare in native applications. It is a C library that runs each JavaScript entry point on a thread of its own, called a worklet, with an in-process IPC channel between the host app and the worklet. Bindings for several languages build on it:
react-native-bare-kit, for React Native and Expo, is documented under Worklet.bare-kit-swift, for iOS and macOS, is documented under Swift.bare-kit-kotlin, for Android and the JVM, is documented under Kotlin.bare-kit-python, for Python on Linux, macOS, and Windows, is documented under Python.
For the architecture this enables, see One core, many platforms.
A worklet is an isolated Bare thread managed by the host app. The name avoids confusion with the worker threads of bare-worker.
From react-native-bare-kit 0.17.0, the package does not include Bare Kit. The app brings Bare Kit itself, through bare-kit-swift on iOS and bare-kit-kotlin on Android, along with the addons and assets of its worklets, so that other code in the app, such as a notification service extension, can share them. See Linking addons and assets.
Worklet
The React Native API. A worklet runs a Bare entry script on a background thread. Create one, start it with an entry filename and source, and manage its lifecycle.
Constructor
new Worklet([options])— create a worklet.new Worklet(id[, options])New in 0.10.5— create a worklet under a stringid. When a worklet with anidstarts, any earlier worklet holding the sameidis terminated, so at most one live worklet owns anid.idmust be a string.
options is an object with an optional memoryLimit, the memory limit in bytes of each JavaScript heap in the worklet, where 0, the default, infers the limit from the physical memory of the device.
- Removed in 0.17.0
options.assets— earlier versions took a string, the directory that assets bundled with the worklet were unpacked into. From 0.17.0, assets ship with the app as resources instead. See Loading a bundle.
The constructor throws if the app does not include Bare Kit, with an error that names bare-kit-swift and bare-kit-kotlin. On Android, it also throws if it cannot find the application context, which the package records at startup through a content provider, to.holepunch.bare.kit.react.BareKitProvider, that its manifest declares. New in 0.17.0
Actions
start(filename[, args]),start(filename, source[, args])— start the worklet runningsourceasfilename.sourceis a string or aUint8Array. Withoutsource, the worklet readsfilenameitself.argsis an array of strings that becomesBare.argvinside the worklet as it is, so unlike on a desktop it holds no executable path and no entry path. A worklet can be started once, and starting it again, or starting one that has been terminated, throws. New in 0.17.0 A relativefilenamenames a resource of the app, as Loading a bundle describes.suspend([linger])— suspend execution, keeping the process alive for up tolingermilliseconds before it fully exits. A negative or omittedlingertakes the platform default of 30 seconds. On iOS the default, and the limit for anylinger, is the background time the OS grants the app.resume()— resume a suspended worklet.wakeup([deadline])— wake the worklet during suspension. Work may run untildeadline, after which it suspends again.deadlinedefaults to0and follows the same rules aslinger: a negative value takes the platform default, and on iOS a longer value is shortened to the background time the OS grants.update([state])— apply a host app-lifecycle state (React Native'sAppStateStatus) to the worklet:'active'resumes it,'background'suspends it, and any other state does nothing.statedefaults toAppState.currentState. React Native already forwards app-state changes to every started worklet, andstart()applies the current state once the worklet is running, so a worklet started while the app is in the background is suspended straight away. You rarely need to call this yourself.terminate()— terminate the worklet and destroy its IPC. Calling it on a terminated worklet does nothing.wait()New in 0.17.1— return a promise that resolves with the exit code of the worklet once it has exited, on its own or afterterminate(). For a worklet that has already exited, the promise resolves straight away. For a worklet that was never started, it never resolves.
suspend(), resume(), and wakeup() throw if the worklet has not been started or has been terminated, as does update() when it ends up resuming or suspending.
In react-native-bare-kit 0.15.6 through 0.17.1, start(filename) with no second argument throws a TypeError, although the type declarations allow it, because an omitted source is undefined, which the argument check rejects. To start from filename alone, pass an empty args array: worklet.start('/app.js', []).
suspend, resume, wakeup, and update are also available as static methods (Worklet.suspend(), etc.), driving every started worklet the host manages at once rather than one instance.
In react-native-bare-kit 0.15.6 and 0.16.0, the static Worklet.wakeup() calls worklet.deadline(...), which doesn't exist, so it throws a TypeError when any started worklet has not been terminated. Call wakeup() on each worklet instead. 0.17.0 fixed this.
Properties
worklet.IPC— the IPC channel to the worklet, astreamxDuplexstream with aworkletproperty pointing back at it.worklet.started,worklet.terminated,worklet.suspendedTyped in 0.17.1— booleans for the lifecycle state.startedistrueoncestart()has succeeded.suspendedistruefromsuspend()untilresume().terminatedistrueonceterminate()is called and, from 0.17.1, once the worklet has exited on its own. Earlier versions have the same getters in the JavaScript but not in the type declarations.
Events
Worklet is an event emitter, and each event mirrors the same event on Bare inside the worklet, as described under Lifecycle methods.
suspend—(linger), the worklet is suspending.wakeup—(deadline), the worklet woke up during suspension.idle—(), the worklet has gone idle. New in 0.14.0resume—(), the worklet resumed.exit—(code), the worklet has exited, on its own or afterterminate(), with its exit code. When it exits on its own, the IPC first emits the data that the worklet wrote and then ends. New in 0.17.1- Removed in 0.14.0
startandterminate— earlier versions emitted these as well. Checkworklet.startedandworklet.terminatedinstead.
Example
import { Worklet } from 'react-native-bare-kit'
import b4a from 'b4a'
const worklet = new Worklet()
const source = `
Bare.IPC.on('data', (data) => console.log(data.toString()))
Bare.IPC.write(Buffer.from('Hello from Bare!'))
`
worklet.start('/app.js', source)
const { IPC } = worklet
IPC.on('data', (data) => console.log(b4a.toString(data)))
IPC.write(b4a.from('Hello from React Native!'))Native bindings
The Swift, Kotlin, and Python bindings are thin layers over the C API. Bare Kit calls back on threads of its own, which the bindings turn into async calls, so you can use a worklet and its IPC from any Swift task or Kotlin coroutine, and from the asyncio event loop that started it in Python. Unlike react-native-bare-kit, they have no update() and no lifecycle events, and their wakeup() deadline defaults to -1, the platform default, rather than 0.
Swift
bare-kit-swift supports iOS 15 and macOS 13 or later, and includes Bare Kit as a framework, BareKit.framework, from its own release. Add it with Swift Package Manager and depend on its BareKit product. Linking addons and assets writes a package that does this for you.
dependencies: [
.package(url: "https://github.com/holepunchto/bare-kit-swift", from: "2.3.0")
]
.product(name: "BareKit", package: "bare-kit-swift")import BareKit
import Foundation
let worklet = try Worklet(options: .init(memoryLimit: 24 * 1024 * 1024)) // 24 MiB
let ipc = try IPC(worklet: worklet)
try worklet.start("app.bundle")
try await ipc.write(Data("Hello from Swift".utf8))
for await data in ipc {
print(String(decoding: data, as: UTF8.self))
}
ipc.close()
let code = await worklet.wait()Worklet
Worklet.Options(memoryLimit:)— the memory limit in bytes of each JavaScript heap, where0, the default, infers the limit from the physical memory of the device.init(options:) throws— create a worklet that has not started. It throwsBareKitError.failed(_:)if Bare Kit cannot create it.start(_ filename: String, source: Data? = nil, arguments: [String] = []) throws,start(_ url: URL, source:arguments:) throws— start the worklet runningfilename, withargumentsasBare.argv. TheURLform passes the path of a file URL and the full string of any other URL. Withoutsource, the worklet reads the module at runtime, so it may be a module next to itsnode_modulesrather than a bundle. A relativefilenamenames a resource of the app bundle, which app extensions share. It throwsBareKitError.failed(_:)if the worklet cannot start, for example afterteardown().suspend(linger:),resume(),wakeup(deadline:),terminate()— the lifecycle methods.lingeranddeadlineareInt32milliseconds and default to-1, the platform default.wait() async -> Int32— wait for a started worklet to exit, on its own or afterterminate(), and return its exit code.Worklet.optimizeForMemory(_:),Worklet.teardown()— the class methods for the state that the worklets of a process share. Seebare_worklet_optimize_for_memory()andbare_worklet_teardown()under C API.
Releasing a worklet terminates it, so keep a reference to it for as long as it should run.
IPC
IPC is an AsyncSequence of Data. Iterating it yields what the worklet writes to Bare.IPC, until the worklet ends its side or the IPC is closed. Data is read from the worklet only while you iterate, so a worklet that writes faster than the host iterates waits for room. Only one iterator can wait for data at a time: iteration ends early for an iterator that waits while another one already does, or whose task is cancelled while it waits.
init(worklet:) throws— open the IPC ofworklet. A worklet has one IPC, and it throwsBareKitError.failed(_:)if the worklet already has one or has been terminated.write(_ data: Data) async throws— writedatatoBare.IPCin the worklet, waiting for room as needed. It throwsBareKitError.closedif the IPC is ended or closed before all of the data is written, andBareKitError.peerClosedif the worklet closes its side first.end()— end what the host writes once the pending writes complete. The worklet then reads end-of-stream, while iteration continues. Later writes throw. Ending twice, or after closing, does nothing.close()— close the IPC, which ends iteration and makes writes throw. Closing twice does nothing.
BareKitError has three cases: failed(Int32), a call into Bare Kit that failed with that status; closed; and peerClosed.
Native addons that bare-link links are loaded by the system linker, so embed them in the app as you would any other framework.
Kotlin
bare-kit-kotlin supports Android and the JVM on Linux, macOS, and Windows, in the package to.holepunch.bare.kit. Add it from JitPack. Linking addons and assets writes a Gradle module that depends on it, but the app still needs JitPack among its repositories.
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
implementation "com.github.holepunchto.bare-kit-kotlin:bare-kit-kotlin:v0.2.3"
}import to.holepunch.bare.kit.Ipc
import to.holepunch.bare.kit.Worklet
// Inside a coroutine
val worklet = Worklet(context, Worklet.Options(memoryLimit = 24L * 1024 * 1024)) // 24 MiB
val ipc = Ipc(worklet)
worklet.start("app.bundle")
ipc.write("Hello from Kotlin".encodeToByteArray())
ipc.data.collect { data -> println(data.decodeToString()) }
ipc.close()
val code = worklet.wait()
worklet.close()Worklet implements AutoCloseable.
Worklet(context, options)on Android,Worklet(options)on the JVM— create a worklet that has not started.optionsis aWorklet.Options(memoryLimit), the memory limit in bytes of each JavaScript heap as aLong, where0, the default, infers the limit from the physical memory of the device. On Android, the application context ofcontextis handed to the native addons of the worklet underbare.android.context.v1. Both throwBareKitException.Failedif Bare Kit cannot create the worklet.start(filename, source = null, arguments = emptyList())— start the worklet runningfilename, withargumentsasBare.argv.sourceis aByteArray. Without it, the worklet readsfilenameat runtime, so it may be a module next to itsnode_modulesrather than a bundle. On Android, a relativefilenamenames an asset of the app, as Loading a bundle describes. On macOS, it names a resource of the app bundle. On Linux and Windows, pass the path of the bundle or its source. It throwsBareKitException.Failedif the worklet cannot start, for example afterteardown().suspend(linger = -1),resume(),wakeup(deadline = -1),terminate()— the lifecycle methods, withlingeranddeadlinein milliseconds, where-1is the platform default.suspend fun wait(): Int— wait for a started worklet to exit, on its own or afterterminate(), and return its exit code.close()— terminate the worklet if it is still running and release it. Closing twice does nothing. Once closed,terminate()does nothing and the other methods throwIllegalStateException.Worklet.optimizeForMemory(enabled),Worklet.teardown()— the companion functions for the state that the worklets of a process share. Seebare_worklet_optimize_for_memory()andbare_worklet_teardown()under C API.
Closing a worklet terminates it, so keep it open for as long as it should run.
Ipc implements AutoCloseable.
Ipc(worklet)— open the IPC ofworklet. A worklet has one IPC, and it throwsBareKitException.Failedif the worklet already has one or has been terminated, andIllegalStateExceptionif the worklet is closed.data— aFlow<ByteArray>of what the worklet writes toBare.IPC, until the worklet ends its side or the IPC is closed. It can be collected only once.suspend fun write(data: ByteArray)— writedatatoBare.IPCin the worklet, waiting for room as needed. It throwsBareKitException.Closedif the IPC is ended or closed before all of the data is written, andBareKitException.PeerClosedif the worklet closes its side first.end()— end what the host writes once the pending writes complete. The worklet then reads end-of-stream, whiledatakeeps collecting. Later writes throw. Ending twice, or after closing, does nothing.close()— close the IPC and release it, which ends collection and makes writes throw. Closing twice does nothing.
BareKitException is a sealed class with three subclasses: Failed, whose status is the status that a call into Bare Kit failed with; Closed; and PeerClosed.
On Android, include native addons that bare-link links in the jniLibs of the app, where the system linker loads them. On the JVM, the library includes Bare Kit for Linux, macOS, and Windows on arm64 and x64, and extracts it to a temporary file when first used. On other platforms it loads bare-kit from java.library.path instead.
Python
bare-kit-python supports Python 3.10 or later on Linux, macOS, and Windows, on arm64 and x64. Its wheels include Bare Kit for the platform they are for: macOS 13 or later, Linux with glibc 2.34 or later, and Windows. Install it from PyPI, where the package is named bare-kit and the module bare_kit:
pip install bare-kitimport asyncio
from pathlib import Path
from bare_kit import start
async def main():
async with await start(Path(__file__).parent / "app.bundle") as worklet:
await worklet.write(b"Hello from Python")
async for data in worklet:
print(data.decode())
code = await worklet.wait()
asyncio.run(main())Unlike the Swift and Kotlin bindings, a Python worklet and its IPC are one object.
await start(filename, *args, source=None, memory_limit=0)— create a worklet, open its IPC, start it runningfilenamewithargsasBare.argv, and return theWorklet.sourceisbytes. Without it, the worklet readsfilenameat runtime, so it may be a module next to itsnode_modulesrather than a bundle, and its native addons load from there.memory_limitis the memory limit in bytes of each JavaScript heap, where0infers the limit from the physical memory of the device. It raisesBareKitErrorif Bare Kit cannot create or start the worklet, for example afterteardown(). Call it from the event loop that will use the worklet, which Bare Kit's callbacks are handed to.async for data in worklet,await worklet.read(n=65536)— thebytesthat the worklet writes toBare.IPC, until the worklet ends its side.read()returnsb""then. Reading to the end closes the IPC, so that the worklet can exit.await worklet.write(data)— writedatatoBare.IPCin the worklet and wait for it to drain. It raisesBrokenPipeErrorif the IPC is ended or closed before all of the data is written, including by reading to the end, or if the worklet closes its side first.worklet.end()— end what the host writes once the pending writes drain. The worklet then reads end-of-stream, while reading continues. Ending twice does nothing.suspend(linger=-1),resume(),wakeup(deadline=-1),terminate()— the lifecycle methods, withlingeranddeadlinein milliseconds, where-1is the platform default.await worklet.wait()— wait for the worklet to exit and return its exit code.worklet.exit_codeis the exit code, orNonewhile the worklet runs.await worklet.close(),async with— close the IPC, terminate the worklet if it is still running, and wait for it to exit. Closing twice does nothing. Once closed,terminate()does nothing, andsuspend(),resume(), andwakeup()raiseValueError.optimize_for_memory(enabled),teardown()— the module functions for the state that the worklets of a process share. Seebare_worklet_optimize_for_memory()andbare_worklet_teardown()under C API.
Closing a worklet terminates it, so keep it open for as long as it should run.
BareKitError is raised when a call into Bare Kit fails, with the failing status as status.
The bare-kit target of bare-stow writes no Python package. To run a bundle in a separate Bare process from Python instead of a thread, use bare-sidecar-python.
Bare Kit 2 bindings
bare-kit 2.x shipped its own Objective-C binding (BareWorklet, BareWorkletConfiguration, and BareIPC in apple/BareKit/BareKit.h) and Java binding (Worklet and IPC in to.holepunch.bare.kit), with a polling IPC API. bare-kit 3.0.0 removed both from the repository in favor of bare-kit-swift and bare-kit-kotlin. It also removed push, the one-off request from the host that the worklet answered from a push listener on the BareKit global, along with the assets option. Send requests over the IPC instead, for example with bare-rpc.
IPC
Bare Kit provides an IPC channel between the host app and a worklet. From bare-kit 3.0.0 the channel is an in-process queue rather than a pipe. Inside the worklet it is Bare.IPC, a duplex stream. On the host it depends on the binding.
- Removed in 0.17.0 The
BareKitglobal— earlier versions also exposed the channel inside the worklet asBareKit.IPC, the same object asBare.IPC. UseBare.IPC, which works in every version.
An open IPC keeps the worklet running until both the worklet and the host have ended their side of it, just like a pipe would. Ending a side is a half-close: the other side reads the end of the stream but can keep writing. Inside the worklet, call Bare.IPC.end(). While the worklet is suspended, Bare.IPC does not keep it running. A write to Bare.IPC after the host has closed the channel fails with an error whose code is IPC_CLOSED.
React Native. worklet.IPC is a streamx Duplex stream, so use it as one: listen for data, call write(), and destroy() it. Writes queue behind a slow worklet instead of being partial. It opens when the worklet starts, so you can write before calling start() and the writes wait until the worklet is running. It is destroyed along with the worklet.
end() half-closes the host side, so the worklet reads the end of the stream. New in 0.17.0 From 0.17.1, when the worklet exits on its own, the stream emits what the worklet wrote and then ends, and writes that are pending or come later fail with IPC has been closed. New in 0.17.1
Swift, Kotlin, and Python. IPC, Ipc, and the Python Worklet offer async writes, an async sequence, flow, or iterator of reads, end(), and close(), as Swift, Kotlin, and Python describe.
C. bare_ipc_read() and bare_ipc_write() never block, and a poll calls the host back when the channel becomes readable or writable. See the IPC functions under C API.
For typed, schema-generated messaging over this channel instead of raw bytes, layer bare-rpc on top—see Type a native RPC bridge.
C API
Bare Kit is a C library declared in include/bare-kit.h. Use it to host worklets from your own C or C++ code. Functions that return an int return 0 on success and a negative value on failure, except where noted.
Worklet
struct bare_worklet_options_s {
int version;
size_t memory_limit;
union {
struct {
void *jvm;
void *context;
} android;
void *reserved[8];
} platform;
};version is the version of the struct, 0. memory_limit is the memory limit of each JavaScript heap in bytes, applied to each thread individually, the main thread included. By default it is inferred from the physical memory of the device.
platform holds the options of one platform, and only the member of the platform that the worklet runs on is read. On Android, jvm is the JavaVM *, which addons read under bare.android.jvm.v1. It defaults to the virtual machine that loaded Bare Kit through JNI_OnLoad(), so pass it if Bare Kit is loaded by other means. context is a JNI reference to an android.content.Context, which addons read under bare.android.context.v1. The worklet takes a global reference of its own, so the reference you pass needs to be valid only for the call. A relative filename on Android needs context.
bare_worklet_optimize_for_memory(bool enabled)— trade performance for memory. Configure it before the first worklet starts.bare_worklet_teardown(void)— tear down the state that the worklets of the process share, a single JavaScript platform. Terminate or destroy every worklet first: the call waits for the ones still tearing down. Call it at most once, after which no worklet can start. A host that runs worklets for as long as it lives does not need to call it.bare_worklet_create(const bare_worklet_options_t *options, bare_worklet_t **result)— create a worklet.optionsis copied and may beNULL. On Android, the calling thread must be attached to the JVM ifoptionsgives acontext.bare_worklet_destroy(bare_worklet_t *worklet)— terminate the worklet if it is still running and hand it over to tear itself down. It never blocks. Don't use the worklet afterwards. Its IPC may be destroyed before or after it.bare_worklet_start(bare_worklet_t *worklet, const char *filename, const void *source, size_t len, int argc, const char *argv[])— start the worklet on a thread of its own, runningfilenamewithargvasBare.argv. IfsourceisNULL, the worklet readsfilenameat runtime. The arguments need to be valid only until the call returns. A relativefilenamenames a resource of the app, as Loading a bundle describes. It fails afterbare_worklet_teardown().bare_worklet_suspend(worklet, int linger),bare_worklet_resume(worklet),bare_worklet_wakeup(worklet, int deadline),bare_worklet_terminate(worklet)— the lifecycle, which the worklet observes as thesuspend,resume, andwakeupevents ofBare. They are safe to call from any thread, and do nothing if the worklet has not started or has torn down. A negativelingerlingers for 30 seconds. On iOS the worklet holds a background task for as long as it lingers, solingeris capped by the background time remaining to the app, which a negativelingerlingers for instead.deadlinefollows the same rules.bare_worklet_resume()cancels a suspension that has not yet gone idle.bare_worklet_terminate()terminates the worklet as soon as possible.bare_worklet_on_suspend(),bare_worklet_on_wakeup(),bare_worklet_on_idle(),bare_worklet_on_resume(),bare_worklet_on_exit()—(worklet, cb, data), set the listener for the matching event. Set them before you start the worklet. They are called on the worklet thread asbare_worklet_suspend_cb(int linger, void *data),bare_worklet_wakeup_cb(int deadline, void *data),bare_worklet_idle_cb(void *data),bare_worklet_resume_cb(void *data), andbare_worklet_exit_cb(int exit_code, void *data).bare_worklet_get_data(worklet),bare_worklet_set_data(worklet, void *data)— a pointer of your own to keep on the worklet, which the worklet does not use.
A worklet exits when its event loop runs out of work, when it calls Bare.exit(), or when the host terminates it. Once it has exited and torn down, the exit callback is called exactly once with the exit code, also when the host destroyed a running worklet, so keep its data until then and release what the host associated with the worklet there. By then any IPC of the worklet has reached the end of the stream, and the lifecycle functions do nothing.
IPC
bare_ipc_create(bare_worklet_t *worklet, bare_ipc_t **result)— create the host end of the IPC of a worklet, which the worklet sees asBare.IPC. It fails if the worklet already has an IPC or has been terminated.bare_ipc_end(bare_ipc_t *ipc)— end the host side, a half-close after whichBare.IPCreads the end of the stream once drained, while the host keeps reading. Writes fail afterwards. Ending twice, or after closing, does nothing.bare_ipc_close(bare_ipc_t *ipc)— close the host end, after which reads return the end of the stream and writes fail. Closing twice does nothing.bare_ipc_destroy(bare_ipc_t *ipc)— close and free the IPC. It may be called before or afterbare_worklet_destroy(), and from a poll callback of the IPC itself.bare_ipc_read(bare_ipc_t *ipc, void *data, size_t len)— read up tolenbytes, which must not be0, intodata. It returns the number of bytes read,0at the end of the stream, orbare_ipc_would_block(-1) when there is nothing to read.BARE_IPC_READ_BUFFER_SIZE(64 KiB) is a buffer size to read with.bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len)— write up tolenbytes fromdata. It returns the number of bytes written, which may be fewer thanlen,bare_ipc_would_blockwhen there is no room, orbare_ipc_error(-2) once the IPC is closed.bare_ipc_poll_create(bare_ipc_t *ipc, bare_ipc_poll_t **result),bare_ipc_poll_destroy(poll)— create a poll of the IPC, and stop and free it. If the callback of the poll is running on another thread,bare_ipc_poll_destroy()waits for it to return. It may be called from the callback itself.bare_ipc_poll_start(poll, int events, bare_ipc_poll_cb cb),bare_ipc_poll_stop(poll)— callcb(poll, events)when the IPC becomes readable or writable.eventsisbare_ipc_readable,bare_ipc_writable, or both ORed. Starting a started poll replaces its events and callback, and starting it with noeventsstops it. Polls are level-triggered, so the callback is called again for as long as the events remain ready.bare_ipc_poll_get_ipc(poll),bare_ipc_poll_get_data(poll),bare_ipc_poll_set_data(poll, void *data)— return the IPC of the poll, and keep a pointer of your own on it.
Poll callbacks run on a thread that the IPC owns, not on the thread that started the poll, on every platform. On Android that thread is attached to the JVM. A callback may stop or destroy its poll, or the IPC itself.
Addons
The native addons of a worklet resolve the symbols of Bare from the host process. This works as is when the host links or loads Bare Kit as a shared library, as bare-kit-swift and bare-kit-kotlin do. Otherwise:
- A host that links Bare Kit statically into an executable must export its symbols, for example with
ENABLE_EXPORTSand, on Windows,WINDOWS_EXPORT_ALL_SYMBOLSin CMake. - A host that links Bare Kit statically into a shared library must keep its symbols exported, and on Android must also link with
-z global. From bare-kit 3.0.1, linking thebare::kit::exportsCMake target into the library exports the functions of Bare Kit and the symbols of Bare that addons need, and nothing else.
Addons may bind to the wrong symbols if the process already exports libuv, V8, or Node-API, as Node.js and Electron do, or holds more than one copy of Bare Kit.
Changes from bare-kit 2
bare-kit 3.0.0 replaced the API of shared/worklet.h and shared/ipc.h. bare_worklet_create(), bare_ipc_create(), and bare_ipc_poll_create() replace the _alloc() and _init() pairs. bare_worklet_start() takes the source as a pointer and a length instead of a uv_buf_t. bare_ipc_read() copies into a buffer of the caller instead of returning a pointer to one that the IPC owns. The lifecycle callbacks take the value and data rather than the Bare listener types. bare_worklet_on_exit(), bare_worklet_teardown(), bare_ipc_end(), and bare_ipc_close() are new. The assets option, bare_worklet_push() and its request functions, and bare_ipc_get_incoming() and bare_ipc_get_outgoing() are gone.
Loading a bundle
Instead of inline source, a worklet can start from a bundle produced by bare-pack. The entry filename's extension must be .bundle:
import { Worklet } from 'react-native-bare-kit'
import bundle from './my.bundle.js' // output by bare-pack
const worklet = new Worklet()
worklet.start('/app.bundle', bundle)See Bundle a Bare app for producing the bundle.
From bare-kit 3.0.0 and react-native-bare-kit 0.17.0, a relative filename names a resource of the app, so that a bundle and the assets it references ship with the app: New in 0.17.0
- On iOS and macOS, it resolves against the resources of the app bundle, which app extensions share.
- On Android, it resolves against the code cache directory of the app. Before
<name>.bundlefirst runs, the resources listed in<name>.assets, one/<path>per line, are extracted there from<name>/<path>in the assets of the APK, and a bundle started withoutsourceis read from the APK.
For example, these resources in the APK let app.bundle reference an asset of a dependency:
app.bundle
app.assets
app/node_modules/a/asset.txtbare-stow lays out the resources of the worklets it links this way under the name bare-stow: bare-stow link writes bare-stow.assets and the bare-stow folder, as Linking addons and assets describes, and a worklet packed by bare-stow pack starts as bare-stow.bundle, with the bundle as its source.
From 0.17.0, you can also pack a worker and its dependencies into a package with bare-stow and its React Native target, bare-stow-target-react-native. The worker exports a function that receives the IPC stream:
module.exports = function start(ipc) {
ipc.on('data', (data) => ipc.write(data))
}bare-stow pack --target react-native --out ./worker worker.jsAdd the package as a dependency of the app and start the worker, which runs in a worklet:
import worker from 'worker'
const { ipc } = await worker.start()
ipc.on('data', (data) => console.log(b4a.toString(data)))
ipc.write(b4a.from('Hello from React Native!'))The package leaves out the addons and assets of the worker, so link them as the next section describes. In an Expo app, list the workers in the workers option of expo-bare-kit instead, which packs them whenever Metro bundles the app.
If the bundle carries assets and the worklet was created with an assets directory, the worklet unpacks the assets into a subdirectory of it, named after a hash of the bundle's id. It does so once, and reuses the directory on later starts.
If the bundle loads native addons, link them into your app as well, as Linking addons and assets describes.
Linking addons and assets
From 0.17.0, the app brings Bare Kit and the native addons and assets of all of its worklets. Link them once with bare-stow, passing the entry point of every worklet. It writes a Swift package and a Gradle module, which also depend on bare-kit-swift and bare-kit-kotlin: New in 0.17.0
bare-stow link --target bare-kit --language swift --out ios/BareKitResources worklet.js
bare-stow link --target bare-kit --language kotlin --language-option package=com.example.addons --out android/bare-kit-resources worklet.jsAdd the Swift package and its bare-stow folder to the app target, and include the Gradle module in the app. In an Expo app, list the workers in the workers option of expo-bare-kit instead. Without Bare Kit in the app, new Worklet() throws.
0.17.0 also stopped building the ios/addons and android/src/main/addons directories of the package into the app, so addons that you linked there with an earlier version are no longer included.
react-native-bare-kit does not link the native addons that a worklet loads. Releases from 0.3.1 through 0.15.6 ran bare-link themselves, from the podspec on iOS and from a Gradle task before each Android build. Version 0.16.0 removed both steps along with its dependency on bare-link, so an app links its own addons.
Run bare-link with the entry point of the worklet, the file that you pack into the bundle. It links the addons that the module graph of that entry point loads, for the hosts that a preset selects:
bare-link --preset ios --out ios/addons worklet.js
bare-link --preset android --out android/app/src/main/jniLibs worklet.jsHere ios/addons and android/app/src/main/jniLibs are directories of your own app project. The ios preset targets ios-arm64, ios-arm64-simulator, and ios-x64-simulator. The android preset targets android-arm, android-arm64, android-ia32, and android-x64. On iOS the output is one .xcframework bundle per addon, which you embed in the app target. On Android it is one .so library per addon and ABI, in a directory named for the ABI, which belongs in the jniLibs of the app, and you add any .jar library that an addon ships as a dependency. Pack the worklet with bare-pack --linked so that addons resolve to the linked libraries, as Bundle a Bare app describes.
The native projects of the library also already include two directories in the build, without further configuration: any .xcframework bundle in its ios/addons directory, and any .so or .jar library in its android/src/main/addons directory. The package does not ship these directories, and bare-link creates them. Point --out at them to link without changing your own native projects:
bare-link --preset ios --out node_modules/react-native-bare-kit/ios/addons worklet.js
bare-link --preset android --out node_modules/react-native-bare-kit/android/src/main/addons worklet.jsThese directories are inside node_modules, so reinstalling the library clears them. Run the commands from a postinstall script of the app to restore them:
{
"scripts": {
"postinstall": "npm run link:ios && npm run link:android",
"link:ios": "bare-link --preset ios --out node_modules/react-native-bare-kit/ios/addons worklet.js",
"link:android": "bare-link --preset android --out node_modules/react-native-bare-kit/android/src/main/addons worklet.js"
},
"devDependencies": {
"bare-link": "^4.0.1"
}
}Bundled Bare version
A worklet runs the Bare that Bare Kit embeds, not the Bare installed on your machine. Bare features added after that version are not available in a worklet until a Bare Kit release embeds a newer Bare.
| Bare Kit | Embeds Bare | Built by |
|---|---|---|
| 3.1.0 | 1.37.1 | bare-kit-swift 2.3.0, bare-kit-kotlin 0.2.3, bare-kit-python 0.2.1 |
| 3.0.1 | 1.36.2 | bare-kit-swift 2.0.0 to 2.2.0, bare-kit-kotlin 0.1.2 to 0.2.2, bare-kit-python 0.1.0 to 0.2.0 |
| 3.0.0 | 1.36.1 | |
| 2.5.4, 2.5.5 | 1.33.4 | react-native-bare-kit 0.15.5 to 0.16.0 |
From Bare Kit 3.1.0, iOS apps need the entitlement that iOS entitlement describes. bare-stow 0.2.0 through 0.3.6 linked bare-kit-swift with a from: requirement, from: "2.0.0" in 0.2.0 and from: "2.2.0" after it, which Swift Package Manager resolves to any later 2.x release. A package update therefore brings an app they linked onto bare-kit-swift 2.3.0 and Bare Kit 3.1.0 without a new bare-stow. They linked one bare-kit-kotlin release exactly: v0.1.1 in 0.2.0, v0.2.3 in 0.3.4, and v0.2.2 in the others.
From 0.17.0, react-native-bare-kit includes no Bare Kit, so the Bare version depends on the bare-kit-swift and bare-kit-kotlin releases in the app. bare-stow 0.3.7 links bare-kit-swift 2.3.0 or a later 2.x release, and the latest 0.2.x release of bare-kit-kotlin.
The react-native-bare-kit package contains prebuilt bare-kit libraries for iOS and Android, which its CMakeLists.txt fetches from a fixed bare-kit release when the package is published. Versions 0.15.5 through 0.16.0 use the bare-kit 2.5.4 prebuilds, and bare-kit 2.5.4 and 2.5.5 both embed Bare 1.33.4, so a worklet in any of them runs Bare 1.33.4.
iOS entitlement
From Bare Kit 3.1.0, which embeds Bare 1.37.1, an iOS app that runs worklets must be signed with the com.apple.developer.kernel.extended-virtual-addressing entitlement. This applies to bare-kit-swift 2.3.0 and later, and so to a react-native-bare-kit app that links them. When V8 starts, it reserves a large region of virtual memory for pointer compression and for the heap of its C++ garbage collector. On iOS that is more than the default address space of an app, so without the entitlement the app aborts on a device with this fatal error:
Failed to reserve virtual memory for process-wide V8 pointer compression cageAdd the entitlement to the entitlements file of the app target:
<key>com.apple.developer.kernel.extended-virtual-addressing</key>
<true/>In Xcode, the Extended Virtual Addressing capability under Signing & Capabilities of the target adds it for you, and with automatic signing also enables it for the App ID. Entitlements belong to the binary they are signed into, so an app extension that runs worklets, such as a notification service extension, starts V8 in a process of its own under its own entitlements. The upstream sources don't say whether an extension needs the entitlement as well, so test an extension on a device. The macOS builds don't need it.
Error handling
A worklet runs as a thread inside the host process, so it follows Bare's default handling of uncaught errors: an uncaught exception or unhandled promise rejection in worklet JavaScript is printed and the process is aborted. Because the worklet shares the host's process, this takes the host down with it. This is by design.
To keep a worklet error from aborting the host, register an uncaughtException and an unhandledRejection listener inside the worklet. Adding a listener overrides the default abort and lets the worklet decide how to respond, for example by reporting the error to the host before it exits:
Bare.on('uncaughtException', (err) => {
Bare.IPC.write(String(err))
Bare.exit(1)
})The handler runs inside the worklet, not in the host, so the host cannot catch a worklet exception directly. Surface it yourself, for example over IPC as above. The host sees the exit code through wait() in the Swift, Kotlin, and Python bindings, and through wait() and the exit event from react-native-bare-kit 0.17.1. See the uncaughtException and unhandledRejection events.
Logging
console.* calls inside the worklet write to the system log (via liblog) under the bare identifier, so worklet output shows up in the platform's native logging tools.
See also
- One core, many platforms—the shell/seam/core pattern this enables.
- Embed Bare in a React Native app—a step-by-step walkthrough.
- Bare runtime API—the
Bareglobal and lifecycle the worklet runs. - Embedder context—the keys that Bare Kit publishes to native addons.
- Bare modules—
bare-rpc,bare-pack,bare-stow, and the rest of the userland.
Last updated on