Skip to content
FeliksLv01Public

About

Protocol-first, contract-driven RPC framework sharing one Swift/Kotlin native service layer across Flutter (FFI + Binary), React Native (TurboModule + C++ JSI), and WebView.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

NativeRPC

NativeRPC is a protocol-first, SDK-isolated RPC framework with standalone native SDKs for iOS (pure SwiftPM + Swift Macros) and Android (Kotlin + KSP auto-registration), pluggable connection layers (Flutter FFI + BasicMessageChannel, React Native TurboModule + optional C++ JSI binary bridge, WebView bridge, or custom transports), and a TypeScript contract code generator.

Key Features

  • Protocol-First & High-Performance Binary Fast-Path: Simplified JSON-RPC 2.0 wire protocol (single-pass JSON parsing across all connections) paired with a zero-dependency Positional Binary Codec routed through the same NativeRPCStub, interceptors, and service lifecycle
  • Standalone Native SDKs: iOS (NativeRPCKit) and Android (com.nativerpc) have zero Flutter/RN runtime dependencies
  • Compile-Time Service Auto-Registration:
    • iOS: @RPCServiceRegister("serviceName") Swift Macro (Member + Peer macro) + Mach-O section scanning via NativeRPCServiceCenter.shared.autoScan()
    • Android: @RPCServiceRegister("serviceName") + @RPCServiceRegistryRoot KSP processor generating NativeRPCGeneratedServiceRegistry.registerAll()
  • Pluggable Connections:
    • Flutter (native_rpc_flutter): dart:ffi + Positional Binary fast-path (sync & async via 6 fixed C ABI symbols on iOS SwiftPM and Android JNI/CMake) with automatic fallback to BasicMessageChannel<String?> (native_rpc), ref-counted event streams, waitForUser, and Android NativeRPCHost
    • React Native (@nativerpc/react-native): New Architecture TurboModule with caller-thread sync methods, async RPC, scoped events, unified RN/FFI scope, and an optional single-channel C++ JSI binary bridge (__nativeRPCBinary) with per-method FNV-1a layout hash verification
    • WebView (@nativerpc/web + WebViewNativeRPCConnection / WebViewNativeRPCBridge): Direct JSON-RPC bridge for WKWebView and Android WebView with iframe frameId routing
    • Custom: Subclass NativeRPCConnection for WebSocket, IPC, or in-memory testing
  • Declarative DSL & Strict Concurrency: Expo Modules-style DSL with Swift 6 strict concurrency (@MainActor by default + BackgroundAsyncFunction + CallerFunction) and Kotlin coroutines + kotlinx.serialization
  • Unified Contract Codegen (nativerpc-codegen): Generate strongly typed Dart, Swift, Kotlin, TypeScript, and optional C++17 schema descriptors (cpp) plus JSON manifest from a single TypeScript schema (binaryCodec enabled by default for Dart/Swift/Kotlin)

Installation & Integration

NativeRPC is currently consumed from a local git clone (no tagged releases or npm / pub.dev packages are published yet). Clone this repository first and integrate directly from your local checkout (path/to/NativeRPC):

git clone https://github.com/FeliksLv01/NativeRPC.git

iOS (Pure Swift Package Manager)

Reference the local repository root Package.swift (Swift 6.0+, iOS 15+ / macOS 12+; sdk/ios/Package.swift is also available for the standalone iOS package):

dependencies: [
    .package(path: "path/to/NativeRPC")
]

Add the NativeRPCKit library product to your target (SwiftPM derives the package identity from the last path component, "NativeRPC" for path/to/NativeRPC). Targets that use @RPCServiceRegister must enable SymbolLinkageMarkers:

.target(
    name: "MyApp",
    dependencies: [
        .product(name: "NativeRPCKit", package: "NativeRPC"),
    ],
    swiftSettings: [
        .enableExperimentalFeature("SymbolLinkageMarkers"),
    ]
)

Verify locally from the cloned repository root (or inside sdk/ios):

swift test

Android (Gradle + KSP)

Include the SDK and KSP processor modules from your local clone in settings.gradle.kts:

include(":nativerpc-sdk")
project(":nativerpc-sdk").projectDir = file("path/to/NativeRPC/sdk/android")

include(":nativerpc-processor")
project(":nativerpc-processor").projectDir = file("path/to/NativeRPC/sdk/android/processor")

