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.skpkThe 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§
Modules§
- bytes
- Binary data for native modules: a
Uint8Arrayin JS.#[serde(with = "skathi::bytes")]puts aVec<u8>field in that form;#[skathi::data]does it for everyVec<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 anyArrayBufferView, anArrayBufferor an array of numbers. - Call
- One
appHost.call(name, ...args). - D3D11
Device - The renderer’s
ID3D11Device, referenced while this lives. Multithread-protected: use it and its immediate context from any thread. Raw, so anywindowscrate version can wrap it (ID3D11Device::from_raw_borrowed(&device.as_raw())). - D3D12
Device - The renderer’s
ID3D12Deviceand its directID3D12CommandQueue, referenced while this lives. Raw, so anywindowscrate version can wrap them. - D3D12
Fence - The
ID3D12Fencea surface signals whenSurfaceHandle::present_d3d12is 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.
- Dynamic
Range Limit SurfaceInfo::dynamic_range_limit’s type. The computeddynamic-range-limit: the weights ofstandard,constrainedandno-limit, summing to 1. The initial value isno-limit.- Exit
- How the app ended.
- Frame
Present - What
SurfaceHandle::present_d3d12andSurfaceHandle::present_metal_texturereturn. - Frame
Watch - Ends an
SurfaceHandle::on_framesubscription 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.
- Host
Allocator - Allocator an embedder can install to enable native allocation recording.
- Host
Context - Services available after storage is installed and before any application JS runs.
Cookie and secret operations need the
storagesfeature; secrets are sealed by the OS provider, no plaintext fallback. - Host
Cookie - A host-provisioned cookie.
urlis its origin; normal HTTP cookie rules apply. - Metal
Device - The renderer’s
id<MTLDevice>and theid<MTLCommandQueue>of its first window, retained while this lives. Raw, so anyobjc2ormetalcrate version can wrap them. - Metal
Event - The
id<MTLSharedEvent>a surface signals whenSurfaceHandle::present_metal_textureis done with a texture. A command buffer on any device canencodeWaitForEventon it. - Module
- One
native:<name>module, filled in byBuilder::module. - Reply
- Settles one call’s promise, from any thread. Dropped unanswered, it rejects, so a promise never hangs.
- Shared
Texture - 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 afterSurfaceError::DeviceChanged. - Surface
Display - 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. - Surface
Handle - A named surface. Cheap to clone,
Send + Sync; present from any thread. - Surface
Info - Where the elements showing a surface are, for a producer that renders at the painted size.
- Surface
Stats - Frame counters, for a producer that wants to know whether its frames are seen.
- Surface
Watch - Ends an
SurfaceHandle::on_changesubscription when dropped.
Enums§
- Emit
Error - Why
Handle::emit_todid not queue an event. - Error
- Why
Builder::spawndid not start Skathi. - Frame
Drop Reason - Why a frame never reached the screen.
- Frame
Event - What became of a presented frame, reported once per frame in frame order
(
SurfaceHandle::on_frame). - Frame
Precision - How
FrameEvent::Presented’sshown_atwas known. - Same
Site - Cookie attributes accepted by the host’s HTTP cookie jar.
- Surface
Error - Why a surface call failed.
- Surface
Event - What
SurfaceHandle::on_changereports. - Surface
Format - The pixels a surface takes, set with
SurfaceHandle::set_format.
Traits§
- Function
- A Rust closure the app can call:
Fn(A1, ..., An) -> Rfor up to eight arguments, eachDeserialize, withR: Serialize. AnErr(e)result throws withe. - Into
Module - What
Builder::moduletakes: a type with#[skathi::module], or a closure that fills theModule(|m: &mut Module| …). - Task
- A
Functionrun on a worker: its arguments are read in the call, so they are alsoSend. AnErr(e)result rejects withe. - Type
- Provides runtime type information for a Rust type.
- Typed
- What every argument, result and event type implements:
serdeplus, with thetypesfeature,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_timeon macOS,CLOCK_MONOTONICelsewhere, 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
Callon 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
SerializeandDeserializeand, with skathi’stypesfeature,skathi::Type, all throughskathi’s paths. - module
- Makes an
implblock a native module:skathi::Builder::new().module("notes", Notes { … }).
Derive Macros§
- Type
- Implements
specta::Typefor a given struct or enum.