### Worklet start with inline source example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/android-worklet.md Basic example of starting a worklet with inline source code. Uses the start(String, String, Charset, String[]) overload with UTF-8 charset and null arguments. ```java import to.holepunch.bare.kit.Worklet; import java.nio.charset.StandardCharsets; Worklet worklet = new Worklet(new Worklet.Options().memoryLimit(24 * 1024 * 1024)); String source = "console.log('hello from the worklet')"; worklet.start("/app.js", source, StandardCharsets.UTF_8, null); ``` -------------------------------- ### Basic IPC creation example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/android-ipc.md Basic example of creating an IPC instance. Creates a Worklet, starts it with a script, and then constructs an IPC on that worklet. ```java import to.holepunch.bare.kit.Worklet; import to.holepunch.bare.kit.IPC; Worklet worklet = new Worklet(new Worklet.Options()); worklet.start("/app.js", "console.log('ready')", StandardCharsets.UTF_8, null); IPC ipc = new IPC(worklet); ``` -------------------------------- ### BareWorklet basic initialization example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Basic example of creating a BareWorklet with a custom configuration. Sets a 24 MiB memory limit and the assets directory to the home directory, then initializes the worklet. The worklet is not started yet. ```objc #import BareWorkletConfiguration *options = [BareWorkletConfiguration defaultWorkletConfiguration]; options.memoryLimit = 1024 * 1024 * 24; // 24 MiB options.assets = NSHomeDirectory(); // where worklet assets may be unpacked BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:options]; ``` -------------------------------- ### Install bare-make and dependencies Source: https://github.com/holepunchto/bare-kit/blob/main/CONTRIBUTING.md Install bare-make globally, then install project dependencies. ```bash npm i -g bare-make ``` ```bash npm i ``` -------------------------------- ### Raw C usage of bare_worklet API Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-worklet.md Complete C example showing how to initialize, start, push messages to, and terminate a Bare worklet using the raw C API. Includes error handling for init, start, and push operations, and uses uv_sleep to allow the worklet to run before termination. ```c #include #include #include "shared/worklet.h" static void on_push(bare_worklet_push_t *req, const char *error, const uv_buf_t *reply) { if (error) fprintf(stderr, "push error: %s\n", error); if (reply) fwrite(reply->base, 1, reply->len, stdout); } int main(void) { bare_worklet_t w; bare_worklet_options_t options = { .memory_limit = 0, /* infer from physical memory */ .assets = NULL, /* no asset directory */ }; if (bare_worklet_init(&w, &options) != 0) return 1; const char *argv[] = { "label" }; const char *source = "console.log('hi')"; if (bare_worklet_start(&w, "/app.js", &(uv_buf_t){ .base = (char *) source, .len = strlen(source) }, 1, argv) != 0) { return 1; } bare_worklet_push_t req = { 0 }; req.data = &req; /* or use bare_worklet_push_set_data */ const char *payload = "ping"; if (bare_worklet_push(&w, &req, &(uv_buf_t){ .base = (char *) payload, .len = strlen(payload) }, on_push) != 0) { return 1; } uv_sleep(1000); bare_worklet_terminate(&w); bare_worklet_destroy(&w); return 0; } ``` -------------------------------- ### Install bare-kit globally Source: https://github.com/holepunchto/bare-kit/blob/main/npm/README.md Install the bare-kit package globally using npm. ```sh npm i -g bare-kit ``` -------------------------------- ### Host-side Example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-queue.md Example of host-side usage of the bare_queue API, including opening a thread port, reading and writing messages, and handling would-block conditions. ```APIDOC ## Host-side Example ### Description Example of host-side usage of the bare_queue API, including opening a thread port, reading and writing messages, and handling would-block conditions. ### Functions Used - `bare_queue_create()` - `bare_queue_open_thread(q, on_signal)` - `bare_queue_readable(port)` - `bare_queue_read(port, &data, &len)` - `bare_queue_writable(port)` - `bare_queue_write(port, msg, len)` ### Example Code ```c static void on_signal(bare_queue_port_t *port) { /* Hop back to our own run loop and re-check both directions. */ schedule_on_main_thread(port); } void on_main_thread(bare_queue_port_t *port) { if (bare_queue_readable(port)) { void *data; size_t len; if (bare_queue_read(port, &data, &len) == bare_queue_ok) { if (len == 0) return; /* EOF: peer closed */ /* consume message, then the buffer is reusable */ } } if (bare_queue_writable(port)) { const char msg[] = "hello"; int n = bare_queue_write(port, msg, sizeof(msg) - 1); if (n == bare_queue_would_block) retry_later(port); } } bare_queue_t *q = bare_queue_create(); bare_queue_port_t *host = bare_queue_open_thread(q, on_signal); /* ... hand q to the worklet, which calls bare_queue_open_uv(q, loop, on_recv) ... */ ``` ``` -------------------------------- ### start overloads Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/android-worklet.md All public overloads of the start method. Each asynchronously starts the worklet thread with the given entry filename and argv, with different ways to provide the source code. ```APIDOC ## start(String filename, String[] arguments) ### Description Starts the worklet thread asynchronously with the given entry filename. The source is resolved by the worklet's module protocol. ### Method start ### Signature `public void start(String filename, String[] arguments)` ### Parameters - **filename** (`String`) - Required - Worklet entry filename. - **arguments** (`String[]`) - Required - argv passed to the worklet. `null` allowed. ### Return Type `void` ### Example ```java Worklet worklet = new Worklet(new Worklet.Options().memoryLimit(24 * 1024 * 1024)); worklet.start("/app.js", null); ``` ``` ```APIDOC ## start(String filename, ByteBuffer source, String[] arguments) ### Description Starts the worklet thread asynchronously from a byte source. A heap buffer is copied into a fresh direct buffer; a direct buffer is passed through as-is. If `source` is `null`, falls back to filename loading. ### Method start ### Signature `public void start(String filename, ByteBuffer source, String[] arguments)` ### Parameters - **filename** (`String`) - Required - Worklet entry filename. - **source** (`ByteBuffer`) - Optional - Inline source; omitted → resolved by filename. - **arguments** (`String[]`) - Required - argv passed to the worklet. `null` allowed. ### Return Type `void` ### Example ```java Worklet worklet = new Worklet(new Worklet.Options().memoryLimit(24 * 1024 * 1024)); ByteBuffer source = ByteBuffer.wrap("console.log('hello')".getBytes()); worklet.start("/app.js", source, null); ``` ``` ```APIDOC ## start(String filename, String source, Charset charset, String[] arguments) ### Description Starts the worklet thread asynchronously from a string source, encoding it with the given charset and delegating to the ByteBuffer variant. ### Method start ### Signature `public void start(String filename, String source, Charset charset, String[] arguments)` ### Parameters - **filename** (`String`) - Required - Worklet entry filename. - **source** (`String`) - Optional - Inline source; omitted → resolved by filename. - **charset** (`Charset`) - Required - Charset for source encoding. - **arguments** (`String[]`) - Required - argv passed to the worklet. `null` allowed. ### Return Type `void` ### Example ```java import to.holepunch.bare.kit.Worklet; import java.nio.charset.StandardCharsets; Worklet worklet = new Worklet(new Worklet.Options().memoryLimit(24 * 1024 * 1024)); String source = "console.log('hello from the worklet')"; worklet.start("/app.js", source, StandardCharsets.UTF_8, null); ``` ``` ```APIDOC ## start(String filename, String source, String charset, String[] arguments) ### Description Starts the worklet thread asynchronously from a string source, encoding it with the charset given by name and delegating to the ByteBuffer variant. ### Method start ### Signature `public void start(String filename, String source, String charset, String[] arguments)` ### Parameters - **filename** (`String`) - Required - Worklet entry filename. - **source** (`String`) - Optional - Inline source; omitted → resolved by filename. - **charset** (`String`) - Required - Charset name for source encoding (via `Charset.forName(charset)`). - **arguments** (`String[]`) - Required - argv passed to the worklet. `null` allowed. ### Return Type `void` ### Example ```java Worklet worklet = new Worklet(new Worklet.Options().memoryLimit(24 * 1024 * 1024)); worklet.start("/app.js", "console.log('hello')", "UTF-8", null); ``` ``` ```APIDOC ## start(String filename, InputStream source, String[] arguments) throws IOException ### Description Starts the worklet thread asynchronously from an input stream. Reads the stream to EOF into a growing (doubling) direct buffer starting at `max(4096, available())`, then starts. Calls `source.reset()` first. ### Method start ### Signature `public void start(String filename, InputStream source, String[] arguments) throws IOException` ### Parameters - **filename** (`String`) - Required - Worklet entry filename. - **source** (`InputStream`) - Optional - Inline source; omitted → resolved by filename. - **arguments** (`String[]`) - Required - argv passed to the worklet. `null` allowed. ### Return Type `void` ### Exceptions - **IOException** - On stream failures. ### Example ```java Worklet worklet = new Worklet(new Worklet.Options().memoryLimit(24 * 1024 * 1024)); try (InputStream source = new FileInputStream("/path/to/app.js")) { worklet.start("/app.js", source, null); } catch (IOException e) { e.printStackTrace(); } ``` ``` -------------------------------- ### Worklet basic creation example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/android-worklet.md Basic example of creating a Worklet with a memory limit of 24 MiB. The assets path is commented out as optional. ```java Worklet.Options options = new Worklet.Options() .memoryLimit(24 * 1024 * 1024); // 24 MiB // .assets("/path/to/assets"); // optional Worklet worklet = new Worklet(options); ``` -------------------------------- ### - (void)start:(NSString *)name ofType:(NSString *)type inBundle:(NSBundle *)bundle arguments:(NSArray *_Nullable)arguments Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Loads a bundle resource from an explicit bundle and starts from that path. ```APIDOC ## [OBJC] - (void)start:(NSString *)name ofType:(NSString *)type inBundle:(NSBundle *)bundle arguments:(NSArray *_Nullable)arguments ### Description Loads a bundle resource from an explicit bundle and starts from that path. The call blocks until the worklet thread has finished booting. ### Method Objective-C instance method ### Signature `- (void)start:(NSString *)name ofType:(NSString *)type inBundle:(NSBundle *)bundle arguments:(NSArray *_Nullable)arguments` ### Parameters - **name** (NSString *) - Required - Resource name. - **type** (NSString *) - Required - Resource type (extension). - **bundle** (NSBundle *) - Required - Bundle to look up the resource in. - **arguments** (NSArray *) - Optional (nil allowed) - argv passed to the worklet. ### Return Type void ### Errors Errors surface as process aborts (assert(err == 0)), not exceptions. ``` -------------------------------- ### - (void)start:(NSString *)name ofType:(NSString *)type inDirectory:(NSString *)subpath arguments:(NSArray *_Nullable)arguments Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Loads a bundle resource from a subdirectory of the main bundle and starts from that path. ```APIDOC ## [OBJC] - (void)start:(NSString *)name ofType:(NSString *)type inDirectory:(NSString *)subpath arguments:(NSArray *_Nullable)arguments ### Description Loads a bundle resource from a subdirectory of the main bundle and starts from that path. The call blocks until the worklet thread has finished booting. ### Method Objective-C instance method ### Signature `- (void)start:(NSString *)name ofType:(NSString *)type inDirectory:(NSString *)subpath arguments:(NSArray *_Nullable)arguments` ### Parameters - **name** (NSString *) - Required - Resource name. - **type** (NSString *) - Required - Resource type (extension). - **subpath** (NSString *) - Required - Bundle subdirectory. - **arguments** (NSArray *) - Optional (nil allowed) - argv passed to the worklet. ### Return Type void ### Errors Errors surface as process aborts (assert(err == 0)), not exceptions. ``` -------------------------------- ### - (void)start:(NSString *)filename source:(NSData *_Nullable)source arguments:(NSArray *_Nullable)arguments Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Starts a worklet with the given bytes as source. If source is nil, falls back to loading by filename. ```APIDOC ## [OBJC] - (void)start:(NSString *)filename source:(NSData *_Nullable)source arguments:(NSArray *_Nullable)arguments ### Description Starts a worklet with the given bytes as source. If source is nil, falls back to loading by filename. The call blocks until the worklet thread has finished booting. ### Method Objective-C instance method ### Signature `- (void)start:(NSString *)filename source:(NSData *_Nullable)source arguments:(NSArray *_Nullable)arguments` ### Parameters - **filename** (NSString *) - Required - Worklet entry filename. - **source** (NSData *) - Optional - Inline source; when nil, the file is resolved at runtime. - **arguments** (NSArray *) - Optional (nil allowed) - argv passed to the worklet. ### Return Type void ### Errors Errors surface as process aborts (assert(err == 0)), not exceptions. ``` -------------------------------- ### - (void)start:(NSString *)name ofType:(NSString *)type arguments:(NSArray *_Nullable)arguments Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Loads [NSBundle mainBundle] pathForResource:name ofType:type and starts from that path. ```APIDOC ## [OBJC] - (void)start:(NSString *)name ofType:(NSString *)type arguments:(NSArray *_Nullable)arguments ### Description Loads [NSBundle mainBundle] pathForResource:name ofType:type and starts from that path. The call blocks until the worklet thread has finished booting. ### Method Objective-C instance method ### Signature `- (void)start:(NSString *)name ofType:(NSString *)type arguments:(NSArray *_Nullable)arguments` ### Parameters - **name** (NSString *) - Required - Resource name. - **type** (NSString *) - Required - Resource type (extension). - **arguments** (NSArray *) - Optional (nil allowed) - argv passed to the worklet. ### Return Type void ### Errors Errors surface as process aborts (assert(err == 0)), not exceptions. ``` -------------------------------- ### - (_Nullable instancetype)initWithConfiguration:(BareWorkletConfiguration *_Nullable)options Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Creates a BareWorklet object with the given configuration. The worklet does not start running until a start: variant is called. ```APIDOC ## - (_Nullable instancetype)initWithConfiguration:(BareWorkletConfiguration *_Nullable)options ### Description Creates the worklet object and initializes the underlying `bare_worklet_t` with the given options (`options == nil` behaves like a default configuration). Registers the Objective-C object as the worklet's `data` pointer. ### Method Instance method ### Parameters #### Parameters - **options** (BareWorkletConfiguration * nullable) - Optional - Configuration; `nil` == defaults. ### Return Type `instancetype` (nullable). The worklet has not begun running until a `start:` variant is called. ### Example — basic ```objc #import BareWorkletConfiguration *options = [BareWorkletConfiguration defaultWorkletConfiguration]; options.memoryLimit = 1024 * 1024 * 24; // 24 MiB options.assets = NSHomeDirectory(); // where worklet assets may be unpacked BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:options]; ``` ``` -------------------------------- ### BareIPC read:completion: example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Asynchronous read example using the completion block. Handles end-of-stream (nil data) and decodes received data as UTF-8. ```objc [ipc read:^(NSData *data, NSError *error) { if (data == nil) { NSLog(@"end of stream"); return; } NSLog(@"Received: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; ``` -------------------------------- ### - (void)start:(NSString *)filename arguments:(NSArray *_Nullable)arguments Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Starts a worklet from a filename, resolved by the worklet's module resolution protocol. Blocks until the worklet thread has booted. ```APIDOC ## [OBJC] - (void)start:(NSString *)filename arguments:(NSArray *_Nullable)arguments ### Description Starts a worklet from a filename; the source is loaded by the worklet's module resolution protocol. The call blocks until the worklet thread has finished booting. ### Method Objective-C instance method ### Signature `- (void)start:(NSString *)filename arguments:(NSArray *_Nullable)arguments` ### Parameters - **filename** (NSString *) - Required - Worklet entry filename. - **arguments** (NSArray *) - Optional (nil allowed) - argv passed to the worklet. ### Return Type void ### Errors Errors surface as process aborts (assert(err == 0)), not exceptions. ``` -------------------------------- ### Export start bootstrap function Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/js-barekit.md Exports the async start function that bootstraps the entry module. It normalizes assets, resolves the entry filename, reads source synchronously if null, unpacks .bundle files if configured, and finally loads the module with Module.loadSync. ```javascript exports.start = async function start(filename, source, assets) { ... } ``` -------------------------------- ### Install BareKit on global Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/js-barekit.md Installs the BareKit singleton on the worklet global as an immutable-but-configurable, enumerable property. It is shared with the npm package as its default export. ```javascript Object.defineProperty(global, 'BareKit', { value: exports.BareKit, enumerable: true, writable: false, configurable: true }) ``` -------------------------------- ### bare_worklet_start Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-worklet.md Starts the worklet with the given entry source and arguments. ```APIDOC ## bare_worklet_start ### Description Starts the worklet with the given entry source and arguments. ### Method Function call ### Endpoint `int bare_worklet_start(bare_worklet_t *worklet, const char *filename, const uv_buf_t *source, int argc, const char **argv)` ### Parameters - **worklet** (bare_worklet_t*) - Required - Pointer to the initialized worklet. - **filename** (const char*) - Required - Entry filename (e.g., "/app.js"). - **source** (const uv_buf_t*) - Required - Buffer containing the JavaScript source code. - **argc** (int) - Required - Number of arguments in argv. - **argv** (const char**) - Required - Array of argument strings (e.g., ["label"]). ### Return Value - **int** - 0 on success, non-zero on failure. ### Example ```c const char *argv[] = { "label" }; const char *source = "console.log('hi')"; if (bare_worklet_start(&w, "/app.js", &(uv_buf_t){ .base = (char *) source, .len = strlen(source) }, 1, argv) != 0) { return 1; } ``` ``` -------------------------------- ### Start worklet from string source Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Starts a worklet from an inline source string. The source is converted to NSData with NSUTF8StringEncoding and passed to the start:source:arguments: variant. The call blocks until the worklet thread has booted, but bare_worklet_start is non-blocking after that. ```objc BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; NSString *source = @"console.log('hello from the worklet')"; [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; ``` -------------------------------- ### bare_worklet_start Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-worklet.md Starts the worklet thread. ```APIDOC ## bare_worklet_start ### Description Starts the worklet thread. The thread bootstraps the shared JS platform thread, initializes a bare runtime, loads the embedded worklet bundle, grabs IPC port file descriptors, creates the push threadsafe function, and calls `start(filename, source, assets)` in the worklet JS. The caller blocks on the ready barrier until the worklet thread is set up, then detaches the thread and returns. ### Method C function ### Endpoint `int bare_worklet_start(bare_worklet_t *worklet, const char *filename, const uv_buf_t *source, int argc, const char *argv[])` ### Parameters - `worklet` (bare_worklet_t *) - Required - Initialized worklet. - `filename` (const char *) - Required - Entry filename for module resolution. - `source` (const uv_buf_t *) - Optional (NULL = load by filename) - Optional inline source bytes. - `argc` (int) - Required - Number of argv entries. - `argv` (const char *[]) - Required - Worklet argv. ### Return `int` - `0` on success; a negative libuv error (e.g. thread creation failure) in which case the ready barrier is cleaned up first. ``` -------------------------------- ### - (void)start:(NSString *)name ofType:(NSString *)type inDirectory:(NSString *)subpath inBundle:(NSBundle *)bundle arguments:(NSArray *_Nullable)arguments Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Fully explicit bundle-resource lookup: loads a resource from a subdirectory of a given bundle and starts from that path. ```APIDOC ## [OBJC] - (void)start:(NSString *)name ofType:(NSString *)type inDirectory:(NSString *)subpath inBundle:(NSBundle *)bundle arguments:(NSArray *_Nullable)arguments ### Description Fully explicit bundle-resource lookup: loads a resource from a subdirectory of a given bundle and starts from that path. The call blocks until the worklet thread has finished booting. ### Method Objective-C instance method ### Signature `- (void)start:(NSString *)name ofType:(NSString *)type inDirectory:(NSString *)subpath inBundle:(NSBundle *)bundle arguments:(NSArray *_Nullable)arguments` ### Parameters - **name** (NSString *) - Required - Resource name. - **type** (NSString *) - Required - Resource type (extension). - **subpath** (NSString *) - Required - Bundle subdirectory. - **bundle** (NSBundle *) - Required - Bundle to look up the resource in. - **arguments** (NSArray *) - Optional (nil allowed) - argv passed to the worklet. ### Return Type void ### Errors Errors surface as process aborts (assert(err == 0)), not exceptions. ``` -------------------------------- ### Host-side example using bare_queue_open_thread and bare_queue_read/write Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-queue.md Host-side usage example. The on_signal callback schedules work back to the main thread, where on_main_thread reads available messages (treating len 0 as EOF) and writes a message, handling bare_queue_would_block. The host opens a thread port with bare_queue_open_thread and hands the queue to the worklet, which opens the uv side. ```c static void on_signal(bare_queue_port_t *port) { /* Hop back to our own run loop and re-check both directions. */ schedule_on_main_thread(port); } void on_main_thread(bare_queue_port_t *port) { if (bare_queue_readable(port)) { void *data; size_t len; if (bare_queue_read(port, &data, &len) == bare_queue_ok) { if (len == 0) return; /* EOF: peer closed */ /* consume message, then the buffer is reusable */ } } if (bare_queue_writable(port)) { const char msg[] = "hello"; int n = bare_queue_write(port, msg, sizeof(msg) - 1); if (n == bare_queue_would_block) retry_later(port); } } bare_queue_t *q = bare_queue_create(); bare_queue_port_t *host = bare_queue_open_thread(q, on_signal); /* ... hand q to the worklet, which calls bare_queue_open_uv(q, loop, on_recv) ... */ ``` -------------------------------- ### Run test app on iOS simulator Source: https://github.com/holepunchto/bare-kit/blob/main/CONTRIBUTING.md Run the test app on a simulator. The first uses a placeholder name; the second shows an example with 'iPhone 15'. ```bash xcrun simctl spawn "" ./build/test/apple/worklet.app/worklet ``` ```bash xcrun simctl spawn "iPhone 15" ./build/test/apple/worklet.app/worklet ``` -------------------------------- ### Asynchronous write example with error handling Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/android-ipc.md Example of using the asynchronous write method with error handling. The callback receives an exception if the write fails, otherwise prints a success message. ```java ByteBuffer message = ByteBuffer.wrap("Hello from main thread".getBytes(StandardCharsets.UTF_8)); ipc.write(message, (exception) -> { if (exception != null) { System.err.println("Write error: " + exception.getMessage()); } else { System.out.println("Message sent successfully"); } }); ``` -------------------------------- ### Raw C poll loop Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-ipc.md Example showing how to use bare_ipc_init, bare_ipc_poll_init, bare_ipc_poll_start, bare_ipc_read, bare_ipc_write, and bare_ipc_poll_stop in a poll loop. ```APIDOC ## bare_ipc_init ### Description Initializes a bare_ipc_t instance associated with a worklet. ### Method C function ### Signature ```c void bare_ipc_init(bare_ipc_t *ipc, bare_worklet_t *worklet); ``` ### Parameters - **ipc** (bare_ipc_t*) - Required - Pointer to the IPC instance to initialize. - **worklet** (bare_worklet_t*) - Required - Pointer to the worklet that owns the pipe ends. ### Return Value None. ## bare_ipc_poll_init ### Description Initializes a bare_ipc_poll_t instance associated with an IPC instance. ### Method C function ### Signature ```c void bare_ipc_poll_init(bare_ipc_poll_t *poll, bare_ipc_t *ipc); ``` ### Parameters - **poll** (bare_ipc_poll_t*) - Required - Pointer to the poll instance to initialize. - **ipc** (bare_ipc_t*) - Required - Pointer to the IPC instance. ### Return Value None. ## bare_ipc_poll_start ### Description Starts polling for events on the IPC instance. ### Method C function ### Signature ```c void bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, void (*on_poll)(bare_ipc_poll_t *, int)); ``` ### Parameters - **poll** (bare_ipc_poll_t*) - Required - Pointer to the poll instance. - **events** (int) - Required - Bitmask of events to watch (e.g., bare_ipc_readable, bare_ipc_writable). - **on_poll** (function pointer) - Required - Callback invoked when poll events occur. ### Return Value None. ## bare_ipc_poll_stop ### Description Stops polling on the IPC instance. ### Method C function ### Signature ```c void bare_ipc_poll_stop(bare_ipc_poll_t *poll); ``` ### Parameters - **poll** (bare_ipc_poll_t*) - Required - Pointer to the poll instance. ### Return Value None. ## bare_ipc_read ### Description Reads data from the IPC pipe. ### Method C function ### Signature ```c int bare_ipc_read(bare_ipc_t *ipc, void **data, size_t *len); ``` ### Parameters - **ipc** (bare_ipc_t*) - Required - Pointer to the IPC instance. - **data** (void**) - Required - Output pointer to the read data buffer. - **len** (size_t*) - Required - Output pointer to the length of the read data. ### Return Value Returns 0 on success, or an error code on failure. A length of 0 indicates EOF (the worklet closed its end). ## bare_ipc_write ### Description Writes data to the IPC pipe. ### Method C function ### Signature ```c int bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len); ``` ### Parameters - **ipc** (bare_ipc_t*) - Required - Pointer to the IPC instance. - **data** (const void*) - Required - Pointer to the data to write. - **len** (size_t) - Required - Number of bytes to write. ### Return Value Returns the number of bytes written, or an error code on failure. ## bare_ipc_poll_get_ipc ### Description Retrieves the IPC instance associated with a poll. ### Method C function ### Signature ```c bare_ipc_t *bare_ipc_poll_get_ipc(bare_ipc_poll_t *poll); ``` ### Parameters - **poll** (bare_ipc_poll_t*) - Required - Pointer to the poll instance. ### Return Value Pointer to the associated bare_ipc_t instance. ``` -------------------------------- ### Basic polling example with readable() Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/android-ipc.md Basic polling example using the readable callback. Reads data, handles null (retry) and empty buffer (end-of-stream) cases, and prints received data as a UTF-8 string. ```java ipc.readable(() -> { ByteBuffer data = ipc.read(); if (data == null) return; // retry after the next readable event if (data.limit() == 0) { System.out.println("worklet closed its end of the IPC"); ipc.readable(null); return; } byte[] bytes = new byte[data.remaining()]; data.get(bytes); System.out.println("Received: " + new String(bytes, StandardCharsets.UTF_8)); }); ``` -------------------------------- ### BareKit IPC write example with error handling Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Shows how to call the write:completion: method with error handling. The completion block logs whether the write failed or succeeded. ```objc NSData *payload = [@"big payload" dataUsingEncoding:NSUTF8StringEncoding]; [ipc write:payload completion:^(NSError *error) { if (error != nil) { NSLog(@"write failed: %@", error); } else { NSLog(@"fully written"); } }]; ``` -------------------------------- ### Create and start a Worklet in Java Source: https://github.com/holepunchto/bare-kit/blob/main/README.md Creates a Worklet on Android with a 24 MiB memory limit, starts it with a JavaScript source string, and passes UTF-8 encoding. The configuration step is optional; the worklet instance represents the running worklet. ```java import to.holepunch.bare.kit.Worklet; import java.nio.charset.StandardCharsets; Worklet.Options options = new Worklet.Options() .memoryLimit(24 * 1024 * 1024); // 24 MiB Worklet worklet = new Worklet(options); String source = "console.log('hello from the worklet')"; worklet.start("/app.js", source, StandardCharsets.UTF_8, null); ``` -------------------------------- ### Create and start a BareWorklet in Objective-C Source: https://github.com/holepunchto/bare-kit/blob/main/README.md Creates a BareWorklet on iOS with a 24 MiB memory limit, starts it with a JavaScript source string, and runs the run loop. The configuration step is optional; the worklet instance represents the running worklet. ```objc #import #import int main() { BareWorkletConfiguration *options = [BareWorkletConfiguration defaultWorkletConfiguration]; options.memoryLimit = 1024 * 1024 * 24; // 24 MiB BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:options]; NSString *source = @"console.log('hello from the worklet')"; [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; [[NSRunLoop currentRunLoop] run]; } ``` -------------------------------- ### - (void)start:(NSString *)filename source:(NSString *)source encoding:(NSStringEncoding)encoding arguments:(NSArray *_Nullable)arguments Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Convenience overload that encodes the source string with the given encoding and calls the NSData variant. ```APIDOC ## [OBJC] - (void)start:(NSString *)filename source:(NSString *)source encoding:(NSStringEncoding)encoding arguments:(NSArray *_Nullable)arguments ### Description Convenience overload: encodes the source string with the given encoding and calls the NSData variant. The call blocks until the worklet thread has finished booting. ### Method Objective-C instance method ### Signature `- (void)start:(NSString *)filename source:(NSString *)source encoding:(NSStringEncoding)encoding arguments:(NSArray *_Nullable)arguments` ### Parameters - **filename** (NSString *) - Required - Worklet entry filename. - **source** (NSString *) - Required - Source string to encode. - **encoding** (NSStringEncoding) - Required - Encoding used to convert the source string. - **arguments** (NSArray *) - Optional (nil allowed) - argv passed to the worklet. ### Return Type void ### Errors Errors surface as process aborts (assert(err == 0)), not exceptions. ``` -------------------------------- ### bare_queue_create function declaration Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-queue.md Creates the queue, initializing the uv async handle, mutex, both rings, and both ports. Created on the host thread, handed to the worklet at start, freed by bare_queue_destroy on the worklet thread. Returns a new queue, never NULL in practice, asserting on init failure. ```c bare_queue_t * bare_queue_create(void); ``` -------------------------------- ### bare_worklet_optimize_for_memory declaration Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-worklet.md Trades performance for memory. Sets UV_THREADPOOL_SIZE to "1" (enabled) or "4" (disabled) via uv_os_setenv and flips bare_worklet__platform_options.optimize_for_memory. Must be called before the first bare_worklet_start because the JS platform thread is created lazily on the first start. Returns 0 on success; asserts internally on uv_os_setenv failure. ```c int bare_worklet_optimize_for_memory(bool enabled); ``` -------------------------------- ### BareWorklet initWithConfiguration: declaration Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Initializer that creates the worklet object and initializes the underlying bare_worklet_t with the given options (nil behaves like defaults). Registers the Objective-C object as the worklet's data pointer. The worklet does not begin running until a start: variant is called. ```objc - (_Nullable instancetype)initWithConfiguration:(BareWorkletConfiguration *_Nullable)options; ``` -------------------------------- ### Raw C poll loop with bare_ipc_poll Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-ipc.md Shows a raw C poll loop using the bare-kit IPC API. The callback handles readable events (reading data, stopping on EOF) and writable events (writing a message, then restarting the poll for readable only). The example assumes a started worklet and initializes the IPC and poll structures before starting the poll. ```c #include "shared/ipc.h" static void on_poll(bare_ipc_poll_t *poll, int events) { bare_ipc_t *ipc = bare_ipc_poll_get_ipc(poll); if (events & bare_ipc_readable) { void *data; size_t len; int err = bare_ipc_read(ipc, &data, &len); if (err == 0) { /* len == 0 means EOF: the worklet closed its end */ bare_ipc_poll_stop(poll); } } if (events & bare_ipc_writable) { const char msg[] = "hello"; int n = bare_ipc_write(ipc, msg, sizeof(msg) - 1); if (n == sizeof(msg) - 1) /* fully written, stop watching writable */ bare_ipc_poll_start(poll, bare_ipc_readable, on_poll); } } /* assume bare_worklet_t w is started */ bare_ipc_t ipc; bare_ipc_poll_t poll; bare_ipc_init(&ipc, &w); bare_ipc_poll_init(&poll, &ipc); bare_ipc_poll_start(&poll, bare_ipc_readable | bare_ipc_writable, on_poll); ``` -------------------------------- ### Set up global console with SystemLog Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/js-barekit.md Sets up the global console on the worklet thread using a bare-console instance that logs through bare-system-logger (SystemLog: OS log on iOS/Android). This is executed before the user entry module. ```javascript global.console = new Console(new SystemLog()) ``` -------------------------------- ### BareIPC write polling example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Polling write example using the writable callback. Stops the poll when all bytes are written; otherwise retries with the remainder on the next writable event. ```objc NSData *message = [@"Hello from main thread" dataUsingEncoding:NSUTF8StringEncoding]; ipc.writable = ^(BareIPC *ipc) { NSInteger written = [ipc write:message]; if (written == message.length) { ipc.writable = nil; // done; stop the write poll } else { // written < length — retry with the remainder on the next writable event } }; ``` -------------------------------- ### Generate and build iOS project Source: https://github.com/holepunchto/bare-kit/blob/main/CONTRIBUTING.md Generate the iOS project for the arm64 simulator, then build it. ```bash bare-make generate --platform ios --arch arm64 --simulator ``` ```bash bare-make build ``` -------------------------------- ### BareIPC read polling example Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/apple-barekit.md Polling read example using the readable callback. Retries on nil, stops the poll on end-of-stream (empty data), and logs the received byte count. ```objc ipc.readable = ^(BareIPC *ipc) { NSData *data = [ipc read]; if (data == nil) return; // retry after the next readable event if (data.length == 0) { NSLog(@"worklet closed its end of the IPC"); ipc.readable = nil; return; } NSLog(@"Received %lu bytes", (unsigned long)data.length); }; ``` -------------------------------- ### Error handling example with read(ReadCallback) Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/android-ipc.md Example of error handling with the asynchronous read method. Handles exceptions, null data (IPC closed), and prints received data as a UTF-8 string. ```java ipc.read((data, exception) -> { if (exception != null) { System.err.println("Read error: " + exception.getMessage()); return; } if (data == null) { System.out.println("IPC closed by worklet"); return; } byte[] bytes = new byte[data.remaining()]; data.get(bytes); System.out.println("Received: " + new String(bytes, StandardCharsets.UTF_8)); }); ``` -------------------------------- ### bare_worklet_init Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-worklet.md Initializes a worklet instance with the given options. ```APIDOC ## bare_worklet_init ### Description Initializes a worklet instance with the given options. ### Method Function call ### Endpoint `int bare_worklet_init(bare_worklet_t *worklet, const bare_worklet_options_t *options)` ### Parameters - **worklet** (bare_worklet_t*) - Required - Pointer to the worklet structure to initialize. - **options** (const bare_worklet_options_t*) - Required - Pointer to options structure. Fields: `memory_limit` (size_t) - Optional - Memory limit in bytes, 0 to infer from physical memory. `assets` (const char*) - Optional - Path to asset directory, NULL for none. ### Return Value - **int** - 0 on success, non-zero on failure. ### Example ```c bare_worklet_t w; bare_worklet_options_t options = { .memory_limit = 0, .assets = NULL, }; if (bare_worklet_init(&w, &options) != 0) return 1; ``` ``` -------------------------------- ### Configure Worklet with Worklet.Options Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/configuration.md Configure a Worklet with a memory limit and asset directory using the fluent Options builder. Passing null to the Worklet constructor applies the defaults (memoryLimit 0, assets null). ```java Worklet.Options options = new Worklet.Options() .memoryLimit(24 * 1024 * 1024) .assets("/data/assets"); Worklet worklet = new Worklet(options); // or: new Worklet(null) == defaults ``` -------------------------------- ### Publish Android JVM context (shared/android/context.c) Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-suspension-events-context.md Android implementation of bare_kit__publish_context. It retrieves the JavaVM via bare_kit__jvm_get and publishes it under the key "bare.android.jvm.v1" using bare_context_set, so in-process addons can retrieve it with bare_context_get(). The non-Android shared/context.c is a stub with an empty body. ```c void bare_kit__publish_context(bare_t *bare) { JavaVM *vm = bare_kit__jvm_get(); assert(vm != NULL); err = bare_context_set(bare, "bare.android.jvm.v1", vm, NULL); assert(err == 0); } ``` -------------------------------- ### bare_worklet_t struct definition Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/types.md Main worklet struct. Fields cover runtime handle, options, state, filename, optional inline source, argv, thread handle, barriers, pipes, and push channel. incoming/outgoing are -1 before start; thread is 0 before start. ```c struct bare_worklet_s { bare_t *bare; /* bare runtime handle */ bare_worklet_options_t options; /* configured options */ bare_worklet_state_t *state; /* finished flag + lifecycle callbacks */ const char *filename; /* entry filename for module resolution */ struct { enum { bare_worklet_source_none = 0, bare_worklet_source_buffer = 1, } type; union { uv_buf_t buffer; }; } source; /* optional inline source */ void *finalize_hint; int argc; /* argv count */ const char **argv; /* worklet argv */ uv_thread_t thread; /* running thread (0 = not started) */ uv_barrier_t ready; /* start barrier */ uv_sem_t *finished; /* completion semaphore */ uv_file incoming; /* worklet -> host pipe end */ uv_file outgoing; /* host -> worklet pipe end */ js_threadsafe_function_t *push; /* push channel to the JS thread */ void *data; /* opaque user field */ }; ``` -------------------------------- ### bare_worklet_options_t Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/types.md Configuration options for a worklet, accepted by `bare_worklet_init()`. ```APIDOC ## bare_worklet_options_t ### Description Configuration options for a worklet, accepted by `bare_worklet_init()`. ### Fields - **memory_limit** (`size_t`) - Per-thread JS heap limit in bytes; `0` = infer from physical memory. - **assets** (`const char *`) - Asset directory; `NULL` = assets may not be referenced. ``` -------------------------------- ### bare_worklet_init Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-worklet.md Initializes a bare_worklet_t with the given options. Performs one-time initialization and copies options, duplicating the assets string. ```APIDOC ## bare_worklet_init ### Description Initializes the worklet: runs process-wide one-time init, allocates state, and copies options. The `assets` string is duplicated; `memory_limit` 0 means "infer from physical memory". ### Signature ```c int bare_worklet_init(bare_worklet_t *worklet, const bare_worklet_options_t *options); ``` ### Parameters - **worklet** (`bare_worklet_t *`) - Required - Storage for the worklet (may be allocated by `bare_worklet_alloc` or stack/ivvar storage). - **options** (`const bare_worklet_options_t *`) - Optional (`NULL` allowed) - Options; zeroed defaults when `NULL`. ### Return `int` — always `0`; aborts via assert on `malloc` failure. ``` -------------------------------- ### bare_worklet_destroy declaration Source: https://github.com/holepunchto/bare-kit/blob/main/_autodocs/api-reference/c-worklet.md Destroys the worklet: posts the finish semaphore if a thread was started, otherwise frees the state; closes the incoming/outgoing descriptors and frees the strdup'ed assets string. ```c void bare_worklet_destroy(bare_worklet_t *worklet); ```