Configure dependencies in your module's build.gradle.kts:

plugins {
    id("org.jetbrains.kotlin.plugin.serialization")
    id("com.google.devtools.ksp")
}

dependencies {
    implementation(project(":nativerpc-sdk"))
    ksp(project(":nativerpc-processor"))
}

Flutter (native_rpc_flutter)

Add a local path dependency to pubspec.yaml:

dependencies:
  native_rpc_flutter:
    path: path/to/NativeRPC/connections/flutter/native_rpc_flutter
  • iOS: Integrated via Flutter Swift Package Manager (connections/flutter/native_rpc_flutter/ios/native_rpc_flutter/Package.swift), which resolves NativeRPCKit directly from the local repository root (../../../../..).
  • Android: Include :nativerpc-sdk (path/to/NativeRPC/sdk/android, and :nativerpc-processor at path/to/NativeRPC/sdk/android/processor if using KSP) in your app's android/settings.gradle.kts (see connections/flutter/native_rpc_flutter/example/android/settings.gradle.kts).

Verify the plugin locally:

cd connections/flutter/native_rpc_flutter
flutter pub get
flutter analyze
flutter test

Web (@nativerpc/web)

@nativerpc/web is not published to npm; it is managed in this repository's pnpm workspace (pnpm-workspace.yaml -> connections/web). Install, build, and verify from the cloned repository root:

pnpm install
pnpm --filter @nativerpc/web build
pnpm --filter @nativerpc/web test
pnpm --filter web-counter build
  • Inside a pnpm workspace (as in examples/web-counter/package.json): depend on "@nativerpc/web": "workspace:*".
  • From a standalone local web project: build connections/web first so connections/web/dist/ is generated, then depend on "@nativerpc/web": "file:path/to/NativeRPC/connections/web".

Protocol

NativeRPC uses a simplified JSON-RPC 2.0 wire format (without the jsonrpc field):

  • Call: {"id":"1","method":"counter.add","params":{"value":5}}
  • Result: {"id":"1","result":5}
  • Error: {"id":"1","error":{"code":-32601,"message":"Method not found"}}
  • Subscribe: {"id":"2","method":"rpc.subscribe","params":{"event":"counter.countChanged"}}
  • Unsubscribe: {"id":"3","method":"rpc.unsubscribe","params":{"event":"counter.countChanged"}}
  • Event Notification: {"method":"counter.countChanged","params":{"count":5}}

Quick Start

1. Define a Service on iOS (Swift + Macro)

import NativeRPCKit

struct AddParams: Codable, Sendable {
    let value: Int
}

@RPCServiceRegister("counter")
final class CounterService: NativeRPCService {
    private var count = 0

    @ServiceDefinitionBuilder
    override func definition() -> ServiceDefinitionContainer {
        Function("increment") { () -> Int in
            self.count += 1
            self.emit("countChanged", data: ["count": self.count])
            return self.count
        }

        AsyncFunction("add") { (params: AddParams) async throws -> Int in
            self.count += params.value
            self.emit("countChanged", data: ["count": self.count])
            return self.count
        }

        Events("countChanged")
    }
}

// At app startup:
NativeRPCServiceCenter.shared.autoScan()

2. Define a Service on Android (Kotlin + KSP)

package com.example.app

import com.nativerpc.core.NativeRPCContext
import com.nativerpc.core.NativeRPCService
import com.nativerpc.core.RPCServiceRegister
import com.nativerpc.core.RPCServiceRegistryRoot
import com.nativerpc.dsl.serviceDefinition
import com.nativerpc.generated.NativeRPCGeneratedServiceRegistry
import kotlinx.serialization.Serializable

@Serializable
data class AddParams(val value: Int)

@RPCServiceRegister("counter")
class CounterService : NativeRPCService() {
    private var count = 0

    override fun definition() = serviceDefinition {
        Function<Int>("increment") {
            count++
            emit("countChanged", mapOf("count" to count))
            count
        }
        AsyncFunction<AddParams, Int>("add") { params ->
            count += params.value
            emit("countChanged", mapOf("count" to count))
            count
        }
        Events("countChanged")
    }
}

// At app startup (annotated with @RPCServiceRegistryRoot):
@RPCServiceRegistryRoot
class AppRegistry {
    fun init() {
        NativeRPCGeneratedServiceRegistry.registerAll()
    }
}

