### Deno Compile and Node Modules Setup Example Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Provides an example directory structure and build script for using Deno compile with Tauri, emphasizing the separation of Deno worker source code from `node_modules`. This prevents Deno from attempting to compile the entire `node_modules` directory, which can lead to stack overflows. ```bash Example setup: ``` examples/ deno-compile/ # Separate Deno package — no node_modules here deno.json # { "imports": { "kkrpc/deno": "npm:kkrpc/deno" } } main.ts # Deno worker source shared-api.ts # Type definitions (copy from backends/) tauri-app/ backends/ # Contains node_modules from npm deno-worker.ts # Used for dev mode (deno run), NOT for deno compile ``` Run `deno install` in the deno package directory to cache dependencies before compiling. The build script should compile from the separate directory: ```bash deno compile --allow-all --output src-tauri/binaries/deno-worker-$TARGET ../deno-compile/main.ts ``` ``` -------------------------------- ### RPC Calls Example Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/examples/tauri-app/README.md Demonstrates various RPC calls that can be made to the backend API, including arithmetic, string echoing, system information retrieval, and Fibonacci computation. These calls are type-safe against the shared BackendAPI interface. ```typescript add(5, 3) echo("hello") getSystemInfo() fibonacci(10) ``` -------------------------------- ### Install tauri-plugin-js in Tauri App (Rust) Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Registers the tauri-plugin-js in the Tauri application's Rust setup by calling `tauri_plugin_js::init()` within the `tauri::Builder`. Also includes adding the dependency to `Cargo.toml` and necessary permissions to `default.json`. ```rust pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_js::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` ```toml [dependencies] tauri-plugin-js = { git = "https://github.com/user/tauri-plugin-js" } ``` ```json { "permissions": [ "core:default", "js:default" ] } ``` -------------------------------- ### Frontend Installation Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/README.md Instructions for installing the necessary JavaScript packages for the tauri-plugin-js API on the frontend of your Tauri application. ```bash pnpm add tauri-plugin-js-api kkrpc ``` -------------------------------- ### Spawn JavaScript Runtime Process Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Starts a named JavaScript runtime process with the specified configuration. Supports managed runtimes, direct binary commands, or Tauri sidecar binaries. ```APIDOC ## POST /spawn ### Description Starts a named JavaScript runtime process with the specified configuration. Returns process information including PID and running status. Supports three spawn modes: managed runtimes (bun/node/deno), direct binary commands, or Tauri sidecar binaries. ### Method POST ### Endpoint /spawn ### Parameters #### Query Parameters - **name** (string) - Required - The unique name for the process. - **config** (object) - Required - The configuration for the spawned process. - **runtime** (string) - Optional - The JavaScript runtime to use ('bun', 'node', 'deno'). Auto-detected if not provided. - **script** (string) - Optional - The path to the script to execute within the runtime. - **command** (string) - Optional - The direct command to execute (e.g., path to a Node.js executable). - **sidecar** (string) - Optional - The name of a compiled binary sidecar to execute. - **cwd** (string) - Optional - The current working directory for the process. - **args** (array of strings) - Optional - Command-line arguments to pass to the process. - **env** (object) - Optional - Environment variables for the process. ### Request Example ```json { "name": "my-bun-worker", "config": { "runtime": "bun", "script": "worker.ts", "cwd": "/path/to/backends", "args": ["--verbose"], "env": {"NODE_ENV": "production"} } } ``` ### Response #### Success Response (200) - **name** (string) - The name of the spawned process. - **pid** (number) - The process ID (PID) of the spawned process. - **running** (boolean) - Indicates if the process is currently running. #### Response Example ```json { "name": "my-bun-worker", "pid": 12345, "running": true } ``` ``` -------------------------------- ### detectRuntimes Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Detects installed JavaScript runtimes (bun, node, deno) on the system, returning their paths, versions, and availability status. ```APIDOC ## detectRuntimes ### Description Detects installed JavaScript runtimes (bun, node, deno) on the system, returning their paths, versions, and availability status. ### Method GET ### Endpoint /detectRuntimes ### Parameters #### Query Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **runtimes** (array) - An array of objects, where each object represents a detected runtime with properties: `name` (string), `path` (string | null), `version` (string | null), `available` (boolean). #### Response Example ```json [ { "name": "bun", "path": "/usr/local/bin/bun", "version": "1.2.0", "available": true }, { "name": "node", "path": "/usr/local/bin/node", "version": "v22.0.0", "available": true }, { "name": "deno", "path": null, "version": null, "available": false } ] ``` ``` -------------------------------- ### JsRuntimeIo Class for Direct Stdio Communication Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Illustrates the JsRuntimeIo class, a low-level IO adapter for kkrpc implementing the IoInterface for direct stdio communication. It shows manual channel setup, API usage, and cleanup for custom implementations. ```typescript import { JsRuntimeIo, spawn } from "tauri-plugin-js-api"; import { RPCChannel } from "kkrpc/browser"; await spawn("worker", { runtime: "bun", script: "worker.ts" }); // Manual channel setup const io = new JsRuntimeIo("worker"); await io.initialize(); const channel = new RPCChannel(io, { expose: {} }); const api = channel.getAPI(); // Use the API const result = await api.someMethod(); // Cleanup await io.destroy(); console.log(io.isDestroyed); // true ``` -------------------------------- ### Backend Worker Implementation (Bun) Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Example implementation of a backend worker using Bun and kkrpc. This worker exposes an API for RPC communication over stdio. It defines functions for arithmetic, echoing messages, and retrieving system information. ```typescript // backends/bun-worker.ts import { RPCChannel, BunIo } from "kkrpc"; import type { BackendAPI } from "./shared-api"; const api: BackendAPI = { async add(a: number, b: number) { return a + b; }, async echo(message: string) { return `[bun] ${message}`; }, async getSystemInfo() { return { runtime: "bun", pid: process.pid, platform: process.platform, arch: process.arch, }; }, async fibonacci(n: number) { const fib = (n: number): number => n <= 1 ? n : fib(n - 1) + fib(n - 2); return fib(n); }, }; const io = new BunIo(Bun.stdin.stream()); const channel = new RPCChannel(io, { expose: api }); ``` -------------------------------- ### Production Deployment: Compiled Sidecar Example Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Illustrates the process of building a compiled sidecar binary for production deployment in a Tauri application. It shows how to determine the target architecture, compile the backend script using Bun, and configure `tauri.conf.json` to include the external binary. Finally, it demonstrates how to spawn the sidecar from the application code. ```bash TARGET=$(rustc -vV | grep host | cut -d' ' -f2) bun build --compile src/backend/main.ts --outfile src-tauri/binaries/backend-$TARGET Add to tauri.conf.json: ```json { "bundle": { "externalBin": ["binaries/backend"] } } ``` Spawn with: ```typescript await spawn("backend", { sidecar: "backend" }); ``` ``` -------------------------------- ### Spawn JavaScript Process (TypeScript) Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Starts a named JavaScript runtime process. Supports spawning managed runtimes (Bun, Node.js, Deno), direct binary commands, or compiled Tauri sidecar binaries. Returns process information including PID and running status. ```typescript import { spawn } from "tauri-plugin-js-api"; // Spawn using a managed runtime const info = await spawn("my-bun-worker", { runtime: "bun", script: "worker.ts", cwd: "/path/to/backends", args: ["--verbose"], env: { NODE_ENV: "production" } }); console.log(`Started process: ${info.name}, PID: ${info.pid}, Running: ${info.running}`); // Spawn using a direct command await spawn("custom-process", { command: "/usr/local/bin/my-runtime", args: ["script.js"] }); // Spawn a compiled sidecar binary (no runtime needed on user machine) await spawn("compiled-worker", { sidecar: "bun-worker" // Resolves from externalBin config }); ``` -------------------------------- ### Backend Worker Implementation (Node.js) Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Example implementation of a backend worker using Node.js and kkrpc. This worker utilizes the `NodeIo` adapter for stdio communication and exposes an API for RPC calls, including arithmetic, echoing messages, and retrieving system information. ```javascript // backends/node-worker.mjs import { RPCChannel, NodeIo } from "kkrpc"; const api = { async add(a, b) { return a + b; }, async echo(message) { return `[node] ${message}`; }, async getSystemInfo() { return { runtime: "node", pid: process.pid, platform: process.platform, arch: process.arch, }; }, }; const io = new NodeIo(process.stdin, process.stdout); const channel = new RPCChannel(io, { expose: api }); ``` -------------------------------- ### Deno Worker Implementation with kkrpc Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/README.md An example of a Deno worker script that implements the shared API and establishes an RPC channel using kkrpc, leveraging Deno's specific APIs. ```typescript import { DenoIo, RPCChannel } from "npm:kkrpc/deno"; import type { BackendAPI } from "./shared-api.ts"; const api: BackendAPI = { /* same methods, using Deno.pid, Deno.build.os, etc. */ }; const io = new DenoIo(Deno.stdin.readable); const channel = new RPCChannel(io, { expose: api }); ``` -------------------------------- ### Install tauri-plugin-js (Rust) Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Add the `tauri-plugin-js` dependency to your Rust project's `Cargo.toml` file. This enables the JavaScript runtime integration for your Tauri application. ```toml [dependencies] tauri-plugin-js = { path = "../path/to/tauri-plugin-js" } ``` -------------------------------- ### Detect JavaScript Runtimes Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Detects installed JavaScript runtimes (bun, node, deno) on the system. It returns an array of objects, each containing the runtime's name, path, version, and availability status. This is useful for dynamically selecting or verifying the presence of required JavaScript environments. ```typescript import { detectRuntimes } from "tauri-plugin-js-api"; const runtimes = await detectRuntimes(); // Output: [ // { name: "bun", path: "/usr/local/bin/bun", version: "1.2.0", available: true }, // { name: "node", path: "/usr/local/bin/node", version: "v22.0.0", available: true }, // { name: "deno", path: null, version: null, available: false } // ] runtimes.forEach(rt => { if (rt.available) { console.log(`${rt.name} ${rt.version} at ${rt.path}`); } }); ``` -------------------------------- ### Node.js Worker Implementation with kkrpc Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/README.md An example of a Node.js worker script (using CommonJS modules) that implements the shared API and sets up an RPC channel with kkrpc. ```javascript import { RPCChannel, NodeIo } from "kkrpc"; const api = { /* same methods */ }; const io = new NodeIo(process.stdin, process.stdout); const channel = new RPCChannel(io, { expose: api }); ``` -------------------------------- ### Bun Worker Implementation with kkrpc Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/README.md An example of a Bun.js worker script that implements the shared API and establishes an RPC channel using kkrpc for communication with the Tauri backend. ```typescript import { RPCChannel, BunIo } from "kkrpc"; import type { BackendAPI } from "./shared-api"; const api: BackendAPI = { async add(a, b) { return a + b; }, async echo(msg) { return `[bun] ${msg}`; }, async getSystemInfo() { return { runtime: "bun", pid: process.pid, platform: process.platform, arch: process.arch }; }, }; const io = new BunIo(Bun.stdin.stream()); const channel = new RPCChannel(io, { expose: api }); ``` -------------------------------- ### Project Structure Overview Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/examples/tauri-app/README.md Provides a detailed breakdown of the project's directory structure, highlighting key files and their purposes, such as Deno configurations, worker scripts for different runtimes (Bun, Node, Deno), build scripts, and Tauri application source files. ```bash examples/ deno-compile/ deno.json main.ts shared-api.ts tauri-app/ backends/ shared-api.ts bun-worker.ts node-worker.mjs deno-worker.ts scripts/ build-sidecars.sh build-workers.sh src/ App.svelte main.js app.css src-tauri/ binaries/ workers/ src/lib.rs capabilities/ tauri.conf.json ``` -------------------------------- ### Get Process Status Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Gets the current status of a specific named process. ```APIDOC ## GET /getStatus ### Description Gets the current status of a specific named process. ### Method GET ### Endpoint /getStatus ### Parameters #### Query Parameters - **name** (string) - Required - The name of the process to get the status for. ### Request Example ```json { "name": "my-bun-worker" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the process. - **pid** (number) - The process ID (PID) of the process. - **running** (boolean) - Indicates if the process is currently running. #### Response Example ```json { "name": "my-bun-worker", "pid": 12345, "running": true } ``` ``` -------------------------------- ### Spawn and Call Backend Process with Runtime Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Demonstrates spawning a backend process using a specified runtime (e.g., Bun) and establishing type-safe RPC communication. It includes setting up event listeners for stdout, stderr, and process exit. ```typescript import { spawn, createChannel, onStdout, onStderr, onExit } from "tauri-plugin-js-api"; import type { BackendAPI } from "../backends/shared-api"; // Spawn const cwd = await resolve("..", "backends"); // from @tauri-apps/api/path await spawn("my-worker", { runtime: "bun", script: "bun-worker.ts", cwd }); // Events onStdout("my-worker", (data) => console.log(data)); onStderr("my-worker", (data) => console.error(data)); onExit("my-worker", (code) => console.log("exited", code)); // Type-safe RPC const { api } = await createChannel, BackendAPI>("my-worker"); const result = await api.add(5, 3); // compile-time checked ``` -------------------------------- ### Process Management API Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Provides functions to manage spawned JavaScript processes, including killing, restarting, listing, and getting the status of processes. ```APIDOC ## POST /kill ### Description Kills a specific named JavaScript process. ### Method POST ### Endpoint `/kill` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the process to kill. ### Request Example ```typescript import { kill } from "tauri-plugin-js-api"; await kill("my-worker"); ``` ## POST /killAll ### Description Kills all currently running JavaScript processes managed by the plugin. ### Method POST ### Endpoint `/killAll` ### Request Example ```typescript import { killAll } from "tauri-plugin-js-api"; await killAll(); ``` ## POST /restart ### Description Restarts a specific named JavaScript process. Optionally, a new configuration can be provided for the restart. ### Method POST ### Endpoint `/restart` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the process to restart. - **config** (object) - Optional - A new configuration object to apply upon restart. See `spawn` for configuration details. ### Request Example ```typescript import { restart } from "tauri-plugin-js-api"; // Restart with the same configuration await restart("my-worker"); // Restart with a new configuration await restart("my-worker", { script: "new-worker.ts", runtime: "node" }); ``` ## GET /listProcesses ### Description Retrieves a list of all currently running JavaScript processes managed by the plugin. ### Method GET ### Endpoint `/listProcesses` ### Response #### Success Response (200) - **processes** (array) - An array of objects, where each object represents a running process. - **name** (string) - The name of the process. - **pid** (number) - The process ID. - **status** (string) - The current status of the process (e.g., "running", "stopped"). ### Response Example ```json { "processes": [ { "name": "my-worker", "pid": 12345, "status": "running" }, { "name": "another-worker", "pid": 67890, "status": "running" } ] } ``` ## GET /getStatus ### Description Gets the status of a specific named JavaScript process. ### Method GET ### Endpoint `/getStatus` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the process to get the status for. ### Response #### Success Response (200) - **status** (string) - The current status of the process (e.g., "running", "stopped"). ### Response Example ```json { "status": "running" } ``` ## POST /writeStdin ### Description Writes raw string data to the standard input of a specific named JavaScript process. ### Method POST ### Endpoint `/writeStdin` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the process to write to. - **data** (string) - Required - The string data to send to stdin. ### Request Example ```typescript import { writeStdin } from "tauri-plugin-js-api"; await writeStdin("my-worker", "Input data for the worker\n"); ``` ``` -------------------------------- ### Spawn and Call JavaScript Runtimes Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Demonstrates how to spawn a JavaScript worker using a specified runtime (e.g., Bun) and communicate with it using type-safe RPC. It also covers handling stdout, stderr, and exit events. ```APIDOC ## POST /spawn ### Description Spawns a named JavaScript process using a specified runtime (e.g., Bun, Node.js, Deno). ### Method POST ### Endpoint `/spawn` ### Parameters #### Query Parameters - **name** (string) - Required - The unique name to identify this process. - **config** (object) - Required - Configuration for spawning the process. - **runtime** (string) - Optional - The runtime to use (e.g., "bun", "node"). If not provided, Tauri attempts to detect a suitable runtime. - **script** (string) - Required - The path to the script to execute within the runtime. - **cwd** (string) - Optional - The current working directory for the spawned process. #### Request Body (Not applicable for this command, configuration is in query parameters) ### Request Example ```typescript import { spawn } from "tauri-plugin-js-api"; await spawn("my-worker", { runtime: "bun", script: "bun-worker.ts", cwd: await resolve("..", "backends") // from @tauri-apps/api/path }); ``` ### Response #### Success Response (200) (No specific response body is detailed, success is indicated by the process starting without error.) #### Response Example (N/A) ## Event: js-process-stdout ### Description Emitted when a spawned JavaScript process writes to its standard output. ### Payload - **name** (string) - The name of the process that emitted the event. - **data** (string) - The data received from stdout. ### Example ```json { "name": "my-worker", "data": "Worker output line" } ``` ## Event: js-process-stderr ### Description Emitted when a spawned JavaScript process writes to its standard error. ### Payload - **name** (string) - The name of the process that emitted the event. - **data** (string) - The data received from stderr. ### Example ```json { "name": "my-worker", "data": "Worker error message" } ``` ## Event: js-process-exit ### Description Emitted when a spawned JavaScript process exits. ### Payload - **name** (string) - The name of the process that exited. - **code** (number | null) - The exit code of the process. `null` if the process was terminated by a signal. ### Example ```json { "name": "my-worker", "code": 0 } ``` ## POST /createChannel ### Description Creates a type-safe communication channel to a named JavaScript process, enabling Remote Procedure Calls (RPC). ### Method POST ### Endpoint `/createChannel` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the process to connect to. #### Request Body (Not applicable for this command, configuration is in query parameters) ### Request Example ```typescript import { createChannel } from "tauri-plugin-js-api"; import type { BackendAPI } from "../backends/shared-api"; // Example type const { api } = await createChannel, BackendAPI>("my-worker"); const result = await api.add(5, 3); // Compile-time checked RPC call console.log(result); // => 8 ``` ### Response #### Success Response (200) - **api** (object) - An object providing methods for type-safe RPC calls to the connected process. #### Response Example ```json { "api": { ... } // Methods for RPC calls, e.g., add(a, b) } ``` ``` -------------------------------- ### Get Status of a Specific JavaScript Process (TypeScript) Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Fetches and returns the current status of a single, named JavaScript process. The status includes the process name, its Process ID (PID), and whether it is currently running. ```typescript import { getStatus } from "tauri-plugin-js-api"; const status = await getStatus("my-bun-worker"); console.log(`Process ${status.name}: PID ${status.pid}, Running: ${status.running}`); // Output: Process my-bun-worker: PID 12345, Running: true ``` -------------------------------- ### Spawn Backend Process using Sidecar Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Illustrates how to spawn a backend process using the `sidecar` option in `tauri-plugin-js-api`, pointing to a pre-compiled binary. RPC communication remains the same as with runtime-based processes. ```typescript import { spawn, createChannel } from "tauri-plugin-js-api"; await spawn("compiled-worker", { sidecar: "bun-worker" }); // RPC works identically const { api } = await createChannel, BackendAPI>("compiled-worker"); await api.add(5, 3); // => 8 ``` -------------------------------- ### spawn Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Spawns a new process, which can be a JavaScript runtime like Node.js, Bun, or Deno, to execute a specified script. This is often used in conjunction with communication APIs like `createChannel` or event listeners. ```APIDOC ## spawn ### Description Spawns a new child process. This function is fundamental for running external scripts or applications, particularly JavaScript runtimes, within the Tauri environment. ### Method POST ### Endpoint /spawn ### Parameters #### Request Body - **processName** (string) - Required - A unique name to identify this spawned process. - **options** (object) - Required - Configuration options for spawning the process: - **runtime** (string) - Required - The JavaScript runtime to use (e.g., "bun", "node", "deno"). - **script** (string) - Required - The path to the script to execute within the specified runtime. - **cwd** (string) - Optional - The current working directory for the spawned process. - **env** (object) - Optional - Environment variables to set for the spawned process. - **args** (array) - Optional - Command-line arguments to pass to the script. ### Request Example ```javascript await spawn("my-worker", { runtime: "bun", script: "worker.ts", cwd: "/backends", args: ["--port", "8080"] }); ``` ### Response #### Success Response (200) This endpoint typically does not return specific data on success, as its primary function is to initiate a process. Success is indicated by the process starting without error. Event listeners or channel communication should be used to monitor the process's status and interact with it. ``` -------------------------------- ### Set and Get Runtime Paths Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Allows overriding the default executable path for a specific JavaScript runtime. An empty string can be passed to clear any custom path override. The `getRuntimePaths` function retrieves all currently set custom path overrides. ```typescript import { setRuntimePath, getRuntimePaths } from "tauri-plugin-js-api"; // Set custom path for node (e.g., nvm-managed version) await setRuntimePath("node", "/usr/local/nvm/versions/node/v22.0.0/bin/node"); // Clear custom path await setRuntimePath("node", ""); // Get all custom path overrides const paths = await getRuntimePaths(); // Output: { "node": "/usr/local/nvm/versions/node/v22.0.0/bin/node" } ``` -------------------------------- ### Implement Deno Worker with kkrpc Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Demonstrates a Deno worker implementation using the DenoIo adapter from kkrpc for communication via npm specifiers. It defines a BackendAPI interface and exposes it through an RPCChannel. ```typescript // backends/deno-worker.ts import { DenoIo, RPCChannel } from "npm:kkrpc/deno"; import type { BackendAPI } from "./shared-api.ts"; const api: BackendAPI = { async add(a: number, b: number) { return a + b; }, async echo(message: string) { return `[deno] ${message}`; }, async getSystemInfo() { return { runtime: "deno", pid: Deno.pid, platform: Deno.build.os, arch: Deno.build.arch, }; }, }; const io = new DenoIo(Deno.stdin.readable); const channel = new RPCChannel(io, { expose: api }); ``` -------------------------------- ### Bundle Worker Scripts as Resources Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Shows bash commands to bundle worker scripts (Bun and Node.js) using Bun build for production deployment, eliminating node_modules dependencies. It includes tauri.conf.json configuration and TypeScript code for resolving and spawning these bundled scripts at runtime. ```bash # Bundle for bun target bun build backends/bun-worker.ts --target bun --outfile src-tauri/workers/bun-worker.js # Bundle for node target bun build backends/node-worker.mjs --target node --outfile src-tauri/workers/node-worker.mjs ``` ```json { "bundle": { "resources": { "workers/bun-worker.js": "workers/bun-worker.js", "workers/node-worker.mjs": "workers/node-worker.mjs" } } } ``` ```typescript import { spawn } from "tauri-plugin-js-api"; import { resolveResource } from "@tauri-apps/api/path"; const script = await resolveResource("workers/bun-worker.js"); await spawn("my-worker", { runtime: "bun", script }); ``` -------------------------------- ### createChannel Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Creates a type-safe kkrpc channel over a process's stdio for bidirectional RPC communication. Returns the channel, a typed API proxy, and the IO adapter. ```APIDOC ## createChannel ### Description Establishes a type-safe Remote Procedure Call (RPC) channel between the Tauri frontend and a spawned backend worker process using the kkrpc library. This enables bidirectional communication. ### Method POST ### Endpoint /createChannel ### Parameters #### Request Body - **processName** (string) - Required - The name of the spawned process to establish the channel with. - **backendApiInterface** (object) - Required - A TypeScript interface defining the API exposed by the backend worker. ### Request Example ```typescript // Define the backend API interface interface BackendAPI { add(a: number, b: number): Promise; echo(message: string): Promise; getSystemInfo(): Promise<{ runtime: string; pid: number; platform: string; arch: string }>; } // Spawn the worker (assuming 'my-worker' is the process name) await spawn("my-worker", { runtime: "bun", script: "worker.ts", cwd: "/backends" }); // Create typed RPC channel const { api, channel, io } = await createChannel, BackendAPI>("my-worker"); // Use the typed API proxy for RPC calls const sum = await api.add(5, 3); console.log(`5 + 3 = ${sum}`); ``` ### Response #### Success Response (200) - **api** (object) - A typed proxy object allowing type-safe calls to the backend API. - **channel** (object) - The kkrpc channel instance. - **io** (object) - The IO adapter for the channel, which can be used for cleanup (e.g., `io.destroy()`). #### Response Example ```json { "api": { ... }, // The typed API proxy object "channel": { ... }, // The kkrpc channel instance "io": { ... } // The IO adapter instance } ``` ``` -------------------------------- ### Bundle Scripts as Resources for Runtime Spawning (Bash & JSON) Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/README.md Explains how to bundle worker scripts (especially those with `node_modules` dependencies like `kkrpc`) into self-contained JS files using Bun for production. These bundled files are then added as Tauri resources. Requires Bun for bundling and Tauri's configuration. ```bash # Bundle for bun target (inlines kkrpc dependency) bun build backends/bun-worker.ts --target bun --outfile src-tauri/workers/bun-worker.js # Bundle for node target bun build backends/node-worker.mjs --target node --outfile src-tauri/workers/node-worker.mjs ``` ```json { "bundle": { "resources": { "workers/bun-worker.js": "workers/bun-worker.js", "workers/node-worker.mjs": "workers/node-worker.mjs" } } } ``` ```typescript import { resolveResource } from "@tauri-apps/api/path"; const script = await resolveResource("workers/bun-worker.js"); await spawn("my-worker", { runtime: "bun", script }); ``` -------------------------------- ### Detect and Configure Runtimes Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Demonstrates using `detectRuntimes` to find available Node.js, Bun, or Deno runtimes on the system and `setRuntimePath` to manually specify the path for a particular runtime. ```typescript import { detectRuntimes, setRuntimePath } from "tauri-plugin-js-api"; const runtimes = await detectRuntimes(); // [{ name: "bun", available: true, version: "1.2.0", path: "/usr/local/bin/bun" }, ...] // Override path for a specific runtime await setRuntimePath("node", "/custom/path/to/node"); ``` -------------------------------- ### Restart JavaScript Runtime Process Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Restarts a named process, optionally with a new configuration. If no config is provided, uses the original spawn configuration. ```APIDOC ## POST /restart ### Description Restarts a named process, optionally with a new configuration. If no config is provided, uses the original spawn configuration. ### Method POST ### Endpoint /restart ### Parameters #### Query Parameters - **name** (string) - Required - The name of the process to restart. - **newConfig** (object) - Optional - The new configuration for the restarted process. If omitted, the original configuration is used. - **runtime** (string) - Optional - The JavaScript runtime to use ('bun', 'node', 'deno'). - **script** (string) - Optional - The path to the script to execute within the runtime. - **cwd** (string) - Optional - The current working directory for the process. - **args** (array of strings) - Optional - Command-line arguments to pass to the process. - **env** (object) - Optional - Environment variables for the process. ### Request Example ```json { "name": "my-bun-worker", "newConfig": { "runtime": "bun", "script": "updated-worker.ts", "env": {"DEBUG": "true"} } } ``` ### Response #### Success Response (200) - **name** (string) - The name of the restarted process. - **pid** (number) - The new process ID (PID) of the restarted process. - **running** (boolean) - Indicates if the process is currently running. #### Response Example ```json { "name": "my-bun-worker", "pid": 54321, "running": true } ``` ``` -------------------------------- ### Permission Table Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/permissions/autogenerated/reference.md The permission table provides a detailed breakdown of each permission identifier and its corresponding description, indicating whether a command is allowed or denied. ```APIDOC ## Permission Table | Identifier | | Description | |---|---| | `js:allow-detect-runtimes` | Enables the detect_runtimes command without any pre-configured scope. | | `js:deny-detect-runtimes` | Denies the detect_runtimes command without any pre-configured scope. | | `js:allow-get-runtime-paths` | Enables the get_runtime_paths command without any pre-configured scope. | | `js:deny-get-runtime-paths` | Denies the get_runtime_paths command without any pre-configured scope. | | `js:allow-get-status` | Enables the get_status command without any pre-configured scope. | | `js:deny-get-status` | Denies the get_status command without any pre-configured scope. | | `js:allow-kill` | Enables the kill command without any pre-configured scope. | | `js:deny-kill` | Denies the kill command without any pre-configured scope. | | `js:allow-kill-all` | Enables the kill_all command without any pre-configured scope. | | `js:deny-kill-all` | Denies the kill_all command without any pre-configured scope. | | `js:allow-list-processes` | Enables the list_processes command without any pre-configured scope. | | `js:deny-list-processes` | Denies the list_processes command without any pre-configured scope. | | `js:allow-restart` | Enables the restart command without any pre-configured scope. | | `js:deny-restart` | Denies the restart command without any pre-configured scope. | | `js:allow-set-runtime-path` | Enables the set_runtime_path command without any pre-configured scope. | | `js:deny-set-runtime-path` | Denies the set_runtime_path command without any pre-configured scope. | | `js:allow-spawn` | Enables the spawn command without any pre-configured scope. | | `js:deny-spawn` | Denies the spawn command without any pre-configured scope. | | `js:allow-write-stdin` | Enables the write_stdin command without any pre-configured scope. | | `js:deny-write-stdin` | Denies the write_stdin command without any pre-configured scope. | ``` -------------------------------- ### Event Listeners for Processes (onStdout, onStderr, onExit) Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Provides event listeners for monitoring the standard output (stdout), standard error (stderr), and exit events of spawned processes. Each listener returns an 'unlisten' function. ```APIDOC ## onStdout ### Description Listens for data emitted to the standard output (stdout) of a spawned process. ### Method POST ### Endpoint /onStdout ### Parameters #### Request Body - **processName** (string) - Required - The name of the spawned process to listen to. - **callback** (function) - Required - The function to be called when stdout data is received. It receives the data as an argument. ### Request Example ```javascript await onStdout("my-worker", (data) => { console.log("[stdout]", data); }); ``` ### Response #### Success Response (200) - **unlisten** (function) - A function that, when called, removes the stdout listener. ## onStderr ### Description Listens for data emitted to the standard error (stderr) of a spawned process. ### Method POST ### Endpoint /onStderr ### Parameters #### Request Body - **processName** (string) - Required - The name of the spawned process to listen to. - **callback** (function) - Required - The function to be called when stderr data is received. It receives the data as an argument. ### Request Example ```javascript await onStderr("my-worker", (data) => { console.error("[stderr]", data); }); ``` ### Response #### Success Response (200) - **unlisten** (function) - A function that, when called, removes the stderr listener. ## onExit ### Description Listens for the exit event of a spawned process. ### Method POST ### Endpoint /onExit ### Parameters #### Request Body - **processName** (string) - Required - The name of the spawned process to listen to. - **callback** (function) - Required - The function to be called when the process exits. It receives the exit code as an argument. ### Request Example ```javascript await onExit("my-worker", (code) => { console.log(`Process exited with code: ${code}`); }); ``` ### Response #### Success Response (200) - **unlisten** (function) - A function that, when called, removes the exit listener. ``` -------------------------------- ### Multi-Window Capabilities Configuration Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Specifies the configuration for enabling multi-window capabilities in a Tauri application. It defines the windows that the plugin can interact with and the necessary core permissions, including the specific permission required for creating new webview windows. ```json { "windows": ["main", "window-*"], "permissions": [ "core:default", "core:event:default", "core:webview:allow-create-webview-window" ] } ``` -------------------------------- ### List Managed Processes Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Returns an array of all currently managed processes with their status information. ```APIDOC ## GET /listProcesses ### Description Returns an array of all currently managed processes with their status information. ### Method GET ### Endpoint /listProcesses ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **processes** (array of objects) - An array containing the status of each managed process. - **name** (string) - The name of the process. - **pid** (number) - The process ID (PID) of the process. - **running** (boolean) - Indicates if the process is currently running. #### Response Example ```json { "processes": [ { "name": "bun-worker", "pid": 12345, "running": true }, { "name": "node-worker", "pid": 12346, "running": true } ] } ``` ``` -------------------------------- ### Connect kkrpc with Tauri IO Adapter in TypeScript Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md This TypeScript code demonstrates how to instantiate the TauriEventIo adapter, initialize it, and then use it to create a kkrpc.RPCChannel. This allows for type-safe remote procedure calls between the frontend and the backend process managed by Tauri. ```typescript import { RPCChannel } from "kkrpc/browser"; import type { BackendAPI } from "../backend/types"; // Assuming types are defined elsewhere const io = new TauriEventIo(); await io.initialize(); // Create an RPC channel using the Tauri IO adapter const channel = new RPCChannel<{}, BackendAPI>(io, { expose: {} }); const api = channel.getAPI() as BackendAPI; // Example of a type-safe call to the backend API const result = await api.add(5, 3); console.log(`Result from backend: ${result}`); // Example usage ``` -------------------------------- ### Runtime Detection and Path Configuration (TypeScript) Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/README.md Shows how to detect available JavaScript runtimes (like Bun, Node, Deno) on the system, override their executable paths, and retrieve the configured paths. Uses functions from 'tauri-plugin-js-api'. ```typescript import { detectRuntimes, setRuntimePath, getRuntimePaths } from "tauri-plugin-js-api"; const runtimes = await detectRuntimes(); // => [{ name: "bun", path: "/usr/local/bin/bun", version: "1.2.0", available: true }, ...] // Override a runtime's executable path await setRuntimePath("node", "/usr/local/nvm/versions/node/v22.0.0/bin/node"); // Get all custom path overrides const paths = await getRuntimePaths(); ``` -------------------------------- ### List All Managed JavaScript Processes (TypeScript) Source: https://context7.com/huakunshen/tauri-plugin-js/llms.txt Retrieves and returns an array containing status information for all JavaScript processes currently being managed by the plugin. Each process object includes its name, PID, and running status. ```typescript import { listProcesses } from "tauri-plugin-js-api"; const processes = await listProcesses(); // Output: [ // { name: "bun-worker", pid: 12345, running: true }, // { name: "node-worker", pid: 12346, running: true } // ] processes.forEach(proc => { console.log(`${proc.name}: PID ${proc.pid}, Running: ${proc.running}`); }); ``` -------------------------------- ### Runtime Detection and Path Configuration Source: https://github.com/huakunshen/tauri-plugin-js/blob/main/SKILL.md Utilities for detecting available JavaScript runtimes (Bun, Node.js, Deno) on the system and for setting custom paths for these runtimes. ```APIDOC ## GET /detectRuntimes ### Description Detects the availability and versions of common JavaScript runtimes (Bun, Node.js, Deno) installed on the system. ### Method GET ### Endpoint `/detectRuntimes` ### Response #### Success Response (200) - **runtimes** (array) - An array of objects, each describing a detected runtime. - **name** (string) - The name of the runtime (e.g., "bun", "node", "deno"). - **available** (boolean) - Indicates if the runtime is available on the system. - **version** (string | null) - The version of the runtime, or null if not available. - **path** (string | null) - The executable path of the runtime, or null if not available. ### Response Example ```json [ { "name": "bun", "available": true, "version": "1.2.0", "path": "/usr/local/bin/bun" }, { "name": "node", "available": true, "version": "18.17.0", "path": "/usr/local/bin/node" }, { "name": "deno", "available": false, "version": null, "path": null } ] ``` ## POST /setRuntimePath ### Description Sets a custom executable path for a specific JavaScript runtime. This allows overriding the system's default detection. ### Method POST ### Endpoint `/setRuntimePath` ### Parameters #### Query Parameters - **rt** (string) - Required - The name of the runtime to configure (e.g., "node", "bun", "deno"). - **path** (string) - Required - The custom absolute path to the runtime executable. ### Request Example ```typescript import { setRuntimePath } from "tauri-plugin-js-api"; await setRuntimePath("node", "/custom/path/to/node"); ``` ## GET /getRuntimePaths ### Description Retrieves the current custom path overrides for JavaScript runtimes. ### Method GET ### Endpoint `/getRuntimePaths` ### Response #### Success Response (200) - **paths** (object) - An object where keys are runtime names and values are their custom paths. ### Response Example ```json { "node": "/custom/path/to/node" } ``` ```