Skip to main content

Crate skathi

Crate skathi 

Source
Expand description

Run a Skathi app inside your own Rust executable.

Skathi renders Vue 3 and Svelte 5 apps with gpui and runs their script in JavaScriptCore. The app’s JS half is a payload (.skpk) built by the sk CLI; this crate is the native half. Your main hands the payload to a Builder, registers native modules the app imports (import { greet } from "native:hello") and gets a Handle to send it events.

§A minimal embedder

// Counts the Rust heap for the devtools `mem` command; optional.
#[global_allocator]
static GLOBAL: skathi::HostAllocator = skathi::HostAllocator;

#[skathi::data]
struct Greeting {
    text: String,
}

struct Hello;

// `import { greet, on } from "native:hello"` in the app.
#[skathi::module(events(ready = u32))]
impl Hello {
    pub fn greet(&self, who: String) -> Greeting {
        Greeting { text: format!("hello, {who}") }
    }
}

fn main() {
    // F12 starts this executable again as the inspector (see `inspector_exe` below).
    if std::env::args().nth(1).as_deref() == Some("--devtools") {
        return skathi::run_exe();
    }
    let builder = skathi::Builder::new()
        .payload_file("app/dist/release/.sk/app.skpk")
        .inspector_exe(std::env::current_exe().unwrap())
        .module("hello", Hello);
    #[cfg(target_os = "macos")]
    if let Err(e) = builder.run_on_main_thread(|exit| i32::from(!exit.clean)) {
        eprintln!("{e}");
        std::process::exit(2);
    }
    #[cfg(not(target_os = "macos"))]
    {
        let ui = builder.spawn().unwrap_or_else(|e| {
            eprintln!("{e}");
            std::process::exit(2)
        });
        ui.emit_to("hello", "ready", &std::process::id()).ok();
        std::process::exit(if ui.wait().clean { 0 } else { 1 });
    }
}

module exports every pub fn taking &self under its camelCase name: it runs inside the JS call and returns a value, or, marked #[task], runs on a worker and returns a promise. For a few ad-hoc functions, a closure |m: &mut skathi::Module| … registers them instead. Arguments and results are data types (serde, plus Type with the types feature, on by default), and sk types --exe <program> writes the app’s native-modules.d.ts from them. Deriving Type directly needs #[specta(crate = skathi::specta)] on the type.

Builder::payload_static takes include_bytes! of the payload instead, for a single-file executable. Builder::setup runs before any app JS with a HostContext: direct JavaScriptCore access (js), cookies, OS-sealed secrets and frame, reload and shutdown hooks. tray and hotkeys are the native tray and system-wide hotkeys. surface hands frames a native renderer draws (a D3D11 texture on Windows, CPU BGRA anywhere) to <sk-surface> elements.

§The app payload

The app is an ordinary Skathi project, made and built with the @skathi-native/cli package (needs bun):

bun create skathi app --template minimal --yes
cd app && bun install
bunx sk build --payload-only     # debug: app/dist/debug/.sk/app.skpk
bunx sk publish --payload-only   # release: app/dist/release/.sk/app.skpk

The CLI and this crate are released together and must have the same version: the payload carries the JS half of the host protocol, and a mismatch is refused with Error::Payload. An app split into asset packs (fonts.skpk, assets.skpk) keeps them beside app.skpk; Builder::payload_file finds them there. SK_PAYLOAD=<path> names a payload when the builder is given none.

§Building

The first build downloads the pinned JavaScriptCore prebuilt (about 1.6 GB unpacked on Windows), mimalloc, SQLite3 Multiple Ciphers and a ThorVG archive, and checks each against its hash. REDJS_CACHE_DIR and SK_THORVG_CACHE_DIR move their caches. bun is not needed to build the Rust side.

On Windows (x86_64 MSVC) the build needs the MSVC tools and Windows SDK, clang-cl from LLVM on PATH, and the static CRT, which redjs’s build checks for. In .cargo/config.toml:

[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]

