Native modules
Call Swift from Octane apps, typed end to end, and exchange props and events with the host.
Octapus installs Swift functions into each Hermes runtime as JSI host functions under globalThis.native.<Module>.<member>. JS calls them directly and synchronously on the JS thread, with no message bus or JSON. Values cross as a small value tree (null, boolean, number, string, array, object). Async functions return a Promise.
import { native, host } from 'octapus-js/native';
native.Haptics.impact('light'); // sync
const { os, version } = native.Platform.info(); // sync, typed result
const ms = await native.Platform.delay(100); // Promise
native.Storage.set('session', { user: 'ada' });Modules are installed before the bundle evaluates, so they are available at module scope and in the first render. They are registered per OctapusRoot (there are no globals), and each root's runtime only sees its own modules.
Defining a module (Swift)
Each module is one class in one file. It has a static name and a declarative definition():
import OctapusCore
public final class HapticsModule: OctapusModule {
public static let name = "Haptics"
public init() {}
public enum ImpactStyle: String, OctapusEnum { case light, medium, heavy, soft, rigid }
public func definition() -> ModuleDefinition {
Constant("supported") { true }
// Strings after the function name are the JS parameter names in the generated types.
Function("impact", "style") { (style: ImpactStyle?) in
let s = style ?? .medium
DispatchQueue.main.async { /* UIKit: runs on main */ _ = s }
}
AsyncFunction("prepare") { (promise: Promise<OctapusVoid>) in
DispatchQueue.main.async { /* ... */ promise.resolve() }
}
}
}| Declaration | JS | Runs on |
|---|---|---|
Function(name, paramNames...) { (A, B) throws -> R in } | native.M.name(a, b): R | the JS thread, synchronously |
AsyncFunction(name, paramNames...) { (A, Promise<R>) in } | native.M.name(a): Promise<R> | starts on the JS thread; settle from any thread |
Constant(name) { R } | native.M.name: R (readonly) | evaluated once per runtime at install |
Functions take up to three typed parameters, with a Promise as the last parameter for async functions. A Swift throw becomes a JS Error whose message names the function, for example Haptics.impact: …, and whose code is set. OctapusModuleError(code:_:) lets you choose the code.
Types
Parameter and return types conform to OctapusValueConvertible. That protocol converts the value and supplies the TypeScript type used for generated declarations.
| Swift | TypeScript |
|---|---|
String, Bool | string, boolean |
Double, Float, Int (must be an integer in JS) | number |
T? | optional parameter (name?: T | null), T | null result |
[T], [String: T] | T[], Record<string, T> |
enum E: String, OctapusEnum | 'a' | 'b' |
struct S: OctapusRecord (Codable) | { x: number; label?: string | null } |
OctapusAny, [String: OctapusAny] | unknown, Record<string, unknown> (untyped JSON-like values; plain Any, [Any] and [String: Any] cannot be parameters) |
Promise<OctapusVoid> / no return value | Promise<void> / void |
Arguments are validated before your code runs, and errors say exactly what is wrong:
Storage.get: argument 0: expected string, got number 42
Haptics.impact: argument 0: expected 'light' | 'medium' | 'heavy' | 'soft' | 'rigid', got string "loud"
Test.add: expected at most 2 arguments, got 3
Test.point: argument 0: Point: missing field "y"
native.Haptics has no member "impactt" (has: supported, impact, notification, selection)Threading
Functionbodies run on the JS thread, inside the JS call. Keep them short. For UIKit and AppKit work, hop to main yourself (DispatchQueue.main.async). The JS caller does not wait for that work.AsyncFunctionbodies start on the JS thread. Callpromise.resolve(_:)orpromise.reject(_:)once, from any thread. Octapus moves the result to the JS thread, and the batches it causes are applied like any event. Later settles are ignored.- A module instance is used only from its root's JS thread, and from whatever threads you dispatch to.
Registering modules
Register modules on each root, before launch:
// macOS
let host = OctapusHostView(modules: [ClipboardModule()]) // + built-ins
OctapusView(bundle: bundle, modules: [ClipboardModule()]) // SwiftUI
// iOS
let view = OctapusView(bundle: bundle, modules: [ClipboardModule()])
OctapusSurface(bundle: bundle, modules: [ClipboardModule()])
// any root
let root = OctapusRoot(renderer: renderer, modules: [ClipboardModule()])
root.modules.register(ClipboardModule()) // takes effect on the next launchOctapusHostView and OctapusView register the built-ins Platform, Storage (scoped by storageScope) and Haptics by default. Pass builtinModules: false (or Options(builtinModules: false) on iOS) to opt out.
| Built-in | Members |
|---|---|
Platform | os, info(): { os, version, hostProtocol }, delay(ms): Promise<number> (async example) |
Storage | get(key), set(key, value), remove(key), keys(). JSON values in UserDefaults; not for secrets. |
Haptics | supported, impact(style?), notification(type?), selection() (a trackpad pattern on macOS) |
Generated TypeScript
Types are generated from the modules themselves, not written by hand. A root can write a machine-readable schema of its modules, including names, parameter types, return types, and sync/async kind:
# 1. Run the host app once with the schema path in the environment (Xcode scheme or shell):
OCT_NATIVE_SCHEMA=$PWD/native-modules.json swift run MyApp
# (or call root.modules.writeSchema(to: url) yourself)
# 2. Generate declarations into the app:
oct native types --schema native-modules.json --out src/native.d.tsFor the built-in modules, this produces:
// Generated by `oct native types` from ../native-modules.json. Do not edit; regenerate after changing a module.
import 'octapus-js/native';
declare module 'octapus-js/native' {
interface NativeModules {
Haptics: {
readonly supported: boolean;
impact(style?: 'light' | 'medium' | 'heavy' | 'soft' | 'rigid' | null): void;
notification(type?: 'success' | 'warning' | 'error' | null): void;
selection(): void;
};
Platform: {
readonly os: string;
info(): { os: string; version: string; hostProtocol: number };
delay(ms: number): Promise<number>;
};
Storage: {
get(key: string): unknown;
set(key: string, value: unknown): void;
remove(key: string): void;
keys(): string[];
};
}
}Adding a native function
The recipe is the same for people and for coding agents:
- Define the module. Run
oct native new Clipboard --dir ios/App --target Appto createClipboardModule.swiftfrom the template, along withClipboardModuleTests.swift. The test stub calls functions throughmodule.invoke("name", args), which runs without a JS runtime and uses the same conversion and errors as JS. Add or editFunction/AsyncFunction/Constantentries indefinition(). - Register it on the root:
OctapusHostView(modules: [ClipboardModule()]),OctapusView(..., modules: [...])orroot.modules.register(...). - Regenerate types: run the app once with
OCT_NATIVE_SCHEMA=…/native-modules.json, thenoct native types. Commitnative-modules.jsonandsrc/native.d.ts.
Rules:
- Sync bodies run on the JS thread, so hop to main for UI work.
- Settle each promise exactly once.
- Throw
OctapusModuleError(code:_:)for errors that JS should branch on. - Only JSON-like values cross the boundary. Use
OctapusRecordfor structured values,OctapusEnumfor string unions, andOctapusAnyfor untyped values.
Props and host events
Root component props come from the host. They are installed before the bundle runs, so the first render sees them:
host.launch(bundle, props: ["user": "ada"]) // macOS OctapusHostView
OctapusView(bundle: bundle, props: ["user": "ada"]) // iOS / SwiftUI
root.launch(bundle, props: ["user": "ada"]) // any rootexport function App(props) @{ <p>{'Hello ' + props.user}</p> }Events flow in both directions. root.send can be called from any thread, and root.on handlers run on the main thread:
root.send("deeplink", "myapp://pair?code=42") // host → JS
let sub = root.on("ready") { payload in … } // JS → host; sub.cancel()import { host } from 'octapus-js/native';
const off = host.on('deeplink', (url) => navigate(url)); // returns unsubscribe
host.emit('ready', { at: Date.now() });Batches that a host.on handler causes are applied like any other event. Events sent before hydration are delivered right after it. To type event payloads, augment HostEvents with declare module 'octapus-js/native' { interface HostEvents { deeplink: string } }.
Snapshots, props and native calls
The first-screen snapshot is baked at build time (oct build --bake) in a runtime that has no native modules and no props.
- A launch with props adopts the snapshot only if the first render is identical. Otherwise Octapus remounts, which is correct but slower. A first screen that depends on props needs a snapshot baked per prop set. On iOS, the on-device frame cache bakes from the real first mount.
- Native calls made during render fail the bake with a clear error, because render must not depend on them. Call them in effects and handlers, or guard them with
hasNative('Module'). Errors raised after the first commit, for example by a mount effect, are recorded as bake warnings and do not change the snapshot.
Web
On the web target there is no host. native.X.y() throws an error with code E_UNAVAILABLE unless you register a web implementation:
import { registerWebModule, hasNative } from 'octapus-js/native';
registerWebModule('Haptics', { impact() { navigator.vibrate?.(10); } });host.emit does nothing on the web, and host.props is {}.
C ABI (for other languages)
The Swift layer compiles down to a small C ABI in OctapusHermes, which can be reused for Rust and Kotlin hosts later. The relevant functions are oct_engine_define_function, oct_engine_define_async_function, oct_engine_define_value and oct_engine_settle, together with the oct_value accessors and constructors. A callback receives the arguments as an oct_value array and returns an owned oct_value, or sets *error to throw.
Cost
On an Apple Silicon Mac (release build, 100k calls), a no-op native call costs about 60–85 ns. A typed add(Int, Int) -> Int call costs about 330–430 ns including argument validation, and a plain JS function call costs about 5 ns. For tight loops, read rawNative (the installed object without validation) and keep a reference to the function.