Skip to content

Backend (@tynd/core)

The backend module drives the app’s lifecycle and declares window/menu/tray config.

Call once at the bottom of your backend entry file. The host reads the config on stdout’s first line, builds the window, and starts the event loop.

import { app } from "@tynd/core";
app.start({
frontendDir: import.meta.dir + "/../dist",
window: {
title: "My App",
width: 1200,
height: 800,
center: true,
},
});
Field Type Description
window WindowConfig Window options (see below)
frontendDir string Path to built frontend assets
devUrl string Dev server URL (auto-detected; overrides frontendDir in dev)
menu MenuSubmenu[] Native menu bar (needs @tynd/plugin-menu)
tray TrayConfig System tray (needs @tynd/plugin-tray)
security SecurityPolicy Startup-only path, URL, process, shell, and sensitive-capability scopes
capabilities Capability[] Explicit renderer-native command grants. Omitted or empty means deny all.
quitOnLastWindowClosed boolean (default false) Exit when the last window closes. Leave off for tray-only apps that should stay alive in the background.
assets { scope: string[] } Enable the asset protocol behind convertFileSrc: globs over absolute paths the WebViews may load. Absent means off. See Custom protocols.

Unknown keys are rejected at every level (window: { titel }, security: { fs: { alow } }): app.start() throws Invalid app.start() config with a <path>: unknown option "<key>" line that lists the valid options. Open records such as a permission’s scope accept any key. plugins and other build settings belong in tynd.config.ts, not here.

Field Default Description
title "" Window title
width 1200 Initial width
height 800 Initial height
minWidth / minHeight — Minimum size
maxWidth / maxHeight — Maximum size
resizable true Allow resize
decorations true Show title bar
transparent false Transparent background
alwaysOnTop false Pin above other windows
center false Center on screen at startup
x / y — Initial position of the outer frame, in logical pixels; set both. center wins when both are set
fullscreen false Start fullscreen
maximized false Start maximized
visible true false keeps the window hidden until the frontend calls tyndWindow.show(). See Show the window when ready
kiosk false Start in kiosk mode: borderless fullscreen pinned above other windows
titleBarStyle "visible" macOS title bar: "visible", "transparent" or "overlay" (page drawn under the traffic lights). Ignored on Windows and Linux
theme "system" Native chrome theme: "light", "dark" or "system"
skipTaskbar false Keep the window out of the taskbar (Windows, Linux; ignored on macOS)
backgroundColor — { r, g, b, a? } (0-255) painted before the page loads
userAgent — Custom User-Agent string set on every webview request.
incognito false Non-persistent data store: cookies, cache and local storage are discarded when the window closes
newWindow "allow" window.open() / target="_blank" handling: "allow", "external" or "deny". See New windows
downloads — "allow" or "deny". Unset allows only app-local (and app-local blob:) downloads while the window shows app content. See Downloads
proxy — http://host[:port] or socks5://host:port, no credentials. Works on every platform (macOS 14+). See Proxy
webgpu true Enable WebGPU (ignored on macOS)
hardwareAcceleration "default" "default", "high-performance" or "low-power" GPU hint
preferredFps "monitor" "monitor" or an integer frame-rate cap, clamped to 15..480
contextLostRecovery true Reload the webview when the GPU / web-content process dies (macOS)
colorSpace — "srgb", "p3", "rec2020" or "linear"
hdr false Request an HDR10 surface (Windows, macOS)
vrr false Variable refresh rate
gpu — "auto", "primary", "discrete" or { vendor: "nvidia" | "amd" | "intel" }

The GPU keys are platform hints, not guarantees; see GPU acceleration.

Fires on __tynd_page_ready — a one-shot postMessage sent from the JS_PAGE_READY init script on DOMContentLoaded.

app.onReady(() => {
console.log("window shown, WebView alive");
});

Fires when the user closes the primary window. The window is hidden immediately; you have 2 seconds to run handlers before a watchdog force-exits.

app.onClose(() => {
// quick cleanup only — don't block
});

Create a typed event bus. Exporting the result makes it subscribable from the frontend.

import { createEmitter } from "@tynd/core";
export const events = createEmitter<{
fileChanged: { path: string };
progress: { percent: number };
}>();
events.emit("fileChanged", { path: "/foo.ts" });
events.emit("progress", { percent: 42 });
// Target a single window — other windows don't receive the event.
events.emitTo("settings", "progress", { percent: 42 });