On macOS (arm64) it needs Xcode with its Metal toolchain (or the runtime-shaders feature) and MACOSX_DEPLOYMENT_TARGET=13.0 or later. On Linux (x86_64), clang and the development packages of Wayland, X11 (xcb, xkbcommon), fontconfig and ALSA.

The executable has to carry linker arguments and, on Windows, a manifest (Common Controls 6, per-monitor DPI awareness) that a library cannot add to it. This crate reports them to the embedder’s build script, which passes them on (with embed-resource as a build dependency):

ⓘ
// build.rs
fn main() {
    for arg in std::env::var("DEP_SKATHI_LINK_ARGS").unwrap().split_whitespace() {
        println!("cargo:rustc-link-arg={arg}");
    }
    if let Ok(dir) = std::env::var("DEP_SKATHI_WINDOWS_RESOURCES") {
        let rc = std::path::Path::new(&dir).join("gpui.rc");
        embed_resource::compile(rc, embed_resource::ParamsIncludeDirs([&dir]))
            .manifest_required()
            .unwrap();
    }
}

An application with its own manifest uses that instead, and must keep the Common Controls 6 dependency: without it Windows refuses to start the executable.

Skathi’s own builds patch async-task to the merged but unreleased waker identity fix (smol-rs/async-task#108), which keeps some idle tasks from being polled again and again. An application can do the same until it is released:

[patch.crates-io]
async-task = { git = "https://github.com/smol-rs/async-task", rev = "41fd3359c75e221bd8b187a8ee361aa309c1714c" }

§Features

On by default: prod (runs a payload; off, the host boots the dev output named by SK_DIST), types (native module declarations, with specta), audio (Web Audio), storages (localStorage, cookies and secrets on disk), clipboard, indexeddb, webgpu and native-dx12. Off: battery (the Battery Status API), no-devtools (compiles out the devtools protocol and the inspector) and runtime-shaders (macOS: compile the Metal shaders at startup).

§License

MIT or Apache-2.0. The executable statically links JavaScriptCore from Bun’s WebKit build, parts of which are LGPL-2; its source is at https://github.com/oven-sh/WebKit, at the commit redjs pins.

Re-exports§

pub use sk_app::embed::serde;
pub use specta;

Modules§

bytes
Binary data for native modules: a Uint8Array in JS. #[serde(with = "skathi::bytes")] puts a Vec<u8> field in that form; #[skathi::data] does it for every Vec<u8> field.
hotkeys
System-wide hotkeys for JavaScript (__sk_appHotkeys), over sk-hotkeys. Values and callbacks stay on the VM thread; the service’s worker posts owned events.
js
Direct JavaScriptCore bindings for embedding applications.
tray
Native application tray, shared by Rust embedders and direct JavaScript methods. Values and callbacks stay on the VM thread; the native pump carries only IDs.

Structs§

Builder
Configures and starts an embedded Skathi.
Bytes
Bytes that reach JS as a Uint8Array, read from any ArrayBufferView, an ArrayBuffer or an array of numbers.
Call
One appHost.call(name, ...args).
D3D11Device
The renderer’s ID3D11Device, referenced while this lives. Multithread-protected: use it and its immediate context from any thread. Raw, so any windows crate version can wrap it (ID3D11Device::from_raw_borrowed(&device.as_raw())).
D3D12Device
The renderer’s ID3D12Device and its direct ID3D12CommandQueue, referenced while this lives. Raw, so any windows crate version can wrap them.
D3D12Fence
The ID3D12Fence a surface signals when SurfaceHandle::present_d3d12 is done with a resource. Shared (D3D12_FENCE_FLAG_SHARED), so a queue on the same device can wait on it too.
Declared
A registered function or task; name its parameters for the generated declarations.
DynamicRangeLimit
SurfaceInfo::dynamic_range_limit’s type. The computed dynamic-range-limit: the weights of standard, constrained and no-limit, summing to 1. The initial value is no-limit.
Exit
How the app ended.
FramePresent
What SurfaceHandle::present_d3d12 and SurfaceHandle::present_metal_texture return.
FrameWatch
Ends an SurfaceHandle::on_frame subscription when dropped. Frames of a surface nobody listens to are not tracked.
Handle
The embedder’s side of a running Skathi. Cheap to clone; every method works from any thread.
HostAllocator
Allocator an embedder can install to enable native allocation recording.
HostContext
Services available after storage is installed and before any application JS runs. Cookie and secret operations need the storages feature; secrets are sealed by the OS provider, no plaintext fallback.
HostCookie
A host-provisioned cookie. url is its origin; normal HTTP cookie rules apply.
MetalDevice
The renderer’s id<MTLDevice> and the id<MTLCommandQueue> of its first window, retained while this lives. Raw, so any objc2 or metal crate version can wrap them.
MetalEvent
The id<MTLSharedEvent> a surface signals when SurfaceHandle::present_metal_texture is done with a texture. A command buffer on any device can encodeWaitForEvent on it.
Module
One native:<name> module, filled in by Builder::module.
Reply
Settles one call’s promise, from any thread. Dropped unanswered, it rejects, so a promise never hangs.
SharedTexture
A shared BGRA8 or half-float texture opened on the renderer’s device, from another device, API or process. On Windows: D3D11, D3D12, or Vulkan rendering into D3D12 memory it imports. On macOS: an IOSurface from another MTLDevice, process or framework. Reopen it after SurfaceError::DeviceChanged.
SurfaceDisplay
A display, in a surface’s unit: 1.0 is SDR (paper) white, as in macOS EDR and as Windows composes SDR content, so scRGB is this scaled by Self::sdr_white_nits / 80.
SurfaceHandle
A named surface. Cheap to clone, Send + Sync; present from any thread.
SurfaceInfo
Where the elements showing a surface are, for a producer that renders at the painted size.
SurfaceStats
Frame counters, for a producer that wants to know whether its frames are seen.
SurfaceWatch
Ends an SurfaceHandle::on_change subscription when dropped.

Enums§

EmitError
Why Handle::emit_to did not queue an event.
Error
Why Builder::spawn did not start Skathi.
FrameDropReason
Why a frame never reached the screen.
FrameEvent
What became of a presented frame, reported once per frame in frame order (SurfaceHandle::on_frame).
FramePrecision
How FrameEvent::Presented’s shown_at was known.
SameSite
Cookie attributes accepted by the host’s HTTP cookie jar.
SurfaceError
Why a surface call failed.
SurfaceEvent
What SurfaceHandle::on_change reports.
SurfaceFormat
The pixels a surface takes, set with SurfaceHandle::set_format.

Traits§

Function
A Rust closure the app can call: Fn(A1, ..., An) -> R for up to eight arguments, each Deserialize, with R: Serialize. An Err(e) result throws with e.
IntoModule
What Builder::module takes: a type with #[skathi::module], or a closure that fills the Module (|m: &mut Module| …).
Task
A Function run on a worker: its arguments are read in the call, so they are also Send. An Err(e) result rejects with e.
Type
Provides runtime type information for a Rust type.
Typed
What every argument, result and event type implements: serde plus, with the types feature, specta::Type (#[derive(skathi::Type)]).

Functions§

encrypt_local_storage_at
Seals a dormant profile’s localStorage with the OS provider, no plaintext fallback.
monotonic_ns
Now, in the clock frames are timed in: QPC on Windows, mach_absolute_time on macOS, CLOCK_MONOTONIC elsewhere, in nanoseconds.
run_exe
The host exe’s main: this process IS the app.
surface
The surface named name, created on first use. Every handle and element with that name shares it.

Type Aliases§

Handler
A host function: called with the Call on the Skathi thread.
Job
Runs one task’s work; see Builder::task_executor.

Attribute Macros§

data
Derives what a native module’s argument, result or event type needs: serde’s Serialize and Deserialize and, with skathi’s types feature, skathi::Type, all through skathi’s paths.
module
Makes an impl block a native module: skathi::Builder::new().module("notes", Notes { … }).

Derive Macros§

Type
Implements specta::Type for a given struct or enum.