Skip to content
Valence is in beta. The bundle format and update protocol are meant to stay stable; the CLI, the generated code and the two runtime packages’ APIs may still change. What beta means

Writing a Valence plugin

A plugin is a Dart package that owns native bridge handlers and a schema fragment, plus a matching npm package for web types. It is compiled into the store build. Adding native code or permissions still needs a store release. This guide follows contracts §4.10. Android is tested; iOS is experimental and untested.

Install its Dart package and npm types package, then list the fragment in valence/valence.config.json. Paths are relative to your project root. A package can publish the same fragment in its npm types package so it is easy to resolve:

{
"plugins": [
{ "path": "node_modules/@example/acme-scan/valence.plugin.json", "since": { "acmeScan.read": 3 } }
]
}

Run node valence/valence.mjs codegen, follow the plugin’s native setup notes, and register its Dart instance in your handler class:

class AppHandlers extends ValenceBuiltins implements BridgeHandlers {
AppHandlers(super.valence) : super(plugins: [AcmeScanPlugin()]);
}

Call its methods through your app’s generated bridge.g.ts. The generated types include plugin methods and events. Use has('acmeScan.read') on hosts older than the plugin’s since, and supply an installShim fallback for the browser. Registration alone exposes no methods: dispatch has only the cases in the schema. Regenerated handlers emit hostPluginNamespaces (including event-only fragments) and hostPluginMethods. Constructing ValenceBuiltins checks both with ValencePluginRegistry.checked. A missing plugin or exact method registration throws StateError naming the fix in debug, profile and release builds, before the handlers can serve a page. Extra registered methods remain unreachable. Older generated handlers keep their previous behavior until you regenerate.

Add a host test that constructs your real AppHandlers before shipping. Doctor’s native plugin registration row lists requirements as a warning; it cannot prove which instances Dart constructs. The startup check verifies declarations, not native initialization, permissions or successful platform behavior. Direct registry callers without generated requirements retain E_UNSUPPORTED for missing methods.

After upgrading the tooling or bridge package, regenerate and run your web TypeScript build. The generated client supplies both method and event capability tables; a matching CLI/bridge snapshot pair is required. An unchanged version string alone does not establish that the snapshots are compatible.

The app owns its combined schema version. Bump it for a new plugin capability and use a since above every shipped host. For example, when the app was at version 2, set the app to version 3, stamp "acmeScan.read": 3 in the plugins entry above, and publish this fragment:

{
"namespace": "acmeScan",
"dartPackage": "acme_scan",
"npmPackage": "@example/acme-scan",
"setup": "README.md",
"types": { "AcmeScanResult": { "value": "string" } },
"methods": {
"acmeScan.read": { "params": {}, "returns": "AcmeScanResult?" }
},
"events": {}
}

Use one lower-camel namespace and prefix every method/event with it. Types use the PascalCase namespace followed by an uppercase suffix: AcmeScanResult. Fragments reference only their own named types. Duplicate namespaces and any collision with the app are errors, including identical definitions. Core names such as app, data, secure, open, notify, http and share are reserved; the full list is ValencePluginRegistry.reservedNamespaces. Unknown fragment fields fail validation. Package and setup metadata are descriptions, not executed imports.

Codegen, bundle and doctor merge fragments before checking the recorded store baseline. Editing or removing shipped definitions fails the additive-only guard. Introduce a new method instead. A plugin’s since is an app bridge version, not its pub/npm package version; coordinate it when adding the fragment to an app.

since is an app bridge version, so no published fragment can carry one number that is right for every app installing it. An app that has already shipped a store build needs every new method’s since above its own recorded baseline, and a fragment inside a pub package sits in ~/.pub-cache, where you cannot edit it. So a published fragment declares no since at all, and the app stamps it in its plugins entry:

"plugins": [
{ "path": "plugins/acme-scan/valence.plugin.json", "since": { "acmeScan.read": 3 } }
]

The two forms are exclusive per entry. With since present the fragment must declare none and the stamp must name every method and event in it; without it the fragment declares its own, as before. A stamp naming something the fragment does not declare is an error, so a renamed method cannot leave a number behind. The merged schema holds the resolved number, so your recorded store baseline freezes it and re-stamping after a store build is rejected like any other change. When the plugin’s next version adds a method, codegen tells you to add it to the entry — which is the app owning its own schema version, mechanically.

final class AcmeScanPlugin implements ValencePlugin {
@override
String get namespace => 'acmeScan';
@override
Set<String> get methods => const {'acmeScan.read'};
@override
Future<Object?> invoke(
Valence valence, String method, Map<String, Object?> params,
) async {
if (method != 'acmeScan.read') {
throw const BridgeError(BridgeErrorCode.unsupported, 'unknown scan method');
}
// Replace this fixture value with your platform API after permission checks.
return {'value': 'example'};
}
}

Return JSON maps/lists/primitives, not generated Dart model instances. Generated adapters decode results against the IDL before replying. The normal nonce check, strict parameter decoding and message/reply caps apply. Native errors can use BridgeError; other exceptions become E_INTERNAL. Malformed typed results fail with E_INTERNAL and are never sent as successful values. Invalid arguments still fail with E_PARAMS before invocation; errors thrown by the plugin keep their original code.

The plugin owns initialization, permission prompts, subscriptions and cleanup. Initialize it before registering it; dispose resources through your app lifecycle. For events, wire your native callback to the generated BridgeEvents builder and pass its script to valence.emit. Only schema-declared events get builders. The registry does not create background jobs or manage plugin lifecycle.

Plugins are trusted native code with host privileges. Review them like any native dependency. Keep scheme/origin restrictions and secret rules in native handlers; never bind the registry itself as a raw WebView channel or return secrets to JS.

Valence.dataPut checks writable buckets and dot keys at the page boundary. A native plugin calling valence.store.put bypasses those checks and owns sync correctness. Ordinary pref/secure APIs still refuse valence. keys for native callers, and openExternal still checks its scheme allowlist. Explicit host-pref and token APIs, plus the public database handle, are privileged escape hatches; they must never be exposed to the page.

Only the generated bridge.g.ts is checked against the merged schema. The plugin’s separately published npm types are hand-maintained; codegen does not verify them. The generated-Dart gate compares the CLI’s exported PLUGIN_RESERVED with ValencePluginRegistry.reservedNamespaces. Refresh vendored tooling and regenerate when upgrading the runtime.

The npm types package can export this shape for shim authors. Calls still go through the generated client, which owns nonce handling and capability checks:

export interface AcmeScanMethods {
'acmeScan.read': {
params: Record<string, never>;
returns: { value: string } | null;
};
}

Ship valence.plugin.json alongside those types. Test the types against the merged generated client under strict TypeScript and verbatimModuleSyntax.

The framework’s packages/valence/example/plugins/haptics is a complete local Dart package, schema fragment, npm types package and native setup guide. The example registers it and calls the real haptic platform channel. Its existing haptics.tap method keeps since 1 because only its implementation moved.

The built-in open.external also uses ValencePlugin: ValenceOpenPlugin delegates to the existing native scheme allowlist. Its reserved owner cannot be replaced. Test plugins on Android, run the generated-code and runtime gates, and label any iOS path experimental until tested on Apple hardware.

Distribution is ordinary publishing — pub.dev for the Dart half, npm for the web types — and there is no remote installer, resolver or marketplace: plugins[].path always names a file already on disk. The plugin directory lists what exists today, including the add-on packages that implement a core namespace instead of declaring one, and what a package needs before it is listed.