Without a target, emit reaches app-local webviews only (bundled pages, dev server). A webview showing remote content never receives broadcasts; target it explicitly (emitTo).

Frontend subscribes:

api.on("fileChanged", ({ path }) => { /* … */ });
api.once("progress", ({ percent }) => { /* … */ });

Frontend -> backend events (onFrontendEmit + createFrontendEmitter)

Section titled “Frontend -> backend events (onFrontendEmit + createFrontendEmitter)”

The mirror of createEmitter: frontend emits, backend listens. Reuses the same RPC pipe — no new transport.

backend/main.ts
import { onFrontendEmit } from "@tynd/core";
onFrontendEmit<string>("toast", (text) => log.info(text));
src/toast.ts
import { createFrontendEmitter } from "@tynd/core/client";
const frontend = createFrontendEmitter<{ toast: string }>();
frontend.emit("toast", "Saved!");

onFrontendEmit returns an unsubscribe function. Handlers survive frontend navigations. clearFrontendListeners(name?) drops every handler, or only those of name; use it in test teardown or app.onClose.

import { clearFrontendListeners } from "@tynd/core";
app.onClose(() => clearFrontendListeners());

Run raw JavaScript in a webview from the backend. When label is omitted the script runs on every open window that shows app-local content; target a webview showing remote content explicitly with label.

import { evalInFrontend } from "@tynd/core";
evalInFrontend(`document.body.classList.add('debug')`);
evalInFrontend(`location.reload()`, "settings");

Run trusted backend computation on Bun.Worker threads:

import { bunWorkers } from "@tynd/core";
const worker = await bunWorkers.spawn(
(values: number[]) => values.reduce((sum, value) => sum + value, 0),
);
const total = await worker.run<number, number[]>([1, 2, 3, 4]);
await worker.terminate();

This API is backend-only. Renderer code uses workers, which stays inside the WebView sandbox so executable source never crosses into the trusted Bun process.

Tynd has no separate “utility process” API: Bun covers the cases.

Need Use
CPU-bound function, run and return bunWorkers.spawn(fn)
Long-lived thread with its own message protocol new Worker(new URL("./indexer.ts", import.meta.url)) with postMessage / onmessage
Crash isolation (native addons, untrusted parsers) Bun.spawn({ cmd, ipc }), a separate process

Threads die with the backend; a crash in one takes the backend down. A child process survives its own crash, so restart it from onExit and stop it when the app quits:

let quitting = false;
let indexer: ReturnType<typeof Bun.spawn>;
function startIndexer(script: string) {
indexer = Bun.spawn({
cmd: ["bun", script],
ipc: (message) => emit("indexed", message),
onExit: (_proc, code) => {
if (code !== 0 && !quitting) startIndexer(script);
},
});
}
startIndexer(indexerScriptPath);
app.onClose(() => {
quitting = true;
indexer.kill();
});

indexer.send(value) posts to the child; the child reads with process.on("message", ...) and answers with process.send(...). The child script and the bun it runs with must ship with the app.

Inside a backend function, a JS plugin method, middleware, or a plugin ipc:* hook, getCallContext() tells you which webview issued the call:

import { getCallContext } from "@tynd/core";
export async function deleteAll() {
const caller = getCallContext(); // { window, webview, origin, isAppContent, signal } | undefined
if (caller?.window !== "admin") throw new Error("admin window only");
// ...
}
Field Meaning
window Label of the window that owns the calling webview. getWindow(caller.window) returns its handle
webview Label of the calling webview (child webviews differ from their window)
origin Origin of the calling frame when it shows remote content, null for the app’s own pages
isAppContent true for the app’s own pages (bundled or dev server), false for remote content
signal AbortSignal that aborts when the caller gives up (see Cancellation)

The host attaches this to every forwarded call and overwrites anything the frontend sent, so it can be trusted. It is undefined outside a call (startup code, timers created at module load) and when the host sent none or a malformed value. It stays available across await, for the whole life of a streaming call.

signal aborts with an AbortError when:

  • the frontend calls handle.cancel(), breaks out of a for await, or the signal / timeout of api.withOptions(...) fires;
  • the calling window closes, or its page navigates or reloads.

The frontend promise has already rejected at that point, and the handler’s result is dropped. Pass the signal to whatever accepts one:

export async function search(query: string) {
const { signal } = getCallContext()!;
const res = await fetch(`https://api.example.com/search?q=${encodeURIComponent(query)}`, { signal });
return res.json();
}

To restrict who may call a function without writing code, use backend:<fn> capabilities (see Security).

Registers a function that runs around every backend function and JS plugin method, in registration order (the first registered is the outermost). Register before app.start().

app.use(async (ctx, next) => {
// ctx: { fn: string; args: unknown[]; caller: CallContext | undefined; plugin?: string }
const started = performance.now();
try {
return await next();
} finally {
log.info(`${ctx.fn} took ${Math.round(performance.now() - started)}ms`);
}
});
app.use(async (ctx, next) => {
if (ctx.fn === "deleteAll" && ctx.caller?.window !== "admin") throw new Error("denied");
return next();
});
  • ctx.fn is the function name, or the method name when ctx.plugin is set.
  • ctx.args may be replaced before next() to rewrite the arguments.
  • Return without calling next() to short-circuit with your own value; throw to reject the call through the normal IPC error path.
  • Calling next() twice in one middleware throws. Passing something other than a function to app.use throws a TypeError.
  • Plugin ipc:before / ipc:after hooks run outside user middleware.

Serves the URL scheme name:// from the backend. Every WebView request to it runs handler, which returns a Response. Register before app.start(); build URLs in the frontend with protocolUrl(name, path).

app.protocol("thumbs", async (request, { webview }) => {
const id = new URL(request.url).pathname.slice(1);
return new Response(await renderThumbnail(id), { headers: { "content-type": "image/png" } });
});

Only app pages can reach the scheme. Request and response bodies are buffered and capped at 4 MiB. Names, limits and security rules: Custom protocols.

Plugins built with defineTyndPlugin (from @tynd/plugin-sdk/hooks) can declare these hooks:

Hook Fires Notes
app:beforeStart(cx, config) Before the config is sent to the host Awaited
app:ready(cx) When the primary page is ready
app:beforeQuit(cx) On orderly shutdown, before app.onClose handlers Awaited, capped at 3 s
ipc:before(cx, cmd, args) Before each backend call Throw to reject the call. cmd is the raw wire name; plugin methods look like $plugin$<name>$<method>
ipc:after(cx, cmd, result) After each successful call Errors are logged and never change the result
window:created(cx, { label }) / window:closed(cx, { label }) When a window is created or destroyed Needs a host that sends window events

cx is { name, log: { debug, info, warn, error }, state }. A hook that throws is logged and does not block other plugins (except ipc:before, which rejects the call). See the @tynd/plugin-sdk README for the full contract.

definePlugin({ name, methods }) declares a JavaScript plugin; export the result as the default of the plugin’s backend file. The frontend calls its methods through createPluginClient (see RPC helpers).

plugin/backend.ts
import { definePlugin } from "@tynd/core";
let count = 0;
export default definePlugin({
name: "counter",
methods: {
increment() { count += 1; return count; },
reset() { count = 0; },
},
});
  • Method names must match ^[A-Za-z_][A-Za-z0-9_-]{0,63}$, and every value in methods must be a function, or registration throws.
  • Methods are bound to methods, so this.other() works.
  • tynd build / tynd dev register each entry of tynd.config.ts::plugins with the running backend; app code never registers a plugin itself. Registering the same plugin twice is a no-op; a different plugin under a taken name throws.

definePlugin, createPluginClient and the plugin types are also exported from @tynd/core/plugin, which has no Bun or Node imports: a plugin client or a frontend module can import it safely.

Calls a native host API from the trusted Bun backend. It is not available in the WebView. It is meant for pure TypeScript plugins that need one native primitive.

import { hostCall } from "@tynd/core";
const info = await hostCall<{ name: string }>("os", "info");
  • Rejects until app.start() has run.
  • opts.timeoutMs rejects the call after that many milliseconds; default 5 minutes, 0 disables the deadline.
  • At most 4096 calls may be pending; beyond that the call rejects.

A failed backend RPC call rejects with a TyndIpcError (exported by @tynd/core and @tynd/core/client). Switch on code instead of matching message; fn holds the RPC function name. Native OS calls still reject with a plain Error.

import { TyndIpcError } from "@tynd/core/client";
try {
await api.save(doc);
} catch (e) {
if (e instanceof TyndIpcError && e.code === "PERMISSION_DENIED") showDenied();
else throw e;
}
code Meaning
UNKNOWN_FN No exported function or plugin method of that name, or a reserved name
INVALID_ARGS Arguments failed validation or decoding
HANDLER_THREW The backend handler threw
CANCELLED The client cancelled the call
TIMEOUT The call exceeded its timeout
PERMISSION_DENIED A security policy refused the call (detected from the error message)
BACKEND_DEAD The Bun process exited during the call
PROTOCOL_ERROR Wire encoding or decoding failed
Import Content
@tynd/core Backend API (this page)
@tynd/core/client Frontend API and the core clients (app, tyndWindow, tyndWebview, os, path, monitors, security, log, workers, RPC helpers)
@tynd/core/client/bridge The host bridge plugin clients build on (osCall, osOn, binFetch, …). See Bridge
@tynd/plugin-<api>/client An official plugin client, for example @tynd/plugin-dialog/client
@tynd/plugin-menu, @tynd/plugin-tray The MenuItem / MenuSubmenu and TrayConfig types
@tynd/core/plugin definePlugin, createPluginClient and the plugin types, with no Bun or Node imports
@tynd/core/testing installTyndMock(), a mock of the IPC bridge for frontend unit tests (osFallback answers OS calls with no handler)
@tynd/core/env Ambient types for the frontend (tsconfig types)

The menu bar needs the menu official plugin. Without it, a configured menu stops app startup with an error naming @tynd/plugin-menu.

Install the required plugin:

Terminal window
tynd add menu
app.start({
menu: [
{
type: "submenu",
label: "File",
items: [
{ label: "New", id: "file.new", accelerator: "CmdOrCtrl+N" },
{ label: "Open", id: "file.open", accelerator: "CmdOrCtrl+O" },
{ type: "separator" },
{ label: "Quit", role: "quit" },
],
},
{
type: "submenu",
label: "Edit",
items: [
{ label: "Undo", role: "undo" }, { label: "Redo", role: "redo" },
{ type: "separator" },
{ label: "Cut", role: "cut" }, { label: "Copy", role: "copy" }, { label: "Paste", role: "paste" },
],
},
],
// ...
});

React to clicks from the frontend with the menu API:

import { menu } from "@tynd/plugin-menu/client";
menu.onClick("file.new", () => createDocument());

app.start() validates every item against one of five shapes and throws Invalid app.start() config otherwise. Top-level menu entries must be submenus. The types come from the plugin packages:

import type { MenuItem, MenuSubmenu } from "@tynd/plugin-menu";
import type { TrayConfig } from "@tynd/plugin-tray";
Shape Fields
Item { type?: "item", label, id?, enabled?, role?, accelerator? }
Checkbox { type: "checkbox", label, id?, enabled?, checked?, accelerator? }
Radio { type: "radio", label, id?, enabled?, checked?, accelerator? }
Separator { type: "separator" }
Submenu { type: "submenu", label, enabled?, items: MenuItem[] }
  • label is required on every shape except the separator, role items included.
  • id defaults to label; it is the value menu.onClick and tray.onMenu match.
  • accelerator uses the muda format, for example "CmdOrCtrl+S" or "Alt+F4". An invalid accelerator is logged and dropped.
  • role is one of quit, copy, cut, paste, undo, redo, selectAll, minimize, close, separator, about. A role item becomes the OS-provided item, which the OS manages.
  • Adjacent radio items form a group (a separator or another item ends it): clicking one, or checking it with menu.setItemChecked / tray.setItemChecked, unchecks the others.

The tray needs the tray official plugin. Without it, a configured tray stops app startup with an error naming @tynd/plugin-tray.

Install the required plugin:

Terminal window
tynd add tray
app.start({
tray: {
icon: import.meta.dir + "/assets/tray.png",
tooltip: "My App",
menu: [
{ label: "Show", id: "show" },
{ label: "Quit", id: "quit" },
],
},
// ...
});

Handle clicks with the tray API:

import { app, tyndWindow } from "@tynd/core/client";
import { tray } from "@tynd/plugin-tray/client";
tray.onClick(() => tyndWindow.show());
tray.onMenu("quit", () => app.exit(0));

From the frontend:

import { createBackend } from "@tynd/core/client";
import type * as backend from "../../backend/main";
const api = createBackend<typeof backend>();
const msg = await api.greet("Alice"); // fully typed
api.on("fileChanged", (evt) => { /* … */ });
api.once("progress", (evt) => { /* … */ });
  • Types flow from typeof backend — no codegen.
  • Errors thrown on the backend surface as rejected promises carrying a TyndIpcError.
  • async function* backend handlers return StreamCall handles — awaitable + async-iterable.
  • Every call handle has cancel(). api.withOptions({ signal, timeout }) returns the same functions with a cancel signal, a deadline, or both:
const ac = new AbortController();
const hits = await api.withOptions({ signal: ac.signal, timeout: 5_000 }).search("tynd");
Option Effect
signal Aborting it cancels the call: the promise (or a stream’s iteration) rejects with signal.reason, an AbortError by default
timeout After this many milliseconds the call is cancelled and rejects with a TyndIpcError of code TIMEOUT

Either way the handler’s getCallContext().signal aborts. A call is also cancelled when its page navigates or reloads, or its window closes.

  • Arguments and results are devalue strings inside JSON frames. Uint8Array and ArrayBuffer work but travel as base64 (about 4/3 of their size, plus JSON escaping), and a frame is capped at 8 MiB, so keep binary payloads under about 5 MiB per call. Move larger data as described in Binary data.

A call argument the backend can push to any number of times. Messages go to the calling webview only, in order. The frontend passes new Channel<T>(onMessage) from @tynd/core/client; the types follow from the backend signature.

// backend
import type { Channel } from "@tynd/core";
export async function download(url: string, progress: Channel<number>) {
for await (const percent of fetchWithProgress(url)) progress.send(percent);
progress.close();
}
// frontend
import { Channel } from "@tynd/core/client";
const progress = new Channel<number>((percent) => (bar.value = percent));
progress.onclose = () => bar.remove();
await api.download(url, progress);
Member Side Meaning
send(message) backend Push one devalue-encodable value. Throws after close()
close() backend End the channel; the frontend’s onclose runs
closed both true once closed
onmessage / onclose frontend Message and end handlers
close() frontend Stop listening. The backend is not told: cancel the call for that

Only top-level arguments can be channels. For a pull-based stream with back-pressure, return an async generator (Streaming RPC).

getWindow(label) handles have the same on* event methods as tyndWindow in the frontend (onResized, onMoved, onFocused, onCloseRequested, onClosed, onPageLoad, onDrop…), except onDragOver.

onCloseRequested works for every window, the main one and secondary ones, in a renderer or in the backend. Call event.preventDefault() synchronously to keep the window open:

import { getWindow } from "@tynd/core";
getWindow("editor").onCloseRequested((event) => {
if (hasUnsavedChanges("editor")) event.preventDefault();
});

A close request from the user waits 500 ms for a handler to prevent it, then the window closes. Closing a window from code (handle.close()) is not preventable.

Writes one JSON report per crash to a local directory. Nothing is uploaded: the app reads the reports, usually on its next start, and decides what to send where.

app.start({ window: { title: "My App" } });
await app.crashReporter.start({
onCrash: (report) => telemetry.send({ kind: report.kind, message: report.message }),
});
const last = await app.crashReporter.getLastCrash();
Method Meaning
start({ directory?, onCrash? }) Start writing reports. directory must be absolute; it defaults to <local app data>/<app>/crashes. onCrash receives each report it has not seen yet: crashes of earlier runs during start(), then renderer losses of this run. Call it after app.start()
getCrashReports() Every report, newest first
getLastCrash() The newest report, or undefined
kind Written by Extra fields
host-panic the native host, when a panic escapes it location, backtrace, thread
backend-exit the native host, when the Bun backend exits on its own (uncaught exception, process.exit, killed) exitCode, stderr (last 50 lines, where an uncaught stack ends up)
render-process-gone the backend, when a renderer dies label, reason

Every report also has time (ms since epoch), message, appVersion, os, arch and file (its path); native reports add tyndVersion.

Fires when a webview’s renderer process dies. event.reload() reloads that window.

app.on("render-process-gone", (event) => {
// event: { label, reason, reload() }
if (event.reason !== "browser-exited") void event.reload();
});
Platform Source reason
Windows WebView2 ProcessFailed crashed, unresponsive, frame-crashed, or browser-exited (the whole WebView2 runtime is gone; reloading cannot help)
macOS WebKit web content process termination Always crashed. The host reloads the page itself
Linux — Not reported