Write a native plugin

A plugin is a capability the app reaches the same way on every platform: Bluetooth, NFC, a sensor, an OS API, a vendor's library. You describe it once, in a TypeScript file called the contract. The CLI writes the typed code on both sides of it — the wrapper your app calls and the frame of each platform's native part — and you fill in the native bodies.

Look through the first-party plugins first (the camera, the map, geolocation, push and others: API Reference, Plugins). This page is for what they do not cover.

The page follows one finished project, custom-plugin-app: an app with a plugin of its own, acme-battery, which reports the battery's charge and tells the app when it changes. Clone it and read along — the listings below are its files, shortened:

bash
git clone https://hub.le.codes/examples/custom-plugin-app.git

What a plugin is made of

A plugin is a folder. Its name is the plugin's id:

text
plugins/acme-battery/
  contract.d.ts           what the app can ask and hear — you write it
  lecodes-plugin.json     what each platform needs to build the plugin in — you write it
  sdk/                    the app's side: the generated wrapper, and your own layer over it
  ios/                    the iOS half (Swift)
  android/                the Android half (Kotlin), laid out as a Gradle module
  web/                    the web half (TypeScript)

A half is the native part for one platform. A plugin has the halves it needs: the example has an iOS and an Android half and no web/ folder, so it does not exist on the web.

A contract describes one of three channels:

channelforthe app gets
Serviceno pixels: a sensor, a device, background workcalls and events
Viewit draws its own pixels, full screen: a camera, a mapa destination to open, with the app's widgets over it
Host nodeit draws its own pixels in a box of a screen: a map in a cardan element among a screen's children

The example is a Service, the simplest of the three. Views and host nodes are at the end of the page.

Where your plugin runs

whereyour plugin
your own iOS or Android app (Native apps)yes — lecodes app sync builds it in
the project as a web page (lecodes web)yes, when it has a web half
the le.codes app (a QR code, lecodes dev on a phone)no — it carries the first-party plugins only
lecodes dev --web, headless render and testno
the desktopanother kind of plugin: Desktop plugins

So the app must work without the plugin. That is one check, shown in step 5: the app never asks which platform it is on, only whether the plugin is supported.

Step 1 — write the contract

Decide three things before any native code, because every half depends on them:

  • The name. Prefix it with your vendor: acme.battery. Bare names (camera, push) belong to the first-party plugins.
  • The methods. What the app asks. Plain data in, plain data out, one round trip each.
  • The events. What the native side sends without being asked.

plugins/acme-battery/contract.d.ts:

TypeScript
import type { Service, f64 } from "lecodes-sdk/plugin"

/** The battery as it is now. */
export interface BatteryStatus {
  /** How full it is, [0, 1]; -1 where the device does not say. */
  level: f64
  /** It is on the charger: charging, or full and still plugged in. */
  charging: boolean
}

export interface BatteryParams {}

export interface BatteryEvents {
  /** The level or the charging state changed. Sent while the app listens.
   *  @lazy */
  change: BatteryStatus
}

export interface Battery extends Service<"acme.battery", BatteryParams, BatteryEvents> {
  /** How full the battery is, [0, 1]; -1 where the device does not say. Never rejects. */
  level(): Promise<f64>
  /** Whether the device is on the charger. Never rejects. */
  charging(): Promise<boolean>
}
  • Service<name, Params, Events> marks the channel. name is what the halves register under.
  • A method returns a Promise. One that can fail lists its codes: /** @rejects unavailable busy */.
  • An event maps its name to its payload. @lazy means the half sends it only while the app listens, so nothing runs when nobody does. Use it for anything that ticks.
  • A number is f64 or i32, never number: the native side must know what it reads.

Everything a contract can say is in The plugin contract.

Step 2 — write the manifest

plugins/acme-battery/lecodes-plugin.json says what a platform needs to build the plugin in:

JSON
{
  "id": "acme-battery",
  "name": "Acme Battery",
  "version": "1.0.0",
  "sdk": "^2.0.0",
  "ios": { "register": "AcmeBatteryPlugin" },
  "android": { "register": "com.acme.lecodes.battery.AcmeBatteryPlugin" },
  "web": null
}

Each platform is always a key: an object where the plugin has a half, null where it has none. register names the type you will write in steps 3 and 4 — the one the app's shell calls at launch.

A half that needs an OS library, a Maven dependency, a usage string or an entitlement says so here: The plugin manifest.