3. Call from Flutter (Dart)

import 'package:native_rpc_flutter/native_rpc_flutter.dart';

// Generated typed clients call NativeRPCClient.shared directly, or use NativeRPC facade:
final next = await NativeRPC.call<int>('counter.increment');

// Stream-based events (auto-subscribes on first listener, unsubscribes on last cancel)
final sub = NativeRPCClient.shared.events('counter.countChanged').listen((data) {
  print('Count changed: $data');
});

// Interactive calls (e.g. picker / permission prompt) without execution timeout
final picked = await NativeRPCClient.waitForUser(() => NativeRPCClient.shared.call('media.pick'));

// Clean up
await sub.cancel();
await NativeRPCClient.shared.dispose();

4. Call from WebView (TypeScript)

import { NativeRPC } from '@nativerpc/web';

await NativeRPC.ready();
const count = await NativeRPC.call<number>('counter.increment');

const onChanged = (data: { count: number }) => console.log('Count:', data.count);
NativeRPC.on('counter.countChanged', onChanged);
// Later:
NativeRPC.off('counter.countChanged', onChanged);
NativeRPC.dispose();

Native WebView attachment:

  • iOS: let connection = WebViewNativeRPCConnection(webView: webView, rootViewController: self) (call connection.close() on @MainActor when done)
  • Android: val bridge = WebViewNativeRPCBridge(webView, activity = this).apply { attach() } (call bridge.detach() in onDestroy())

Logging & Interceptors (iOS)

import NativeRPCKit

NativeRPCLog.handler = { level, message in
    print("[\(level)] \(message)")
}
NativeRPCServiceCenter.shared.addInterceptor(NativeRPCLoggingInterceptor(logLevel: .info))

Contract Code Generation

Generate strongly typed Dart clients, Swift/Kotlin protocols and bindings, and a JSON manifest from TypeScript interfaces:

cd codegen
pnpm install
pnpm run build
node bin/native-rpc-codegen.js generate --config examples/config.json
node bin/native-rpc-codegen.js check --config examples/config.json

See codegen/README.md for the full contract specification, JSDoc tags (@shouldExport, @serviceName, @rpcKind events, @platforms, @iosExecution, @androidExecution, @example, @minVersion), and CLI commands (generate, check, scan).

Error Codes

Code Name Scope
-32700 Parse error Standard JSON-RPC 2.0 (all layers)
-32600 Invalid request Standard JSON-RPC 2.0 (all layers)
-32601 Method not found Standard JSON-RPC 2.0 (all layers)
-32602 Invalid params Standard JSON-RPC 2.0 (all layers)
-32603 Internal error Standard JSON-RPC 2.0 (all layers)
-32001 Service not found Native SDKs
-32002 Event not found Native SDKs
-32003 Event not declared (Native SDKs) / Timeout (Flutter & Web clients) Transport / Native
-32004 Timeout (Native SDKs) / Connection error (Flutter & Web clients) Transport / Native
-32005 Connection error Native SDKs
-32006 Connection type not supported Native SDKs
-32007 Permission denied Android SDK
-32008 Operation failed Android SDK

Project Structure

NativeRPC/
├── Package.swift                           # Root SwiftPM manifest (NativeRPCKit + NativeRPCKitMacros)
├── pnpm-workspace.yaml                     # pnpm workspace (`connections/web`, `examples/web-counter`, `codegen`)
├── sdk/
│   ├── ios/                                # Standalone Swift SDK + SwiftSyntax Macros (pure SwiftPM)
│   └── android/                            # Standalone Kotlin SDK (`com.nativerpc`)
│       └── processor/                      # KSP annotation processor (`com.nativerpc.processor`)
├── connections/
│   ├── flutter/
│   │   └── native_rpc_flutter/             # Flutter plugin (Dart + SwiftPM iOS + Android + example)
│   └── web/                                # `@nativerpc/web` WebView bridge SDK
├── codegen/                                # `nativerpc-codegen` TypeScript contract generator
├── examples/
│   └── web-counter/                        # React + Vite WebView counter demo
└── docs/                                   # Architecture & codegen documentation

License

MIT — see LICENSE.

About

Protocol-first, contract-driven RPC framework sharing one Swift/Kotlin native service layer across Flutter (FFI + Binary), React Native (TurboModule + C++ JSI), and WebView.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages