# Tynd — v1.0 > Desktop apps in TypeScript. Small native binaries, zero-codegen typed RPC. Complete documentation for Tynd v1.0. Each page below includes its URL, title, description, and full body content. Intended for LLM ingestion. --- SECTION: Overview --- URL: https://kvnpetit.github.io/tynd/docs/v1.0 TITLE: Introduction DESCRIPTION: Tynd is a desktop-app framework with a Bun TypeScript backend and a native WebView front-end. # Tynd **TypeScript application DX. Native Rust tooling and host. One distributable desktop app.** Tynd is a desktop-app framework with a **TypeScript backend running on Bun** and a native WebView front-end. Your frontend and backend are both TypeScript. RPC types flow from `typeof backend` — no codegen, no IDL, no schema file. ```bash bunx @tynd/cli create my-app ``` ## At a glance - **TypeScript application surface.** Backend, frontend, typed IPC, and config stay TypeScript; CLI, MCP, host, and bundling are native Rust. - **One Bun runtime.** Development and production share Bun. Each app gets its own native Rust host, compiled with the core plus the APIs it declares. - **Native window, zero network.** No HTTP server, no loopback TCP port, no firewall prompt. Frontend and IPC ride a native custom scheme. - **Explicit capability ownership.** Core owns bootstrap, RPC, events, and stable primitives. Specialized OS and plugin APIs install from package-owned `@tynd/plugin-*` entry points. Standalone plugins with a native crate link it into the app's host explicitly. - **Zero-copy binary IPC.** Multi-MB payloads skip JSON/base64 — `ArrayBuffer` end-to-end, 5-10× faster than the usual webview-framework binary path. - **First-class installers.** `.app`, `.dmg`, `.deb`, `.rpm`, `.AppImage`, NSIS, and MSI through the native Rust bundler. Format-specific prerequisites fail where used. Built-in Windows/macOS signing and macOS notarization. - **Framework-agnostic.** React, Vue, Svelte, Solid, Preact, Lit, Angular — anything that outputs a pure SPA. ## Why Tynd Most desktop-app frameworks force you to pick a language for the native side (Rust for Tauri, Go for Wails, or the entire Chromium for Electron). Tynd keeps application code TypeScript-first: **you write TypeScript, while native Rust tooling builds and ships the binary**. Backend, frontend, RPC — same language, same types. Bun powers every backend; plugins only customize the Rust host. RPC and assets never touch TCP — no loopback port, no firewall prompt. Every backend, frontend, and OS API with signatures and examples. ## How it works ``` TypeScript backend Native OS window ────────────────────────── ───────────────────────── export async function greet() ◄── IPC ─ await api.greet("Alice") events.emit("ready", payload) ─── push ─► api.on("ready", handler) │ ▼ Bun backend — one JavaScript runtime native host — Rust host compiled for the app tynd / tynd-mcp — native Rust developer tools ``` Frontend assets and IPC ride a native custom scheme — no HTTP server, no loopback port, no firewall prompt. Multi-MB binary payloads (`fs.readBinary`, `fs.writeBinary`, `compute.hash`) skip JSON entirely via a dedicated binary channel. ## Runtime All backend code runs on Bun with `Bun.*`, `node:*`, Web APIs, JIT, and native npm bindings. Specialized APIs install explicitly as plugins. Tynd compiles each app's Rust host with the core plus the declared plugins, without changing the JavaScript runtime. See [Runtime](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/runtimes) for details. ## Requirements **[Bun](https://bun.sh) is required for app developers.** Application backends, frontend commands, and TypeScript config run on Bun; the CLI and MCP server are native Rust. Node.js is not supported as an application-runtime replacement. [Rust](https://rustup.rs) 1.95+ and the platform build tools are also required, because `tynd dev` and `tynd build` compile the app's native host; you write no Rust. See [Installation](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/installation). ```bash # macOS / Linux curl -fsSL https://bun.sh/install | bash # Windows (PowerShell) powershell -c "irm bun.sh/install.ps1 | iex" ``` **End users do not install Bun separately** — the exact Bun executable is packed into the distributed binary. The target OS still supplies its normal system WebView/runtime libraries. ## What to read next Scaffold a project, run it with HMR, produce a release binary. Frontend, Rust host, TS backend — how the three surfaces fit. Recipes for streaming, multi-window, auto-update, signing, bundling. Tynd vs Tauri, Electron, Wails — where each one fits. ---- --- SECTION: Getting Started --- URL: https://kvnpetit.github.io/tynd/docs/v1.0/getting-started TITLE: Getting Started DESCRIPTION: Scaffold your first Tynd app, run it with hot reload, and produce a release binary in under five minutes. # Getting Started Build a native desktop app in TypeScript in under 5 minutes. By the end of this section you'll have: - a running dev window with HMR on both the frontend and the backend, - a typed RPC boundary — rename a function in `backend/main.ts` and the TypeScript compiler catches every stale frontend call, - a packed executable in `release/-/` that includes the compiled host, Bun, backend, and frontend. ### Install prerequisites [Bun](https://bun.sh) 1.3+ and [Rust](https://rustup.rs) 1.95+ are required, plus the platform build tools: the MSVC build tools on Windows, the Xcode command line tools on macOS (apps run on macOS 14+), the WebKitGTK/GTK dev packages on Linux. See [Installation](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/installation). ### Scaffold a project ```bash bunx @tynd/cli create my-app ``` The required name becomes the project directory. The frontend defaults to React; pass `--framework ` with `vue`, `svelte`, `solid`, `preact`, `lit`, or `angular` when needed. Bun is the backend runtime. ### Run it ```bash cd my-app tynd dev ``` The first run compiles the app's native host and takes a few minutes; later runs reuse it. A native window opens with your frontend + HMR. Save `backend/main.ts` — the backend hot-reloads without tearing down the window. ### Ship it ```bash tynd build # raw binary tynd build --bundle all # + current-host installers (.app/.dmg, .deb/.rpm/.AppImage, NSIS/MSI) ``` Output lands in `release/-/`. Installers need a `bundle.identifier` in `tynd.config.ts` — see [Your First App](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/first-app#ship-it-as-an-installer). ## Keep reading Bun, Rust, platform build tools, WebView deps per OS, verifying the setup. Walk through the backend, the frontend, and the RPC boundary. What each file does and where your code goes. `tynd dev` vs `tynd start`, caching, hot reload. ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/dev-workflow TITLE: Development Workflow DESCRIPTION: The day-to-day loop with native Rust tooling and a TypeScript application. # Development Workflow Tynd keeps application development in TypeScript while the CLI, MCP server, host, and packager run as native Rust binaries. ## `tynd dev` — live development ```bash bun run dev # commonly aliases `tynd dev` ``` `tynd dev` starts the frontend framework's normal development server, waits until it is reachable, compiles the app's native host with the Cargo `dev` profile (a few minutes the first time, skipped when nothing changed), then launches it with the project's pinned Bun executable. - The frontend framework owns HMR. - Tynd watches backend, plugin, config, and environment inputs. - Backend source changes reload the Bun backend while the WebView stays alive. - A configuration change that affects native capabilities, environment, plugins, or host arguments asks you to restart `tynd dev`. Use `--inspect` or `--inspect-brk` for the Bun inspector. Use `--no-debug` when the MCP/debug socket should not be exposed. ## `tynd start` — run existing production assets ```bash tynd start ``` `start` does not rebuild anything. It launches the release host compiled by `tynd build` with the existing frontend output and production backend artifact `.tynd/cache/bundle.dist.js`. If an artifact or the release host is missing, the command stops and tells you to run `tynd build`. This makes `start` useful for repeatable production-shaped launches: build explicitly, then start exactly those outputs. ## `tynd build` — release output ```bash tynd build # packed native executable tynd build --bundle all # supported installers for this host OS ``` `build` runs the framework production build, bundles the backend through the pinned Bun runtime, compiles the host with the Cargo `release` profile, and asks the Rust `tynd-bundler` to create a native package under `release/-/`. Commit `.bun-version` and your package lock. `tynd validate --ci` requires the Bun pin, resolves that exact Bun runtime, and checks native host/bundler availability. Package-lock validation remains the project/CI package manager's job. Installer formats are host-specific: | Host OS | Output | |---|---| | macOS | `.app`, `.dmg` | | Linux | `.deb`, `.rpm`, `.AppImage` | | Windows | NSIS setup, `.msi` | A format-specific external prerequisite is checked only when that format is requested. ## Generated state `.tynd/cache/` and `.tynd/build/` contain generated staging data. Tynd does not claim source-hash build skipping: `build` performs its required build steps and `start` is explicitly cache-only. ```bash tynd clean --dry-run # show exact targets tynd clean --yes # remove .tynd/cache, .tynd/build, and release tynd clean --yes --cache # also remove the shared host build cache ``` ## Project checks Tynd does not impose an application linter or typechecker. Use the ones selected by your frontend project, for example: ```bash bunx tsc --noEmit bunx biome check . ``` `tynd info`, `tynd validate`, and `tynd doctor` inspect project state without registry, WebView, or broad toolchain preflight probes. Missing optional tooling is reported by the command that actually needs it. ## Next - [Backend RPC guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/backend-rpc) - [Build Pipeline](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/build-pipeline) - [Troubleshooting](https://kvnpetit.github.io/tynd/docs/v1.0/troubleshooting) ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/first-app TITLE: Your First App DESCRIPTION: Build a minimal Tynd app from scratch — backend function, frontend call, typed RPC, and a production binary. # Your First App Walk through every surface of Tynd — the TypeScript backend, the typed RPC proxy on the frontend, and the native OS APIs that the frontend can call directly. ## Scaffold ```bash bunx @tynd/cli create hello-tynd --framework react cd hello-tynd ``` `--framework` accepts `react` (default), `vue`, `svelte`, `solid`, `preact`, `lit`, or `angular`; any other value fails with `unknown framework`. Examples below use framework-agnostic TypeScript — swap `document.getElementById` for your framework's idiomatic equivalent (`useState` in React, `ref()` in Vue, `$state` in Svelte, etc.). ## Backend — your TypeScript functions ```ts title="backend/main.ts" import { app, createEmitter } from "@tynd/core"; export const events = createEmitter<{ tick: { count: number }; }>(); export async function greet(name: string): Promise { return `Hello, ${name}!`; } export async function add(a: number, b: number): Promise { return a + b; } app.onReady(() => { let count = 0; setInterval(() => { count += 1; events.emit("tick", { count }); }, 1000); }); app.start({ frontendDir: import.meta.dir + "/../dist", window: { title: "Hello Tynd", width: 1000, height: 700, center: true, }, }); ``` Every exported function and emitter is **automatically callable from the frontend** — no hand-written glue. ## Frontend — typed RPC proxy ```ts title="src/main.ts" import { createBackend } from "@tynd/core/client"; import type * as backend from "../backend/main"; const api = createBackend(); async function render() { const greeting = await api.greet("Alice"); document.getElementById("greeting")!.textContent = greeting; const sum = await api.add(2, 3); document.getElementById("sum")!.textContent = String(sum); } api.on("tick", ({ count }) => { document.getElementById("count")!.textContent = String(count); }); render(); ``` Types come from `typeof backend` through the `@tynd/core` package exports; no file is generated. Rename `greet` to `sayHello` in the backend — the compiler lights up every stale call on the frontend. ## OS APIs — no round-trip to the backend Native things (dialogs, clipboard, notifications) are callable directly from the frontend. No IPC round-trip through your backend, no boilerplate: Install the required plugins: ```bash tynd add notification dialog clipboard ``` ```ts title="src/main.ts" import { tyndWindow } from "@tynd/core/client"; import { dialog } from "@tynd/plugin-dialog/client"; import { clipboard } from "@tynd/plugin-clipboard/client"; import { notification } from "@tynd/plugin-notification/client"; document.getElementById("open")!.addEventListener("click", async () => { const path = await dialog.openFile({ filters: [{ name: "Text", extensions: ["txt", "md"] }], }); if (path) { await notification.send("File picked", { body: path }); await clipboard.writeText(path); } }); document.getElementById("max")!.addEventListener("click", async () => { await tyndWindow.toggleMaximize(); }); ``` ## Run it ```bash tynd dev ``` A native window opens. Save `backend/main.ts` — the backend hot-reloads without tearing down the window. Save frontend files — the frontend HMR reloads in place. ## Build it ```bash tynd build ``` Packed executable under `release/-/`. It contains the native host, exact Bun runtime, backend bundle, and frontend assets. End users do not install Node or Bun separately. Run `tynd doctor` after this first build: before it, the frontend output does not exist yet, so `doctor` reports `frontend assets` as missing. ### Ship it as an installer Installers need a `bundle` section in `tynd.config.ts`; without it, `--bundle` stops with ``installer bundles require a `bundle` section with `bundle.identifier` in tynd.config.ts``. `identifier` is the only required key: a reverse-DNS id with at least three dot-separated parts. ```ts title="tynd.config.ts" import { defineConfig } from "@tynd/cli"; export default defineConfig({ // ...existing keys bundle: { identifier: "com.example.hellotynd", displayName: "Hello Tynd", // optional, defaults to the package name shortDescription: "My first Tynd app", // optional }, }); ``` ```bash tynd build --bundle all ``` Produces platform-native installers: | Host OS | Output | |---|---| | macOS | `MyApp.app` + `MyApp_1.0.0_.dmg` (`x64` or `aarch64`) | | Linux | `.deb` + `.rpm` (if `rpmbuild` is available) + `.AppImage` | | Windows | NSIS `.exe` setup + `.msi` | See [Bundling & Distribution](https://kvnpetit.github.io/tynd/docs/v1.0/guides/bundling) for the full workflow. ## Next - [Project Structure](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/project-structure) - [Backend RPC guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/backend-rpc) - [API Reference](https://kvnpetit.github.io/tynd/docs/v1.0/api) ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/installation TITLE: Installation DESCRIPTION: Install Bun, Rust, and the OS-level dependencies Tynd needs to build and run desktop apps on Windows, macOS, and Linux. # Installation Tynd keeps application development TypeScript-first. The CLI and MCP server are native Rust executables; Bun runs application backends, frontend commands, and TypeScript config. Node.js is not a supported replacement for application code. Every app runs on a native host that `tynd dev` and `tynd build` compile with Cargo, so a project needs: - **Bun 1.3 or newer**; - **Rust 1.95 or newer** (`cargo` and `rustc` on `PATH`); - the platform build tools and WebView development packages listed below. You write no Rust: the host is generated and compiled for you. ## Install Bun ```bash curl -fsSL https://bun.sh/install | bash ``` ```powershell powershell -c "irm bun.sh/install.ps1 | iex" ``` Verify: ```bash bun --version ``` ## Install Rust Install Rust with [rustup](https://rustup.rs): ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` Download and run `rustup-init.exe` from [rustup.rs](https://rustup.rs). Verify: ```bash rustc --version # 1.95.0 or newer ``` If `cargo` or `rustc` is missing, or `rustc` is older than 1.95, `tynd dev` and `tynd build` stop with a message pointing to https://rustup.rs. Run `rustup update` to upgrade an older toolchain. ## Platform build tools The **MSVC build tools**: install [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) with the "Desktop development with C++" workload. `rustup-init.exe` offers to install them. The **Xcode command line tools**: ```bash xcode-select --install ``` A C toolchain (`build-essential` on Debian / Ubuntu) plus the WebKitGTK and GTK development packages listed in the next section. ## OS-level WebView dependencies Tynd uses the platform WebView — Edge WebView2 on Windows, WKWebView on macOS, and WebKitGTK 4.1 on Linux. The CLI does not query registry state or preflight WebView availability during ordinary project commands. **WebView2** is available by default on current supported Windows releases. Locked-down/older images can install Evergreen separately. For distribution, choose `skip`, bootstrapper, offline-installer, or fixed-runtime behavior explicitly under `bundle.windows`; see the [Bundling guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/bundling#windows-webview2-distribution). **WKWebView** ships with macOS — nothing to install. Tynd apps require macOS 14 (Sonoma) or later; `.app` bundles declare it as `LSMinimumSystemVersion`. End-user runtime (for installed `.deb`/`.rpm`/`.AppImage`): ```bash # Debian / Ubuntu sudo apt install libwebkit2gtk-4.1-0 libjavascriptcoregtk-4.1-0 libsoup-3.0-0 ``` Development (compiling the host): ```bash sudo apt install libgtk-3-dev libwebkit2gtk-4.1-dev \ libjavascriptcoregtk-4.1-dev libsoup-3.0-dev \ libxdo-dev libxss-dev libpipewire-0.3-dev \ libgbm-dev libdrm-dev libclang-dev libxcb1-dev libxrandr-dev \ libdbus-1-dev libwayland-dev libegl-dev ``` **Fedora / RHEL:** ```bash sudo dnf install gtk3-devel webkit2gtk4.1-devel libsoup3-devel ``` For screen capture builds, also install `pipewire-devel`, `clang-devel`, `libxcb-devel`, `libXrandr-devel`, `dbus-devel`, `wayland-devel`, and `mesa-libEGL-devel`. ## Install the CLI You don't have to install anything globally — use `bunx`: ```bash bunx @tynd/cli create my-app ``` Or add it to a project: ```bash bun add @tynd/core bun add -d @tynd/cli @tynd/host-src ``` `@tynd/host-src` holds the Rust sources the app host is compiled from; `tynd create` and `tynd add` add it as a dev dependency and `tynd upgrade` updates it. `@tynd/cli` resolves `tynd` and `tynd-bundler` from the matching `@tynd/tooling--` optional package. Neither runs a postinstall or downloads binaries at command time. The first `tynd dev` or `tynd build` compiles the host and takes a few minutes (the CLI prints a notice). Later runs are incremental. ## Verify the install ```bash bunx @tynd/cli info ``` Prints the native tooling version, project root, Bun version, and resolved host/bundler paths without probing WebView or registry state. ## Editor setup Any TypeScript-capable editor works. `tynd init` creates/patches editor config for ES2022, bundler module resolution, `@tynd/core/env`, and the generated client-type path. No Tynd-specific language server is required. ## Next - [Your First App](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/first-app) - [Development Workflow](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/dev-workflow) ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/project-structure TITLE: Project Structure DESCRIPTION: Source, config, generated staging, host build, and platform release directories in a current Tynd app. # Project Structure A Vite/React scaffold (`tynd create my-app --framework react`) has this shape after development/build: - my-app - tynd.config.ts - package.json - bun.lock - .bun-version - tsconfig.json - vite.config.ts - backend - main.ts - src - main.tsx - public/ - dist/ - .tynd - cache/ - build/ - release - win32-x64/ Framework templates keep their standard source layout. ## `tynd.config.ts` Application build/native metadata. Window/menu/tray settings belong to backend `app.start`, not this file. ```ts title="tynd.config.ts" import { defineConfig } from "@tynd/cli"; export default defineConfig({ backend: "backend/main.ts", frontendDir: "dist", icon: "assets/icon.svg", bundle: { identifier: "com.example.myapp", }, }); ``` The public TypeScript type/`defineConfig` helper have no runtime dependency. Native Rust tooling evaluates/merges/validates config, then resolves relative paths from the config project root. ## `package.json` `tynd init` adds `@tynd/core`, plus `@tynd/cli`, `@tynd/host-src`, and `@types/bun` as dev dependencies, then normalizes `dev`, `start`, and `build` scripts. Existing non-Tynd `dev`/`build` scripts are preserved as `dev:ui`/`build:ui` when possible. Native installer metadata reads available package name, version, homepage, author, and license; Tynd bundle fields can supply display name and descriptions. ## `tsconfig.json` and `global.d.ts` `tynd init` creates or patches editor configuration for: - ES2022/ESNext with bundler module resolution; - strict TypeScript; - `@tynd/core/env` globals (in the referenced `tsconfig.app.json` of a Vite/Angular starter, otherwise in `tsconfig.json` plus a `global.d.ts` reference); - the backend: added to the root `include`, or, for a solution-style root (`files: []` + `references`), a generated `tsconfig.backend.json` reference. ## `backend/` TypeScript executed by the packed/project Bun runtime. Exported functions/events form the typed frontend RPC surface; `app.start()` defines application/window behavior. During dev/build, Tynd generates a bootstrap that imports this entry, registers configured JavaScript plugins, and injects runtime/updater values. ## Frontend source and output Frontend source remains owned by Vite, Angular, CRA, Parcel, Rsbuild, Webpack, or the configured command. Tynd detects standard production directories but respects an explicit `frontendDir`. A framework production build normally stays in its framework output such as `dist` or `build`. ## `.tynd/cache/` Generated staging only, including: - backend bootstrap and `.tynd/cache/bundle.dist.js`; - staging of a `frontendDir` that no detected build tool produces; - JSON passed to native pack/bundle/sign operations. It is not a source-hash skip cache. `tynd build` performs required build steps every invocation. `tynd start` is the command that deliberately reuses existing outputs. ## `.tynd/build/` Generated Rust host project (`Cargo.toml`, `src/main.rs`, `Cargo.lock`) and the compiled host binaries, copied to `bin/debug/` by `tynd dev` and to `bin/release/` by `tynd build`. Cargo itself compiles into the [shared host build cache](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/build-pipeline#shared-host-build-cache) outside the project; in CI, cache the directory set in `TYND_CACHE_DIR`. ## `release/` Platform/architecture output: ```text release/-/[.exe] ``` Optional installers, publish manifests, and patches share the release tree. macOS app bundles additionally produce `--macos.zip` for updater publication. ## Cleanup and source control `tynd init` adds these defaults: ```text .tynd/ release/ node_modules/ dist/ .env .env.local *.key ``` `tynd clean --yes` removes `.tynd/cache`, `.tynd/build`, and `release`; it keeps framework output such as `dist`. Add `--cache` to also remove the shared host build cache. ## Next - [Config Reference](https://kvnpetit.github.io/tynd/docs/v1.0/cli/config) - [Development Workflow](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/dev-workflow) - [Build Pipeline](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/build-pipeline) ---- --- SECTION: Core Concepts --- URL: https://kvnpetit.github.io/tynd/docs/v1.0/concepts/architecture TITLE: Architecture DESCRIPTION: How Tynd splits an app across three surfaces — frontend WebView, Rust host, and TypeScript backend — and what each one owns. # Architecture A Tynd app has **three surfaces**: ``` ┌──────────────────────────┐ ┌──────────────────────────┐ ┌──────────────────────────┐ │ Frontend │ │ Rust Host │ │ TS Backend │ │ (WebView) │◄──IPC─►│ (native layer) │◄──IPC─►│ (Bun) │ │ │ │ │ │ │ │ • Your UI │ │ • Window + event loop │ │ • Your exported fns │ │ • @tynd/core/client │ │ • Core + plugin APIs │ │ • createEmitter │ │ • createBackend() │ │ • tynd:// + tynd-bin:// │ │ • app.start(config) │ │ • OS calls (direct) │ │ • Streaming RPC │ │ • Lifecycle hooks │ └──────────────────────────┘ └──────────────────────────┘ └──────────────────────────┘ ``` Each surface has a single, narrow responsibility. The glue between them is **typed, zero-codegen, and transport-agnostic** (no HTTP, no WebSocket, no TCP). ## The three surfaces ### 1. Frontend — your UI A pure SPA. Whatever framework you picked (React, Vue, Svelte, Solid, Preact, Lit, Angular) emits static assets into `dist/`. Tynd serves those through the `tynd://localhost/` custom scheme — `window.location.origin` is `tynd://localhost` (no `http://localhost:xxxx`, no TCP port, no firewall prompt). Typical imports: - `import { createBackend } from "@tynd/core/client"` — typed RPC proxy to your backend. - `import { tyndWindow, path } from "@tynd/core/client"` — core host primitives. - `import { dialog } from "@tynd/plugin-dialog/client"` — a capability from its official plugin. ### 2. Rust host — the native layer The runtime-facing native surface has two entry points: - **`tynd-host`** (library) — the native event loop, the IPC bridge, and the core OS APIs. - **The app host** — an executable Tynd generates for each app and compiles with Cargo from `@tynd/host-src`. It launches the Bun backend. Internally, stable contracts are isolated from the platform-heavy host: | Crate | Responsibility | | --- | --- | | `tynd-protocol` | Shared process protocol types and the IPC frame limit (8 MiB) | | `tynd-capabilities` / `tynd-security-policy` | Capability model and native policy checks | | `tynd-pack-format` / `tynd-update-core` | Package and updater contracts shared with tooling | | `tynd-debug-protocol` | Optional debug transport | | `tynd-host-macros` | Typed Rust dispatch generation | | `tynd-host` | Wry/Tao orchestration, IPC, the webview JS shim, and feature-gated OS implementations | | `tynd-runtime` | Executable bootstrap that launches the embedded Bun runtime | ### 3. Backend — your TypeScript Your exported functions, typed emitters, and lifecycle hooks run in Bun. You get Bun + Node.js globals (`fetch`, `Bun.*`, `node:*`), JIT, and native npm bindings. The host carries the core plus the APIs of the declared host-backed plugins and the native crates of the declared standalone plugins; `tynd dev` and `tynd build` compile it for the app. The JavaScript runtime is always Bun. See [Runtime](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/runtimes). ## Minimal core and composition The host is a minimal core plus the APIs your app declares. The core is always compiled in: the window and its webview, the `tynd://` and `tynd-bin://` schemes, IPC, RPC and events, the app lifecycle, the debug protocol, and the `acl` and `log` APIs (no Cargo feature: they cannot be built out). Its clients come from `@tynd/core/client`: `app`, `tyndWindow` and `tyndWebview` (current window and webview only), `os`, `path`, `monitors`, `security`, `log`, `workers`, and the RPC and event helpers. Every other host API (dialog, clipboard, menu, tray, multiwindow, fs, http, updater, ...) is a host-backed official plugin `@tynd/plugin-`. Such a plugin selects the matching `api-` Cargo feature and exposes the typed client from `@tynd/plugin-/client`; it does not ship a second native implementation. `tynd add ` installs the package and lists it in `plugins`, and the CLI compiles those features into the app host on the next `tynd dev` or `tynd build`. A host built without an API rejects its calls with an error naming `@tynd/plugin-`; a `menu` or `tray` in `app.start` without its plugin stops startup with the same message. Workload-specific extensions such as terminal and local AI are official plugins with their own native crates. SQL runs in the Bun backend through `bun:sqlite`. ## Runtime topology ``` Frontend (WebView) ──postMessage──► Rust host (IPC handler) ──stdin JSON──► Bun backend ▲ ▲ │ │ evaluate_script │ stdout JSON ◄───────────────┘ ``` - Frontend → backend calls travel over the WebView's `window.ipc.postMessage` → Rust parses → stdin JSON → Bun reads a line, dispatches, writes stdout JSON → Rust evaluates the response on the originating webview. - OS calls take a shortcut: frontend → Rust (direct), Rust → frontend (direct). Backend never sees them. ## What's shared - Core bootstrap, RPC, event, and plugin-loading contracts. - Installed plugin APIs; availability follows app configuration, not runtime name. - The RPC wire format (`{ type: "call", id, fn, args }` / `{ type: "return", id, value }`). - The streaming RPC mechanism (per-stream credit, yield batching, cancellation on window close). - The `tynd://` frontend scheme + the `tynd-bin://` binary IPC scheme. - TYNDPKG packing (how your built binary embeds the frontend + backend + assets + sidecars). - Trusted backend workers use `Bun.Worker`; renderer workers remain sandboxed Web Workers. - Release packages include Bun and the app bundle. - Host-backed plugins and standalone plugins with a native crate only change how the Rust host is built. ## Why this split matters - **No HTTP, no TCP.** Frontend assets and IPC ride a native custom scheme. No loopback port, no firewall prompt on first launch, no MITM window for an attacker on the same machine. - **No Rust in your code.** You never write or maintain Rust application code — Tynd generates the host and compiles it with your installed Rust toolchain. - **OS APIs stay off the renderer.** Blocking native calls run outside the WebView; PTYs keep dedicated native threads and SQLite lives in Bun. Renderer worker code deliberately stays inside the WebView sandbox. - **One JavaScript runtime.** Development and production use Bun, avoiding engine-specific behavior. ## Next - [Runtime](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/runtimes) — Bun and custom native hosts. - [IPC Model](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/ipc) — call / event / stream flow in detail. - [Security](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/security) — CSP, scheme allowlists, structural model. ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/concepts/build-pipeline TITLE: Build Pipeline DESCRIPTION: How native Rust tooling develops, launches, builds, and packages a TypeScript Tynd application. # Build Pipeline Tynd separates three execution paths instead of hiding builds behind launch commands: | Command | Frontend | Backend | Native result | |---|---|---|---| | `tynd dev` | Framework dev server/direct assets | Source bootstrap watched and reloaded | Development host process | | `tynd start` | Existing configured/detected output | Existing cached bundle | Existing host process | | `tynd build` | Production build/direct bundle | Fresh minified Bun bundle | Packed executable, optional installers | The npm `@tynd/cli` package only resolves and launches the native executable. Config stays TypeScript-friendly; orchestration runs in Rust. ## Development `tynd dev`: 1. loads merged config and dotenv inputs; 2. detects and starts the frontend development command; 3. waits up to 30 seconds for `devUrl` when one exists; 4. writes a small backend bootstrap that registers configured JavaScript plugins and runtime/updater globals; 5. resolves the pinned Bun executable and compiles the Rust host package generated in `.tynd/build` with the Cargo `dev` profile (skipped when its inputs did not change since the last successful dev build); 6. supervises frontend, host, and relevant backend/plugin/config inputs. Frontend HMR remains owned by Vite, Angular, Parcel, Rsbuild, Webpack, or the configured command. Compatible backend changes send `reload` through the host's control channel without recreating the native window. A changed host/config plan requires a `tynd dev` restart. ## Cache-only start `tynd start` performs no frontend build, backend build, watcher, host build, dependency install, or pack step. It runs the release host compiled by the last `tynd build`. It accepts only the production backend artifact `.tynd/cache/bundle.dist.js`, plus the configured frontend directory when it exists, otherwise the detected framework output. Missing output, including a missing release host, fails with an instruction to run `tynd build`. ## Production build `tynd build`: 1. runs the detected frontend production command when applicable; 2. bundles the generated backend entry to `.tynd/cache/bundle.dist.js` with Bun (`--target=bun --minify`); 3. copies a `frontendDir` that has no detected build tool and injects runtime config; 4. compiles the Rust host package generated in `.tynd/build` with the Cargo `release` profile; 5. invokes native Rust `tynd-bundler pack`; 6. invokes native installer bundling only when `--bundle ` is requested; 7. applies configured platform signing. Default raw output: ```text release/-/[.exe] ``` ## Generated state `.tynd/cache` is a staging directory for bootstraps, bundles, frontend assets, and native bundler JSON. `.tynd/build` contains the generated host package (`Cargo.toml`, `src/main.rs`), `Cargo.lock`, the copies of editable native plugins in `plugins//`, and the host binaries copied to `bin/debug/` and `bin/release/`. Required `build` steps still run on every invocation. ## Shared host build cache Cargo compiles the host into a target directory shared by every project on the machine, from source copies shared the same way: ```text /host/ Cargo target directory /host/src/ copy of the installed @tynd/host-src sources /host/plugins/- copy of an installed native plugin crate ``` | Platform | `cache_root` | |---|---| | Any, when set | `TYND_CACHE_DIR` (made absolute, with native separators) | | Windows | `%LOCALAPPDATA%\tynd\cache` | | macOS | `~/Library/Caches/tynd` | | Linux | `$XDG_CACHE_HOME/tynd`, else `~/.cache/tynd` | `` is derived from the host sources (the `@tynd/host-src` version, or the path of editable sources), the `rustc --version` line, and the compiler's host target triple. Third-party dependencies, the Tynd crates, and native plugin crates are compiled once per key and reused by every project: the first project's first build takes a few minutes, later projects with the same key compile only their own generated host package and link. A Rust upgrade or a new `@tynd/host-src` version starts a new key. The `dev` and `release` profiles share the same target directory. `tynd clean --cache` only removes a `host` directory holding the `.tynd-cache` marker Tynd writes there, and a build refuses to adopt a non-empty `host` directory without it. Cargo identifies a local crate by its absolute path, so a crate read from each project's `node_modules` would be recompiled for every project. The build therefore copies those sources into the cache once and compiles the copies: - `host/src/` holds the `native` tree of an installed `@tynd/host-src`. Editable sources (a Tynd checkout, a linked package) are compiled in place, without a copy. - `host/plugins/-` holds an installed native plugin crate (one inside `node_modules`) in `crate/`, next to a generated `Cargo.toml` that provides the workspace values the crate inherits (`version.workspace = true`, `tynd-plugin-sdk.workspace = true`, …). - An editable plugin (linked by `tynd plugin dev`, or any plugin outside `node_modules`) is copied to `.tynd/build/plugins/` instead, with the same layout. That copy keeps its path and is synchronized on every build: only changed files are rewritten and deleted files are removed, so an edit recompiles the plugin alone rather than starting a new cache copy. Each `` covers the content of every copied file, plus the package version for the host sources and the generated workspace manifest for a plugin. A cache copy is written to a temporary directory (`.tmp-*`, removed when left over an hour by an interrupted build), renamed into place, and never modified afterwards: changed sources, including an edit inside `node_modules`, get a new directory. Old copies stay until `tynd clean --cache`. On Windows, Cargo and the MSVC tools build deep paths under the target directory, and a long one makes the linker or assembler fail (`LNK1104`, `A1009`). When the target directory is longer than 80 characters, builds and `tynd doctor` warn: set `TYND_CACHE_DIR` to a short path such as `C:\tynd-cache`. After Cargo finishes, the binary is copied to `.tynd/build/bin//`, which is what `tynd dev`, `tynd start`, and packing use. `tynd doctor` shows the cache path; `tynd clean --cache` removes it. On Windows a running executable cannot be replaced: stop the app before rebuilding, or the copy fails with `replace … (is the app still running?)`. In CI, set `TYND_CACHE_DIR` to a path inside the workspace and cache that directory. ```bash tynd clean --dry-run tynd clean --yes ``` `clean` removes `.tynd/cache`, `.tynd/build`, and `release` only; add `--cache` to also remove the shared host build cache. ## Native package The pack step combines: - compiled release Rust host; - exact Bun executable and version; - bundled backend; - frontend assets; - configured sidecars; - optional fixed WebView2 runtime; - package metadata. The payload uses the [TYNDPKG format](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/tyndpkg). ## Installers and signing Supported current-host formats: | Host OS | Targets | |---|---| | macOS | `macos`, `dmg` | | Linux | `deb`, `rpm`, `appimage` | | Windows | `nsis`, `msi` | Cross-compilation is rejected. Format-specific prerequisites are resolved when that format runs; no broad registry/WebView/toolchain preflight precedes ordinary commands. Windows signing invokes `signtool` from `PATH` for eligible executable/installer files. macOS signing/notarization uses the Rust bundler. A macOS `.app` update archive is named `--macos.zip`. ## Next - [Bundling](https://kvnpetit.github.io/tynd/docs/v1.0/guides/bundling) - [Code Signing](https://kvnpetit.github.io/tynd/docs/v1.0/guides/code-signing) - [Security](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/security) ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/concepts/gpu-acceleration TITLE: GPU & 3D DESCRIPTION: What hardware acceleration Tynd inherits from the OS webview, what 3D / WebGL / WebGPU works out of the box, and how to wire up a Three.js scene. # GPU acceleration & 3D Tynd renders inside the **system webview** (WebView2 on Windows, WKWebView on macOS, WebKitGTK on Linux). All three engines ship GPU compositing, hardware video decode, and WebGL. WebGPU is available when the installed OS webview supports it; Tynd enables the available platform path by default. **CSS animations, video, and WebGL use the webview GPU path without an app flag.** This page covers what Tynd ships today, the tradeoffs per OS, and how to wire up a Three.js scene with your favourite frontend framework. ## What's enabled per OS | Capability | Windows (WebView2) | macOS (WKWebView) | Linux (WebKitGTK) | |---|---|---|---| | GPU compositing (CSS, scroll, video) | Yes | Yes | Yes | | WebGL 1 + 2 (Three.js, Babylon.js, PixiJS) | Yes | Yes | Yes | | WebGPU (compute shaders, modern 3D) | Yes (Chromium 113+) | Yes (Safari 18+ on macOS 15+) | WebKitGTK 2.40+, behind `WEBKIT_USE_WEBGPU=1` (set by the host unless `window.webgpu` is `false`) | | Hardware video decode (h264, h265, AV1) | Yes (DXVA / D3D11) | Yes (VideoToolbox) | Yes when the VA-API driver is installed | | Canvas 2D GPU acceleration | Yes | Yes | Yes | The webview is the GPU surface — Tynd wraps it but doesn't proxy or buffer GPU calls, so there's no Tynd-specific overhead vs. running the same page in Edge / Safari / Epiphany. ## Three.js — quick start There's no built-in `three` template — use your favourite framework's scaffold and add Three.js as a regular npm dependency: ```bash bunx @tynd/cli create my-3d-app --framework react cd my-3d-app bun add three @types/three # (see snippet below — save it as src/scene.ts and import it from src/main.tsx) bun run dev ``` A minimal HMR-friendly scene that picks the discrete GPU on dual-GPU laptops (Intel + NVIDIA / AMD), caps `devicePixelRatio` at 2 (the standard "no-one-can-tell-3x-from-2x" knob), and uses orbit controls: ```ts title="src/scene.ts" {1-2,7-10} import * as THREE from "three" import { OrbitControls } from "three/addons/controls/OrbitControls.js" const scene = new THREE.Scene() const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) const renderer = new THREE.WebGLRenderer({ antialias: true, // Dual-GPU laptops (Hybrid Graphics) — hint the OS to pick the // discrete GPU. Honoured by Chromium, WKWebView and WebKitGTK. powerPreference: "high-performance", }) renderer.setSize(window.innerWidth, window.innerHeight) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) document.body.appendChild(renderer.domElement) // Add a lit cube + orbit controls + animation loop here. See the // official Three.js "Creating a scene" guide for the full example: // https://threejs.org/docs/#manual/en/introduction/Creating-a-scene camera.position.z = 5 const controls = new OrbitControls(camera, renderer.domElement) function animate() { requestAnimationFrame(animate) controls.update() renderer.render(scene, camera) } animate() ``` Any Vite-based template (`react`, `vue`, `svelte`, `solid`, `preact`, `lit`) works the same way — Three.js is rendered into a `` you mount inside your component tree. ## Knobs you actually have today Host-level GPU policy lives in `WindowConfig`: ```ts title="backend/main.ts" import { app } from "@tynd/core" app.start({ window: { webgpu: true, hardwareAcceleration: "high-performance", preferredFps: "monitor", // or an integer, clamped to 15..480 gpu: "discrete", // or { vendor: "nvidia" | "amd" | "intel" } colorSpace: "p3", // "srgb" | "p3" | "rec2020" | "linear" hdr: false, vrr: true, contextLostRecovery: true, }, }) ``` These are platform hints, not guarantees. Windows maps them to WebView2 / Chromium arguments. Linux applies WebKitGTK and GPU-offload environment hints before creating the first webview; HDR degrades to sRGB with a host warning. macOS delegates adapter choice and frame pacing to the OS, while `contextLostRecovery` controls web-content-process recovery. Renderer-level tuning remains useful for Three.js / Babylon.js / your own WebGL code: ```ts // In src/main.ts (frontend) const renderer = new THREE.WebGLRenderer({ // Hint to the OS to prefer the discrete GPU on dual-GPU laptops. // Honored by Chromium (Windows / Linux / macOS Hybrid Graphics). powerPreference: "high-performance", // | "low-power" | "default" // Trade FXAA-on-the-render-target for free MSAA. antialias: true, // Set on iGPU laptops if you can't afford the full DPR — most users // can't tell 1.5x from 2x at typical viewing distances. // (Three.js example uses Math.min(devicePixelRatio, 2).) }) ``` ```ts // Frame pacing — adopt the monitor's refresh rate (default). function animate(t: number) { requestAnimationFrame(animate) // ...your render call } ``` The browser's `requestAnimationFrame` is automatically synced to the monitor's refresh rate (60, 120, 144, 240+ Hz on appropriate displays), so you get free V-Sync without doing anything special. ## WebGPU compute (advanced) WebGPU support depends on the installed WebView, GPU and driver. Detect it in the frontend before using it for ML inference (transformers.js with `WebGPUBackend`), image processing, particle systems, or modern 3D renderers (Three.js `WebGPURenderer`): ```ts const adapter = await navigator.gpu?.requestAdapter() const device = await adapter?.requestDevice() ``` Choose your WebGL renderer when there is no adapter and the required WebGL context is available. On Linux, the host sets `WEBKIT_USE_WEBGPU=1` before WebKitGTK starts when `window.webgpu` is not `false`. Older WebKitGTK releases ignore the hint, so applications must still detect `navigator.gpu` and keep a WebGL fallback. ## Detecting GPU capabilities Cleanly degrade when the user's hardware doesn't ship WebGPU or hits a WebGL2 limit: ```ts function getGPUInfo() { const canvas = document.createElement("canvas") const gl = canvas.getContext("webgl2") ?? canvas.getContext("webgl") if (!gl) return null const dbg = gl.getExtension("WEBGL_debug_renderer_info") return { vendor: dbg ? gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL) : "unknown", renderer: dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : "unknown", maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE), webgl2: gl instanceof WebGL2RenderingContext, } } const webgl = getGPUInfo() const webgpu = Boolean(await navigator.gpu?.requestAdapter()) ``` `WEBGL_debug_renderer_info` is optional. When the WebView withholds the extension, use the context and its limits to choose a rendering preset. ## Performance gotchas A handful of patterns cost you frames in any webview-based 3D app — they're not Tynd-specific, but worth flagging: - **Don't `console.log` in `requestAnimationFrame`.** The DevTools bridge is synchronous and slow; even a single log per frame caps you near 60 FPS even on 240 Hz monitors. Use a logger that buffers + flushes once per second. - **Cap `devicePixelRatio` to 2.** Retina + 4K Windows laptops report 3.0+, which quadruples your fragment shader load. `setPixelRatio (Math.min(devicePixelRatio, 2))` is the standard knob. - **Disable `OrbitControls.enableDamping` for fixed-camera scenes.** Damping forces a render every frame even when nothing's moving. - **Use `renderer.info` to check draw calls + triangles.** Render an on-screen HUD that pulls `renderer.info.render.triangles` and `.calls` — over ~500 K triangles and you're CPU-bound on the JS side, not GPU-bound. ## What Tynd doesn't do (yet) - **WebXR / OpenXR (VR / AR).** The OS webview controls XR support; WebView2 ships it experimentally, WKWebView doesn't, WebKitGTK doesn't. No Tynd native bridge today. - **Direct Vulkan / Metal / D3D12 access without the webview.** Run rendering through WebGPU or WebGL in the system webview. - **GPU memory introspection.** Use Chrome DevTools (the webview's built-in inspector) or vendor tools (NVIDIA Nsight, RenderDoc, Xcode Instruments) for the deep dive. ## See also - [`tynd create`](https://kvnpetit.github.io/tynd/docs/v1.0/cli/create) — full CLI reference for the create command (use any framework and `bun add three` for 3D apps). - [Architecture](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/architecture) — where the WebView fits in the three-surface model. - [Runtime](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/runtimes) — Bun and native host packaging (all builds ship the same WebView, GPU support is identical). ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/concepts/ipc TITLE: IPC Model DESCRIPTION: The transport under RPC calls, events, streaming, and OS calls — how Tynd moves data between frontend, Rust host, and backend without touching the network. # IPC Model Tynd's IPC is intentionally boring: **no HTTP, no WebSocket, no TCP port**. Everything rides native WebView bindings + a pair of custom schemes. ## The transport matrix | Channel | Direction | Transport | |---|---|---| | `api.()` | Frontend → Backend | `window.ipc.postMessage` → stdin JSON | | `api.on("evt")` | Backend → Frontend | Rust `evaluate_script` | | `events.emit()` | Backend → Frontend | stdout JSON → Rust → `evaluate_script` | | `dialog` / `fs` / `http` / … | Frontend → Rust (OS APIs) | `window.ipc.postMessage` (direct, no backend round-trip) | | `terminal:data` / `http:progress` | Rust → Frontend (stream) | native user events → `evaluate_script` | | `fs.readBinary` / `compute.hash` / … | Frontend ↔ Rust (binary) | `tynd-bin://` custom scheme, raw bytes | **No HTTP. No WebSocket. No firewall prompt.** ## Frontend serving — `tynd://localhost/` A native custom protocol maps `tynd://localhost/` to the built frontend directory (dev: proxied to the dev server; prod: read from the TYNDPKG-packed assets). The asset cache is pre-warmed on a background thread before the WebView is built, so the first request is instant. ``` GET tynd://localhost/index.html → reads dist/index.html GET tynd://localhost/main.js → reads dist/main.js ``` `window.location.origin` is `tynd://localhost`. You can reason about same-origin exactly as on a normal HTTPS site. ## RPC calls — frontend → backend ```ts // backend/main.ts export async function greet(name: string) { return `Hello, ${name}!`; } // frontend import { createBackend } from "@tynd/core/client"; import type * as backend from "../backend/main"; const api = createBackend(); const msg = await api.greet("Alice"); // "Hello, Alice!" ``` Wire: ```json // frontend → rust (via postMessage) { "type": "call", "id": "c42", "fn": "greet", "args": ["Alice"] } // Rust → Bun backend over framed stdin { "type": "call", "id": "c42", "fn": "greet", "args": ["Alice"] } // backend → rust { "type": "return", "id": "c42", "value": "Hello, Alice!" } // rust → frontend (via evaluate_script of the originating webview) ``` JSON IPC frames are capped at 8 MiB across the WebView, Rust host, and Bun transport. Oversized calls reject immediately instead of waiting for the frontend timeout. Use the binary APIs below for larger payloads. ### Backend failure semantics If Bun exits unexpectedly, every in-flight backend call and stream rejects with `code: "BACKEND_DEAD"`. This state stays active, so calls created after the crash also reject immediately without posting another IPC frame. A successful development reload installs a fresh document and shim, clearing the state. Controlled reloads use one shutdown marker per Bun generation; delayed EOF from the previous process cannot be reported as a crash of the new process. ### Zero-codegen types The frontend only knows the backend by `typeof backend` — no generated files, no IDL, no `.d.ts` step. Rename a backend function and every stale frontend call lights up in the compiler. ```ts const api = createBackend(); // ^^^^^^^^^^^^^^^^ compile-time-only type import ``` `createBackend` is a thin `Proxy` that sends the call by method name. The runtime code is tiny (one `postMessage` + a `Promise.withResolvers`). ## Events — backend → frontend Typed via `createEmitter()`: ```ts // backend import { createEmitter } from "@tynd/core"; export const events = createEmitter<{ userCreated: { id: string; name: string }; }>(); events.emit("userCreated", { id: "1", name: "Alice" }); // frontend api.on("userCreated", (user) => console.log(user.name)); // user: { id, name } api.once("userCreated", (user) => { /* fires once */ }); ``` Wire: `{ "type": "emit", "name": "userCreated", "data": {...} }` lands on stdout, Rust reads the frame and `evaluate_script`s `__tynd_emit__(name, data)` on every subscribed app-local webview (remote-content webviews never receive backend events). ## Streaming RPC — async-generator handlers If a backend export is an `async function*`, the frontend gets a **StreamCall handle** — awaitable and async-iterable: ```ts // backend export async function* processFiles(paths: string[]) { let ok = 0; for (const [i, path] of paths.entries()) { await doWork(path); ok++; yield { path, progress: (i + 1) / paths.length }; } return { ok, failed: paths.length - ok }; } // frontend const stream = api.processFiles(["a.txt", "b.txt"]); for await (const chunk of stream) { render(chunk.progress); // yields } const summary = await stream; // return value // early stop: await stream.cancel(); ``` Three flow-control mechanisms keep streaming safe at arbitrary yield rates: 1. **Per-stream credit** — backend generator starts with 64 credits. Every yield decrements. At 0 credit, the backend awaits a waiter; the frontend replenishes by ACK-ing every 32 consumed chunks. Bounded memory regardless of producer speed. 2. **Yield batching** — Rust buffers yields and flushes either every 10ms or at 64 items per bucket. One `evaluate_script` per webview per flush, not one per chunk. 3. **Cleanup on window close** — when a secondary window closes, Rust cancels every active stream that originated there so generators don't leak. Combined guarantee: 10k+ yields/sec to the UI without freezing it. See the [Streaming RPC guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/streaming). ## OS calls — frontend → Rust directly Native things bypass the TypeScript backend entirely: Install the required plugin: ```bash tynd add dialog ``` ```ts // frontend import { dialog } from "@tynd/plugin-dialog/client"; const path = await dialog.openFile({ filters: [{ name: "Images", extensions: ["png", "jpg"] }] }); ``` Wire: frontend posts `{ type: "os_call", api: "dialog", method: "openFile", args: [...] }`. The native host validates and dispatches the call to the selected Rust API. **Backend never sees OS calls** — the TypeScript backend is only for *your* app logic, not for bridging the frontend to the OS. ### Main-thread vs worker-thread dispatch - `tyndWindow.*` calls run on the **main thread** (event loop proxy) because native windowing requires it. Each request carries the label of the webview that issued it; responses route back to the originating window only. - **Every other OS call** runs in a bounded worker pool. Saturation rejects new work instead of creating unbounded threads or blocking the UI thread. - **Native long-lived resources** (terminal PTYs and WebSocket sessions) survive across calls and keep handles in Rust registries. - **Bun resources** such as SQL connections and backend-only `bunWorkers` keep their registries in the trusted backend process. Renderer `workers` remain sandboxed Web Workers and never send executable code over IPC. ## Binary IPC — `tynd-bin://localhost/` Multi-MB payloads skip JSON entirely. A second custom scheme, `tynd-bin://localhost//?`, carries raw bytes in the request and response bodies — no base64, no JSON envelope, `ArrayBuffer` on arrival. Current routes: | Route | Method | In | Out | |---|---|---|---| | `fs/readBinary?path=...` | `GET` | — | file bytes | | `fs/writeBinary?path=...&createDirs=0\|1` | `POST` | bytes | `204` | | `compute/hash?algo=blake3\|sha256\|sha384\|sha512&encoding=base64` | `POST` | bytes | UTF-8 digest | The origin of the scheme depends on the OS: `tynd-bin://localhost` on macOS and Linux, `http://tynd-bin.localhost` on Windows (WebView2 cannot navigate to custom schemes). The host injects the exact origin as `window.__TYND_BIN_ORIGIN__` into every page; the client reads it first and only falls back to guessing from the user agent when it is absent, since an app can override `navigator.userAgent`. The TS client wraps these — `fs.readBinary(path)`, `compute.hash(bytes)` — users never touch the scheme directly. Small / non-binary calls (`randomBytes`, text helpers, terminal events) stay on the JSON IPC where it's simpler. See the [Binary Data guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/binary-data). ## Event emitter infrastructure Any API that pushes async events to the frontend goes through a central emit helper in the Rust host. At startup, the app wires an emitter that turns each emit into a native user event, which the event loop then forwards to the WebView via `evaluate_script`. Subscribe on the frontend via `window.__tynd__.os_on(name, handler)` — or use the typed wrappers (`tyndWindow.onResized`, a terminal session's `onData`, the `onProgress` option of `http` requests, …). ## Multi-window routing - The primary window has label `"main"`. Additional windows created via `multiwindow.create({ label })` (`@tynd/plugin-multiwindow`) get their own WebView + IPC channel. - Every frontend call includes the originating window's label; responses route back to it only. - Window events (resize, focus, close, …) are delivered to every app-local webview (never to remote content) with a `label` field in the payload. Client-side helpers filter by `__TYND_WINDOW_LABEL__` (injected at WebView creation) so handlers only fire for their own window. See the [Multi-Window guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/multi-window). ## Next - [Build Pipeline](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/build-pipeline) - [TYNDPKG Format](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/tyndpkg) - [Streaming RPC guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/streaming) ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/concepts/observability TITLE: Observability DESCRIPTION: Production observability — structured logs, Sentry crash reporting, and OpenTelemetry traces. Opt-in through tynd.config.ts, zero-cost when off. # Observability Tynd ships an always-on structured logger and two **opt-in** pipelines: Sentry panic reporting and OpenTelemetry (OTLP/gRPC) trace export. Both are off by default; a build that does not use them contains no telemetry code and makes no network calls. Observability is switched on in two places, and both must agree: 1. **Config** — the `observability` block in `tynd.config.ts`. 2. **Build** — the Cargo feature `obs-sentry` and/or `obs-otel` on the host. `tynd build` and `tynd dev` enable the features for you from the config when they compile the host. A config without `observability` compiles neither feature, so the binary size is unchanged. ## What's wired by default Every Tynd build installs a `tracing` stderr layer at startup. You get: - **Structured spans** for IPC calls, plugin dispatch, and scheme handlers. - **Per-target filtering** via `TYND_LOG` (or `RUST_LOG` as fallback). - **Panic capture** routed to `target = "tynd::panic"` with a backtrace, even when `RUST_BACKTRACE` is unset. ```bash # Debug logs from the host, info+ from your app: TYND_LOG="tynd_host=debug,my_app=info" my-app ``` ## Configure ```ts title="tynd.config.ts" import { defineConfig } from "@tynd/cli"; export default defineConfig({ backend: "backend/main.ts", observability: { sentry: { dsn: "https://@o0.ingest.sentry.io/", environment: "production", release: "1.4.0", sampleRate: 1, }, otel: { endpoint: "https://otlp.example.com:4317", serviceName: "my-app", }, }, }); ``` | Field | Type | Default | Notes | |---|---|---|---| | `sentry.dsn` | `string` | — | Required inside `sentry`. A blank value disables Sentry | | `sentry.environment` | `string` | — | Environment tag | | `sentry.release` | `string` | — | Release tag | | `sentry.sampleRate` | `number` | `1` | Between 0 and 1. Validation rejects values outside the range | | `otel.endpoint` | `string` | — | Required inside `otel`. OTLP/gRPC collector URL. A blank value disables OTel | | `otel.serviceName` | `string` | executable name | `service.name` resource attribute | An absent `observability` block, or an absent `sentry` / `otel` object, means that pipeline is disabled with no initialization cost. The serialized block must stay under 4096 bytes. `tynd validate` reports invalid values. ## How the config reaches the app | Run mode | Source | |---|---| | `tynd build` (packaged app) | The config is written into the pack as `observability.json`; the entry is omitted when the field is absent. **Packaged apps ignore the environment variable on purpose**, so a user cannot redirect an app's telemetry | | `tynd dev` | `tynd` exports `TYND_OBSERVABILITY=` to the runtime. It is read only when there is no pack | Initialization happens in `tynd_runtime::run()`, before the Bun backend is spawned and before the event loop starts. Invalid JSON is logged (without echoing values, since they may hold a DSN) and ignored: observability stays disabled and the app still boots. ## Enable at build When the config sets `sentry` or `otel`, `tynd` compiles the host with the matching feature on `tynd-host`: | Config | Cargo feature | |---|---| | `observability.sentry` | `obs-sentry` | | `observability.otel` | `obs-otel` | A host compiled without the requested feature (for example by hand, outside `tynd`) logs a warning for Sentry or an error for OTel at runtime, then continues without that pipeline. Both features increase the release artifact; measure the signed output per target. ## Sentry Sentry reports **Rust panics** in the host. The Sentry panic integration captures them, a chained hook waits up to 2 seconds to flush, and the uncaught-panic path in `run()` flushes again. `tracing` events from the host become breadcrumbs. Privacy defaults: - `send_default_pii` is always `false`; the config has no way to turn it on. - Breadcrumbs and messages are scrubbed: emails become `[email]`, `Bearer ` becomes `Bearer [token]`, and long messages are truncated (about 512 characters). What Sentry does **not** cover: native crashes (no minidump or signal capture, only Rust panics), and frontend or Bun-side errors. Report those from your own code if you need them. ## OpenTelemetry Spans from `tracing` are exported over OTLP/gRPC to a collector you control (Honeycomb, Grafana Tempo, Datadog, Jaeger, a self-hosted collector). The exporter runs on a private single-thread Tokio runtime, so it does not depend on anything in your app. OTel resource attributes carry `service.name` plus whatever fields your spans add. Add spans in Rust with `#[tracing::instrument]` or `tracing::info_span!`; they flow to the exporter once initialized. If `otel` is configured but the host was built without `obs-otel`, the host logs an error and continues without traces. ## Behavior matrix | `sentry` config | `otel` config | `obs-sentry` | `obs-otel` | Result | |---|---|---|---|---| | absent | absent | any | any | no-op, no network | | set | absent | on | any | Sentry installed | | set | absent | **off** | any | warning logged, Sentry skipped | | absent | set | any | on | OTel installed | | absent | set | any | **off** | error logged, OTel skipped | | set | set | on | on | both installed | ## Profiling Tynd does not bundle profilers. For local profiling use the platform profiler on the built host (Instruments on macOS, Windows Performance Recorder/Analyzer on Windows, `heaptrack` or Valgrind on Linux), or `tynd profile` for CPU, Bun-memory, and IPC sessions. For continuous production timing, the OTel pipeline gives span-level latency for every IPC call. ## Recommended backends | Signal | Self-hosted | Managed | |---|---|---| | Traces | Jaeger, Grafana Tempo, OpenTelemetry Collector | Honeycomb, Lightstep, Datadog APM | | Crashes | GlitchTip (Sentry-compatible) | Sentry | Any OTLP/gRPC-compatible collector works for OTel; only `endpoint` changes. The Sentry `dsn` identifies the destination project. ## Related - [`tynd.config.ts`](https://kvnpetit.github.io/tynd/docs/v1.0/cli/config#observability) - [Debugging guide](https://kvnpetit.github.io/tynd/docs/v1.0/guides/debugging) - [Production checklist](https://kvnpetit.github.io/tynd/docs/v1.0/production-checklist) ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/concepts/runtimes TITLE: Runtime DESCRIPTION: Bun is the single JavaScript runtime used by every Tynd app. # Bun runtime Tynd runs every TypeScript backend on Bun. There is no runtime selector in `tynd.config.ts`: ```ts export default { backend: "backend/main.ts", frontendDir: "dist", } ``` Bun provides JIT execution, `Bun.*`, Node-compatible APIs, `Buffer`, `process`, `node:*` imports, npm packages, and native addons. ## Local HTTP servers Use [backend RPC](https://kvnpetit.github.io/tynd/docs/v1.0/guides/backend-rpc) for calls between your WebView and the Bun backend. If another process needs an HTTP endpoint, start one in the backend with [`Bun.serve`](https://bun.com/docs/runtime/http/server): ```ts title="backend/main.ts" import { app } from "@tynd/core"; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) { if (request.method === "GET" && new URL(request.url).pathname === "/health") { return new Response("ok"); } return new Response("Not found", { status: 404 }); }, }); app.onClose(() => { void server.stop(true); }); app.start(); ``` Read `server.url` for the address assigned by the OS. `Bun.serve` runs in the trusted backend. Enforce authorization there before adding routes that read or modify app data, including on loopback. ## Native host Every app runs on a native Rust host that Tynd compiles for it with Cargo from the `@tynd/host-src` dev dependency. The host always contains the core (`acl`, `log`, window, webview, IPC) plus exactly the APIs the project declares: those of its `plugins`, any names listed in `apis`, and `updater` when an `updater` block is configured. Declaring a standalone plugin with a native crate links that Rust crate too. JavaScript always executes on Bun. `tynd dev` compiles the host with the Cargo `dev` profile and `tynd build` with `release`, from the host package generated in `.tynd/build`; Cargo output goes to the [shared host build cache](https://kvnpetit.github.io/tynd/docs/v1.0/concepts/build-pipeline#shared-host-build-cache). The first build takes a few minutes; a dev run whose inputs did not change skips Cargo. `tynd start` runs the release host, so it needs a prior `tynd build`. ```ts export default { backend: "backend/main.ts", frontendDir: "dist", apis: ["fs", "http"], plugins: ["@tynd/plugin-sql"], } ``` Compiling the host requires Bun 1.3+ and Rust 1.95+; see [Installation](https://kvnpetit.github.io/tynd/docs/v1.0/getting-started/installation). You write no Rust application code. ---- URL: https://kvnpetit.github.io/tynd/docs/v1.0/concepts/security TITLE: Security DESCRIPTION: The security model — CSP defaults, scheme allowlists, structural exposure surface, and OS-backed secret storage. # Security Tynd's security model is **structural + conservative-by-default**. The exposure surface of your app is the exported module — code and policy can't drift apart — and the WebView runs with an auto-injected CSP. ## Threat model Tynd targets a single-user desktop environment. The primary concerns: - **Untrusted content injection** into the WebView (XSS from user-supplied HTML, data URLs, `postMessage`-based smuggling). - **Local-machine attackers** sniffing IPC traffic if it were on TCP. *(It isn't — see below.)* - **Supply-chain compromise** of a bundled `.exe` (solved by code signing + notarization). - **Update-channel hijacking** (solved by Ed25519-signed auto-updates). What's **not** in scope: - Protecting app secrets from a user with admin access on their own machine. Disk-encryption + OS-level isolation are the right answer, not app-level obfuscation. Tynd has two startup-only policy layers: [`security`](https://kvnpetit.github.io/tynd/docs/v1.0/api/os/security) for path/URL/process rules, and structured `capabilities` for per-command, per-window, per-webview, per-origin, and per-platform grants. ## Transport — no TCP, no firewall prompt RPC and frontend asset serving never touch a TCP port. Everything rides: - **`tynd://localhost/`** (WebView host custom scheme) for frontend assets. - **`tynd-bin://localhost//?`** (WebView host custom scheme) for binary IPC. - **`window.ipc.postMessage`** for JSON IPC. - **`evaluate_script`** for backend → frontend pushes. Consequence: no loopback port, no firewall prompt on first launch, and no MITM window for another process on the same machine that could listen on a socket. ## CSP — auto-injected Every HTML response served through the `tynd://` scheme carries a baseline Content-Security-Policy header that: - Blocks **inline scripts** (no `` from smuggled HTML). - Disables `frame-src` and `object-src`. - Restricts `connect-src` to same-origin (`tynd://localhost`) plus HTTPS/WSS. - Allows workers from `'self'`, `tynd:` and `blob:` (`worker-src`); `workers.spawn` starts its worker from a `blob:` URL. A page can add its own `` tag. The browser enforces both policies, so a meta tag can only **tighten** the baseline, never loosen it. `loadHtml` documents get the same baseline as a `` tag that Tynd inserts as the first element of the HTML (after a leading ``), because the platform loads that HTML without response headers. The document commits as `about:blank`, so the policy names the bundled origin (`tynd:`, and `http://tynd.localhost` on Windows) instead of relying on `'self'`. Inline `