Native features: spec first
Write one TypeScript spec for a native feature, implement the Swift, Kotlin, Rust and web contracts generated from it in one task with the same tests, and let the build check every platform against it.
When your app needs something only native code can do, write its spec first, as a TypeScript file. That file is the single source of truth. BakeNative generates a contract from it for each language (a Swift protocol, a Kotlin abstract class, a Rust trait, a typed web object), you implement those contracts, and the compiler and bake check fail when a platform no longer matches. Build every platform in one task. Use a third-party native library only when building it yourself is not practical.
Who does what. An agent writes the implementations (each language's body and its tests); people review the spec and the result. Machine checks decide when it is done: the generated contracts compile, the same tests pass on every platform, and bake check / bake build --json report "ok": true. The agent never edits the spec; it proposes a platform difference as an @platform line for people to accept.
The API itself is in Native modules. Ready-made modules (clipboard, haptics, linking, share) come from the registry with bake add and follow the same layout.
Why spec first
A third-party native library costs more than it looks:
- It behaves differently per platform. The iOS and Android halves are often separate projects with separate bugs, defaults and error shapes. Your JS has to know about both.
- It is duplicated across app packages. Two app packages that carry the same library break one host (duplicate symbols, merge conflicts). Each one must be declared and resolved as
sharedorisolated(Third-party libraries). - It is outside your OTA contract. A bundle runs only when the installed app provides every native member it uses (requires ⊆ provides, OTA compatibility). A library update you do not control can change what the app provides.
A module you write from one spec avoids all three:
- One API, one behavior. The spec fixes the names, types, errors and sync or async kind. Every platform implements a contract generated from it, so a missing or mistyped member does not compile.
- One source of truth. The JS types (
src/native.d.ts), the schema and the member signatures the OTA check compares all come from the spec, never from a host. There is nothing to compare between platforms afterwards. - Agents do it well. A spec plus test scenarios is a complete task. An agent can implement every platform in one pass, run the same tests on each, and finish with
bake check.
The workflow
1. Write the spec
bake native new starts a module with its spec and one implementation per target:
bake native new Vibration --specIt writes native/vibration/Vibration.native.ts and, next to it, an implementation for each target in bake.config.ts with its tests: Vibration.swift (iOS and macOS), Vibration.kt, vibration.rs, Vibration.web.ts. --platform ios|macos|apple|android|windows|web keeps one; --target is the Kotlin package. (--spec is the default; every module is spec first.)
Replace the example members with yours. The interface is the JS surface; the doc comments say what types cannot: errors (@throws), ranges, platform differences (@platform) and the test scenarios.
// native/vibration/Vibration.native.ts: the source of truth for native.Vibration.
import type { NativeModule } from '@bake-native/octane';
/**
* Plays vibration patterns.
* @platform ios One impact per on-segment: iOS cannot hold a vibration for a given length.
* @throws E_PATTERN an empty pattern, more than 32 entries, or an entry outside 0 to 10000
*
* Tests: [200, 100, 200] plays [200, 100, 200]. [-1] throws E_PATTERN. ["x"] throws E_ARGUMENT.
*/
export interface Vibration extends NativeModule {
/** True when the device can vibrate. */
readonly supported: boolean;
/** Plays on, off, on, … durations in milliseconds. */
vibrate(pattern: number[]): void;
}The one interface that extends NativeModule is the module; other exported interfaces are records and exported string unions are enums. Promise<T> makes a member async, readonly makes it a constant, p?: T is optional and Int is an integer. Callbacks, ArrayBuffer and returning a module instance are build errors that name the line (The spec).
2. Let the build generate the contracts
bake build (and bake native gen on its own) turns the spec into a contract per language, in .bake/native/<target>/, on every build. You never edit or commit them:
| Language | Contract | Async member |
|---|---|---|
| Swift | protocol VibrationSpec: BakeNativeModule | func f() async throws -> T |
| Kotlin | abstract class VibrationSpec : BakeNativeSpecModule | abstract suspend fun f(): T |
| Rust | trait VibrationSpec, vibration_module(value) | fn f(&self) -> Result<T, ModuleError> (on a worker thread) |
| Web | the spec's own type: const web: Vibration = { … } | returns a Promise |
The generated code does what used to be written by hand: argument conversion and E_ARGUMENT, thread hops, promises, error labels, and the registration (BakeNativeBundleModules).
3. Implement every platform in one task
Give all the implementations to one person or one agent, so they cannot drift apart. Each one is a plain class that conforms to the contract. Its dependencies are constructor parameters, so tests can replace the hardware. See the example below.
- Sync members run on the JS thread. Queue UI work on main and return; never wait for main.
- Async members run on a background thread:
@MainActorin Swift,withContext(Dispatchers.Main)in Kotlin, the host's UI post in Rust for UI work. - Errors: throw
BakeNativeModuleError(Swift, Kotlin) or returnModuleError::new(Rust) with the spec's@throwscodes.
4. Write the same tests on every platform
module.invoke(...) and invokeAsync(...) (invoke_async in Rust) call a member without a JS runtime, through the generated glue: the same argument conversion and error labels JS gets. bake native new starts each test file for you.
Write the scenarios once, as native/<name>/<Name>.scenarios.json next to the spec, and run that one file on every platform:
{ "cases": [
{ "call": "vibrate", "args": [[200, 100, 200]], "ok": true },
{ "call": "vibrate", "args": [[]], "code": "E_PATTERN" },
{ "call": "vibrate", "args": ["x"], "message": "Vibration.vibrate: argument 0: expected number[], got string \"x\"" }
] }A case is taken (ok), returns a value (returns, compared as JSON), or is rejected with code and / or message (a message alone means E_ARGUMENT); "async": true awaits the promise. Swift runs it with try await BakeNativeScenarios.run(VibrationModule(play: { _ in }), file: url), Kotlin with BakeNativeScenarios.run(VibrationModule { }, json), Rust with bake_runtime::modules::run_scenarios(module.as_ref(), json), the web with runScenarios(native.Vibration, json) from @bake-native/octane/testing/native-scenarios; each returns the cases that differ (empty: all pass).
5. Pass it to the screen
bake build generates BakeNativeBundleModules.root(...) with one parameter per app module the bundle calls, typed by its contract. A module the bundle calls unguarded is a required parameter, so a host that forgets it does not compile:
BakeNativeView(bundle: bundle, modules: BakeNativeBundleModules.root(vibration: VibrationModule()))bakeNativeView.modules.registerAll(BakeNativeBundleModules.root(vibration = VibrationModule(vibrator)))A module from bake add needs no parameter: the generated code creates it. Windows takes bundle_modules::root(...) in the generated crate; the web build loads Vibration.web.ts before the app. See Registering modules.
6. Run bake check
bake native types # src/native.d.ts from the specs, for your editor and tsc
bake check # every target in bake.config.ts, without writing bundlesbake check runs the fail-closed checks of bake build for each declared target. For modules it fails when:
- a spec does not parse or uses a type a module cannot carry (the line and what to write instead);
- the app calls
native.Xand there is no spec for it (native/x/X.native.ts,bake native new X); - the app calls a module that has no implementation for a target it builds (
module-<name>): write the file, or branch onimport.meta.env.BAKE_TARGETaround the call; - an implementation does not adopt the contract (
VibrationModule: VibrationSpec,class VibrationModule : VibrationSpec(),impl VibrationSpec for …) or lacks one of the spec's members (module-spec-<name>, with the contract's line for it). This check reads the files, so it runs on a machine that cannot compile them:bake check --target ios,androidon Windows or Linux.
A member an implementation types differently is a compile error in that platform's build, because the contract is generated from the spec. In an app package, provides.native lists each member's signature from the spec, and bake release check refuses an OTA bundle whose calls no longer match.
Example: Vibration
The spec from step 1. Each platform takes the function that really vibrates as a constructor parameter, so the tests can replace it.
Swift (native/vibration/Vibration.ios.swift, iOS only):
import UIKit
import BakeNativeKit
public final class VibrationModule: VibrationSpec {
private let play: ([Double]) -> Void
public init(play: @escaping ([Double]) -> Void = VibrationModule.impacts) { self.play = play }
public var supported: Bool { true }
/// Sync: called on the JS thread. Validates, then queues the UI work on main.
public func vibrate(pattern: [Double]) throws {
guard !pattern.isEmpty, pattern.count <= 32, pattern.allSatisfy({ (0...10_000).contains($0) }) else {
throw BakeNativeModuleError(code: "E_PATTERN", "pattern: 1 to 32 durations, each 0 to 10000 ms")
}
play(pattern)
}
/// One impact per on-segment, on the main thread (the spec's platform difference).
public static func impacts(_ pattern: [Double]) {
DispatchQueue.main.async {
var at = 0.0
for (i, ms) in pattern.enumerated() {
if i.isMultiple(of: 2) {
DispatchQueue.main.asyncAfter(deadline: .now() + at / 1000) {
UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
}
}
at += ms
}
}
}
}Kotlin (native/vibration/Vibration.kt):
package com.example.app
import android.os.VibrationEffect
import android.os.Vibrator
import dev.bakenative.generated.VibrationSpec
import dev.bakenative.modules.BakeNativeModuleError
class VibrationModule(private val play: (List<Double>) -> Unit) : VibrationSpec() {
/** The real vibration. A waveform starts with an off segment, the spec with an on one. */
constructor(vibrator: Vibrator) : this({ pattern ->
val timings = longArrayOf(0) + pattern.map { it.toLong() }.toLongArray()
vibrator.vibrate(VibrationEffect.createWaveform(timings, -1))
})
override val supported = true
// Sync: called on the JS thread.
override fun vibrate(pattern: List<Double>) {
if (pattern.isEmpty() || pattern.size > 32 || pattern.any { it < 0 || it > 10_000 })
throw BakeNativeModuleError("E_PATTERN", "pattern: 1 to 32 durations, each 0 to 10000 ms")
play(pattern)
}
}Web (native/vibration/Vibration.web.ts):
import { registerWebModule } from '@bake-native/octane';
import type { Vibration } from './Vibration.native';
const web: Vibration = {
supported: typeof globalThis.navigator?.vibrate === 'function',
vibrate(pattern) {
if (!pattern.length || pattern.length > 32 || pattern.some((ms) => !(ms >= 0 && ms <= 10_000)))
throw Object.assign(new Error('Vibration.vibrate: pattern: 1 to 32 durations, each 0 to 10000 ms'), { code: 'E_PATTERN' });
globalThis.navigator?.vibrate?.(pattern);
},
};
registerWebModule('Vibration', web);No Windows file: an app that targets Windows and calls native.Vibration fails bake check (module-vibration) until it has vibration.rs or guards the call.
JS (typed by bake native types):
import { native } from '@bake-native/octane';
if (native.Vibration.supported) native.Vibration.vibrate([200, 100, 200]);The same three tests on every platform:
final class VibrationModuleTests: XCTestCase {
func testPlaysAValidPattern() throws {
var played: [Double]?
_ = try VibrationModule(play: { played = $0 }).invoke("vibrate", [[200.0, 100.0, 200.0]])
XCTAssertEqual(played, [200, 100, 200])
}
func testRejectsANegativeDuration() {
XCTAssertThrowsError(try VibrationModule(play: { _ in }).invoke("vibrate", [[-1.0]])) {
XCTAssertEqual(($0 as? BakeNativeModuleError)?.code, "E_PATTERN")
}
}
func testRejectsANonNumber() {
XCTAssertThrowsError(try VibrationModule(play: { _ in }).invoke("vibrate", [["x"]])) {
XCTAssertEqual(($0 as? BakeNativeModuleError)?.code, "E_ARGUMENT")
}
}
}class VibrationModuleTest {
@Test fun playsAValidPattern() {
var played: List<Double>? = null
VibrationModule { played = it }.invoke("vibrate", listOf(200.0, 100.0, 200.0))
assertEquals(listOf(200.0, 100.0, 200.0), played)
}
@Test fun rejectsANegativeDuration() {
val e = assertThrows(BakeNativeModuleError::class.java) { VibrationModule {}.invoke("vibrate", listOf(-1.0)) }
assertEquals("E_PATTERN", e.code)
}
@Test fun rejectsANonNumber() {
val e = assertThrows(BakeNativeModuleError::class.java) { VibrationModule {}.invoke("vibrate", listOf("x")) }
assertEquals("E_ARGUMENT", e.code)
}
}Hand it to an agent
Copy this into the task, with your spec in place of the example. It covers the whole loop: spec, every platform, the same tests and the check. See Working with AI agents for the general setup.
Implement the native module native/vibration/Vibration.native.ts on every target in bake.config.ts,
in this one task. The spec is the source of truth: do not change it to fit an implementation.
1. Scaffold: `bake native new Vibration --spec` (spec, one implementation per target, tests).
Keep the spec's members; replace the example implementations.
2. Implement the generated VibrationSpec in Swift, Kotlin and Rust, and the spec's type in
Vibration.web.ts. Never write registration or argument conversion: the build generates them.
Sync members are called on the JS thread: queue UI or hardware work on main and return, never
wait for main. Async members (Promise in the spec) run on a background thread: @MainActor
(Swift), withContext(Dispatchers.Main) (Kotlin) for UI work. Throw BakeNativeModuleError /
return ModuleError with the spec's @throws codes.
3. Take the hardware call as a constructor parameter, so tests run without a device.
4. Write the spec's test scenarios as XCTest, JUnit and Rust tests with invoke / invokeAsync.
Run them. Every scenario passes on every platform.
5. Pass the module to the screen on each host: BakeNativeBundleModules.root(vibration: ...).
6. Run `bake native types`, call it from the app (in an effect or handler, never during render:
the bake has no native modules) and run `bake check --json`. Done means "ok": true.
7. Report any platform difference you could not avoid. Propose it as an @platform line for the
spec; do not add it yourself. The team decides.Native views
A platform view (a map, a payment button, a camera preview) follows the same rule: one spec, a
generated base per platform, and only the implementation written by hand. <video> is not one of
them: it is a built-in element of the core (Video).
- The spec is
native/views/<Name>.native.ts, TypeScript like a module's: one interface that extendsNativeView, whose optional fields are props (/** @default 3 */ zoom?: number),onX(event: T): voidmethods events (@throttle 250) and methods returning aPromisecommands; the interface's JSDoc gives@roleand@size <w> <h> [reports](or@size css). Prop and parameter types arestring,number,booleanand string unions; a payload is a record of those. (A<Name>.view.jsonfrom before still works and gives the same view.) bake native view gen <spec>writes the JS component and its types, the web custom-element base, and a base per platform: a Swift class (iOS and macOS), a Kotlin class, a Rust trait, and the commands' JSI glue. Props and events cross as typed values numbered by slot, never JSON. In a React app, import the named component and its ref type from../native/views/generated/<Name>.js. PassclassNameor a React style object to style its box. React apps that list only native targets inbake.config.tscan omit<Name>.web.js. In an Octane app, import<Name>.tsrx.--checkfails on a stale file.- You write the setters, the command bodies and the
emitcalls, in a class that subclasses the generated base. - The box is the view's. In the tree the view is a replaced element (
bake-<name>), laid out by CSS like<img>. Its accessibility (role and label) and input are the box's; the platform view's own accessibility tree is not exposed yet. The first screen shows a sized placeholder until the view attaches. - Only what the bundle uses is linked (
requires.views), checked bybake checklike modules. - Your own views go in
native/views/(<Name>.native.ts,generated/,<Name>.web.js) with their platform implementation wherepackage.jsonsays:"bakenative": { "views": { "Swatch": { "apple": "native/views/apple" } } }. On iOS and macOS the generated registration package compiles the view and registers it; the host passesBakeNativeAppViews.views()toBakeNativeView.examples/native-viewis one.
When you need a third-party library
Some features are not practical to write yourself (a payment SDK, a video codec, a vendor's login). Then use the library, and declare it:
- Wrap it in your own module with a spec, so JS sees your API and your error codes, not the library's.
- Declare the library in the app package as
shared(one copy, linked by the host) orisolated(the package's own renamed copy, Java/Kotlin,.soand C only).bake package checkandbake package host-checkcheck the declarations (Third-party libraries). - Bump
nativeBuildwhen the library's behavior changes behind the same signatures, so older OTA bundles are refused (Escape hatches).
Not there yet
- Callbacks and instances. A spec cannot take a function or return a native object. Native → JS is an event the spec declares (
onX(listener): Unsubscribe) or a host event. - The Vibration example is not in the repository. It shows the shape of a module; no app builds it on iOS and Android yet.
- Native views. iOS and macOS register app-declared views. Android supports props and events and rejects app-declared views with commands at build time. Windows registration is pending. The platform view's own accessibility tree is not exposed. To package these views, use
bake build --xcframework --embed-runtime. The runtime-separate xcframework and app packages do not include them yet.
System modules
Clipboard, Linking, Share and Haptics — registry modules an app adds with bake add, one API on every target.
Native UI
The three UI packages of BakeNative - Universal (@bake-native/react/ui), SwiftUI (@bake-native/react/ui/swift-ui) and Jetpack Compose (@bake-native/react/ui/jetpack-compose) - and which one to use.