Step 3 — generate, then write the iOS half

Create the folders of the halves you want, then generate:

bash
mkdir -p plugins/acme-battery/ios
mkdir -p plugins/acme-battery/android/src/main/java/com/acme/lecodes/battery
lecodes plugin gen plugins/acme-battery
text
acme-battery  service "acme.battery" v1
  written   sdk/acme-battery.gen.ts
  written   ios/Battery.gen.swift
  written   android/src/main/java/com/acme/lecodes/battery/Battery.gen.kt

A file is generated where its folder exists. Generated files end in .gen.*; commit them, never edit them. On Android the folder under src/main/java is the Kotlin package.

Battery.gen.swift now holds the contract's types (BatteryStatus), the events (BatteryEvents), the protocol to implement (BatteryPlugin) and the registration (BatteryChannel.register). Your part is two things. First, the type the manifest names — ios/AcmeBatteryPlugin.swift:

swift
import Foundation
import LeCodes

public enum AcmeBatteryPlugin {
    public static func register(in engine: LeCodesEngine) {
        // one BatteryService per session; nothing is read before its first call
        BatteryChannel.register(in: engine) { _, events in BatteryService(events) }
    }
}

Second, the session — ios/BatteryService.swift, here without its bookkeeping:

swift
public final class BatteryService: BatteryPlugin {
    private let events: BatteryEvents
    private var observers: [NSObjectProtocol] = []

    public init(_ events: BatteryEvents) { self.events = events }

    // A call: settle its reply exactly once.
    public func level(_ reply: Reply<Double, NoCode>) {
        reply.resolve(status().level)
    }

    public func charging(_ reply: Reply<Bool, NoCode>) {
        reply.resolve(status().charging)
    }

    // `change` is @lazy: start what produces it with the first listener, stop it with the last.
    public func changeObserved(_ observed: Bool) {
        if observed { observe() } else { stopObserving() }
    }

    private func observe() {
        let changed: (Notification) -> Void = { [weak self] _ in self?.send() }
        observers = [
            NotificationCenter.default.addObserver(forName: UIDevice.batteryLevelDidChangeNotification, object: nil, queue: .main, using: changed),
            NotificationCenter.default.addObserver(forName: UIDevice.batteryStateDidChangeNotification, object: nil, queue: .main, using: changed),
        ]
        send()   // the status it is in now: a new listener does not wait for a change
    }

    private func send() { events.change(status()) }

    public func close() { stopObserving() }
}

The rules of a half, on every platform:

  • Settle every call exactly once — reply.resolve(value) or reply.reject(.code), now or later. A call that is never settled leaves the app's promise waiting.
  • Creating a session is cheap. No dialog, no I/O, no hardware in the factory: that belongs to the first call that needs it. The app may open and close sessions freely.
  • close() stops everything the session started.
  • A call arrives on the main thread; a reply and an event may be sent from any thread.

Step 4 — the Android half

Battery.gen.kt holds the same things in Kotlin, and your part has the same two pieces. The object the manifest names — AcmeBatteryPlugin.kt:

kotlin
package com.acme.lecodes.battery

import android.content.Context
import io.letary.lecodes.LecodesEngine

object AcmeBatteryPlugin {
    fun register(engine: LecodesEngine, context: Context) {
        val appContext = context.applicationContext
        BatteryChannel.register(engine) { _, events -> BatteryService(appContext, events) }
    }
}

And the session — BatteryService.kt, shortened the same way:

kotlin
class BatteryService(private val context: Context, private val events: BatteryEvents) : BatteryPlugin {
    private var receiver: BroadcastReceiver? = null

    override fun level(reply: Reply<Double, NoCode>) {
        reply.resolve(statusOf(sticky()).level)
    }

    override fun charging(reply: Reply<Boolean, NoCode>) {
        reply.resolve(statusOf(sticky()).charging)
    }

    override fun changeObserved(observed: Boolean) {
        if (observed) observe() else stopObserving()
    }

    override fun close() {
        stopObserving()
    }
}

The android/ folder is a Gradle module, so the half's own AndroidManifest.xml is at android/src/main/AndroidManifest.xml. A <uses-permission> or a service of the half goes there; the example's is empty, because reading the battery needs no permission.

Step 5 — use it in the app

The generated sdk/acme-battery.gen.ts is the app's side: a class BatteryBase with the contract's methods and a typed on(event, …), and a function supports() that says whether this host has the plugin.

The example puts a small layer of its own over it, sdk/acme-battery.ts, so that the app has nothing to guard — on a host without the plugin every call answers "unknown" instead of failing:

TypeScript
import { BatteryBase, supports } from "./acme-battery.gen"
import type { BatteryStatus } from "../contract"

let client: BatteryBase | null = null
const service = (): BatteryBase => client ??= new BatteryBase()

export const AcmeBattery = {
  get supported(): boolean { return supports() },

  async level(): Promise<number> {
    if (!supports()) return -1
    return await service().level()
  },

  onChange(listener: (status: BatteryStatus) => void): () => void {
    if (!supports()) return () => {}
    const s = service()
    s.on("change", listener)
    s.level().catch(() => {})          // a listener alone does not open the session: a call does
    return () => { s.off("change", listener) }
  },
}

The app imports the wrapper by its path in the project:

TypeScript
import { AcmeBattery } from './plugins/acme-battery/sdk/acme-battery'

const level = UIText('Level: —')
UIScreen(
  UIText(AcmeBattery.supported ? 'The plugin is here.' : 'No battery plugin on this host.'),
  level,
).style({ p: 20, pt: 'safe-top', gap: 12 }).open()

AcmeBattery.onChange(s => { level.text = `Level: ${Math.round(s.level * 100)}%` })
  • supported is true where the host registered the plugin. It is the one check the app makes; with it, the screen renders everywhere.
  • A method is a promise. One that fails rejects with a code of the contract as the error's message.

The hand-written layer is optional. Without an sdk/acme-battery.ts, the generated file exports the finished object itself — Battery, with supported, the methods and on — and the app imports ./plugins/acme-battery/sdk/acme-battery.gen.

Step 6 — put it into your app

Name the folder in app.json. The key is the plugin's id:

JSON
{ "plugins": { "acme-battery": "./plugins/acme-battery" } }

lecodes app plugin add ./plugins/acme-battery writes the same line once the project has a shell. Then:

bash
lecodes app init android     # once: the shell
lecodes app sync             # the plugin's half is compiled into it
lecodes app build android

A plugin of the project needs no repository and nothing published.

A project that hub.le.codes builds gets its plugin built the same way, from the deployment. hub takes a plugin made of Swift and Kotlin sources and an AndroidManifest.xml only — no Gradle file, Swift package, dependency or binary; anything else is refused, and the build's log gives the reason.

Step 7 — test it

  1. Without the plugin. lecodes render and lecodes test have no native code, so they show what a host without the plugin shows. The screen must say so there, not fail.
  2. The native halves, in your own app on a phone: lecodes app sync, then build and run it from Xcode or Android Studio (lecodes app open).

Keep lecodes plugin gen --check in CI: it fails when a generated file no longer matches the contract.

Add a web half

The example has none. To give a plugin one, create web/, name its module in the manifest — "web": { "register": "web/acme-battery.ts" } — and run lecodes plugin gen again: it writes web/acme-battery.gen.ts. The half for this contract, over the browser's Battery Status API:

TypeScript
import { registerBattery, type BatteryPlugin, type BatteryStatus, type PluginHost } from "./acme-battery.gen"

type BatteryManager = EventTarget & { level: number, charging: boolean }
type BatteryNavigator = Navigator & { getBattery?(): Promise<BatteryManager> }

const statusOf = (battery: BatteryManager): BatteryStatus => ({ level: battery.level, charging: battery.charging })

/** What the manifest's `web.register` names: the page calls it once. */
export const register = (host: PluginHost): void => {
  const nav = navigator as BatteryNavigator
  // A browser without the Battery API registers nothing: `AcmeBattery.supported` is false there.
  if (!nav.getBattery) return
  const battery = (): Promise<BatteryManager> => nav.getBattery!()

  registerBattery(host, (_params, events): BatteryPlugin => {
    let watched: BatteryManager | null = null
    let listening = false
    const send = (): void => { if (watched) events.change(statusOf(watched)) }
    const stop = (): void => {
      listening = false
      watched?.removeEventListener("levelchange", send)
      watched?.removeEventListener("chargingchange", send)
      watched = null
    }

    return {
      // A call returns its result, or a promise of it.
      level: async () => (await battery()).level,
      charging: async () => (await battery()).charging,
      // `change` is @lazy: start what produces it with the first listener, stop it with the last.
      changeObserved(observed) {
        stop()
        if (!observed) return
        listening = true
        void battery().then((b) => {
          if (!listening) return
          watched = b
          b.addEventListener("levelchange", send)
          b.addEventListener("chargingchange", send)
          send()   // the status it is in now: a new listener does not wait for a change
        }, () => {})
      },
      close: stop,
    }
  })
}
  • On the web a call returns its result or a promise of it. A method with @rejects codes rejects by throwing the generated error class: throw new BatteryError("unavailable").
  • A web half is plain TypeScript of its own folder: it imports no package and no file outside the plugin's folder.
  • lecodes web dev and lecodes web build build the half with the project. lecodes test --lite runs the project's flow tests on that page, in a real browser.
Note

A project's web half is built with Bun. Use the standalone build of the CLI, or run the CLI with bun; a CLI running on Node says so and stops.

Change the contract later

Edit contract.d.ts, run lecodes plugin gen again, and the compiler of each half points at what is missing.

An app in the field may be newer than the native half inside an installed build. Tag a method that you add later with the contract version that introduced it:

TypeScript
  /** @since 2 */
  health(): Promise<f64>

The app asks before it calls: supports("health"). A call to a method the half is too old for rejects without reaching it.

Ask for a permission

A method that needs an OS permission says so, and the generated code asks before the call reaches your half:

TypeScript
  /** @permission microphone
   *  @rejects denied failed */
  record(): Promise<File>

When the user refuses, the app's promise rejects with denied; the half holds no dialog code. camera and microphone are built in. A permission of your own — Bluetooth, the calendar — is declared in the manifest, and lecodes plugin gen refuses a manifest without the usage string the dialog shows (The plugin manifest).

Share the plugin between projects

Put the plugin's folder at the root of a GitHub repository — lecodes-plugin.json at the top — and name it in another project's app.json:

bash
lecodes app plugin add github:acme/lecodes-battery@v1.0.0
  • The key in app.json must be the manifest's id. plugin add names the entry after the repository; rename it when the two differ.
  • @tag pins a version. Without one the newest v* tag is taken and written to plugins.lock.json; lecodes app update moves it.
  • While you develop the plugin itself, LECODES_PLUGINS_DIR=<checkout> makes sync take your working tree instead of the repository.

Draw pixels: a View or a host node

A plugin that shows something — a video player, a chart drawn by a native library, a scanner — declares a View, a host node, or both:

TypeScript
import type { View, UIHostNode, f64 } from "lecodes-sdk/plugin"

export interface PlayerParams { url?: string }
export interface PlayerEvents { ended: void }
export interface PlayerMethods { seek(seconds: f64): Promise<void> }

// full screen: the app opens it as a destination
export interface PlayerView extends View<"acme.player", PlayerParams, PlayerEvents>, PlayerMethods {}

// a box in a screen's layout: the app puts the generated element, PlayerNode, among a screen's children
export interface Player extends UIHostNode<"acme.player", PlayerParams, PlayerEvents>, PlayerMethods {}
  • A View's half is given the params the view is created with. On the app's side it is opened and pushed like a screen (NativeView).
  • A host node's half is given each prop as the app sets it. On the app's side it is an element with a setter per prop and an on… per event (Plugin nodes).
  • Both share their methods through a plain interface, as above.

The first-party plugins are the worked examples of both: the camera and the map are a View and a host node each. The plugin contract lists what a View and a host node add.

Replace one platform's half of a first-party plugin

A folder can implement the contract of a first-party plugin for one platform — your own web implementation of ar, say — while the first-party halves stay everywhere else. Its manifest says "implements": "ar", it has no contract.d.ts and no sdk/ of its own, and app.json names it for that platform:

JSON
{ "plugins": { "ar": { "web": "./plugins/ar-8thwall" } } }

lecodes plugin gen plugins/ar-8thwall writes web/ar.gen.ts from the contract the SDK carries.

Traps

  • Never make a screen require a plugin. Headless renders, flow tests and the le.codes app have none of yours, and that is where most of your feedback loop is.
  • The folder's name is the id, and the id is the key in app.json. A manifest whose id differs is refused.
  • lecodes plugin gen needs the typescript package, version 5. An npm or bun install of the CLI brings it. With the standalone build, add typescript@^5.8.3 to the project's dev dependencies.
  • Add @lazy when you add the event. An app built before the tag never says it listens, so tagging an event that apps already hear takes it away from them.
  • Do no work when a session is created. A dialog or I/O there makes every feature check expensive.

Next