### Install and Run Next.js Example Source: https://github.com/vercel-labs/wterm/blob/main/examples/nextjs/README.md Steps to install dependencies, build the project, and run the Next.js development server. ```bash pnpm install zig build pnpm --filter nextjs dev ``` -------------------------------- ### Install and Run Ghostty Example Source: https://github.com/vercel-labs/wterm/blob/main/examples/ghostty/README.md Install dependencies and run the ghostty example from the monorepo root. The example will be accessible via localhost. ```bash pnpm install pnpm --filter ghostty-example dev ``` -------------------------------- ### Install and Run Vite Example Source: https://github.com/vercel-labs/wterm/blob/main/examples/vite/README.md Commands to install dependencies, build the project, and run the Vite development server. ```bash pnpm install zig build pnpm --filter vite dev ``` -------------------------------- ### Start Development Server Source: https://github.com/vercel-labs/wterm/blob/main/examples/markdown-streaming/README.md Start the development server for the markdown-streaming example using pnpm. ```bash pnpm --filter markdown-streaming dev ``` -------------------------------- ### Install and Run Vue Example Source: https://github.com/vercel-labs/wterm/blob/main/examples/vue/README.md Commands to install dependencies, build the Zig component, and run the Vue development server from the monorepo root. ```bash pnpm install zig build pnpm --filter vue dev ``` -------------------------------- ### Run Next.js Example Source: https://github.com/vercel-labs/wterm/blob/main/README.md Sets up and runs the Next.js example. Copies the WASM binary and starts the development server using pnpm. ```bash cp web/wterm.wasm examples/nextjs/public/ pnpm --filter nextjs dev ``` -------------------------------- ### Install Dependencies and Build Source: https://github.com/vercel-labs/wterm/blob/main/examples/local/README.md Run these commands from the monorepo root to install necessary packages and build the project before starting the development server. ```bash pnpm install zig build pnpm --filter local dev ``` -------------------------------- ### Install Dependencies and Build Source: https://github.com/vercel-labs/wterm/blob/main/examples/ssh/README.md Install project dependencies and build the necessary components from the monorepo root. ```bash pnpm install zig build pnpm --filter ssh dev ``` -------------------------------- ### Install @wterm/core Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/core/page.mdx Install the core package using npm. ```bash npm install @wterm/core ``` -------------------------------- ### Install Dependencies and Build Source: https://github.com/vercel-labs/wterm/blob/main/examples/markdown-streaming/README.md Install project dependencies and build necessary components from the monorepo root. ```bash pnpm install zig build ``` -------------------------------- ### Virtual Filesystem Example Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/just-bash/page.mdx Example of how to populate the in-memory virtual filesystem using the `files` option in the BashShell constructor. ```APIDOC ## Virtual Filesystem ### Example ```ts const shell = new BashShell({ files: { "/home/user/README.md": "# My Project\n\nHello, world!\n", "/home/user/src/main.zig": 'const std = @import("std");\n', "/home/user/data/config.json": '{ "key": "value" }\n', }, }); ``` Directories are created implicitly from file paths. Commands like `ls`, `cat`, `cd`, and `pwd` operate on this virtual filesystem. ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/vercel-labs/wterm/blob/main/examples/markdown-streaming/README.md Copy the example environment file and add your API key to the local configuration. ```bash cp examples/markdown-streaming/.env.example examples/markdown-streaming/.env.local ``` -------------------------------- ### Install @wterm/markdown Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/markdown/page.mdx Install the package using npm. This is the first step to using the Markdown renderer. ```bash npm install @wterm/markdown ``` -------------------------------- ### Quick Start wterm with BashShell Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/just-bash/page.mdx Initialize and attach a BashShell instance to your wterm application. This example demonstrates setting up a virtual file and attaching the shell to the terminal's write function. ```tsx import { useCallback, useRef } from "react"; import { Terminal, useTerminal } from "@wterm/react"; import { BashShell } from "@wterm/just-bash"; import "@wterm/react/css"; function App() { const { ref, write } = useTerminal(); const shellRef = useRef(null); const handleReady = useCallback(() => { if (shellRef.current) return; const shell = new BashShell({ files: { "/home/user/hello.txt": "Hello, world!\n" }, greeting: "Welcome to wterm!", }); shellRef.current = shell; shell.attach(write); }, [write]); const handleData = useCallback((data: string) => { shellRef.current?.handleInput(data); }, []); return ( ); } ``` -------------------------------- ### Install Dependencies Source: https://github.com/vercel-labs/wterm/blob/main/README.md Installs project dependencies using pnpm. Ensure Node.js and pnpm are installed. ```bash pnpm install ``` -------------------------------- ### Install @wterm/just-bash Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/just-bash/page.mdx Install the necessary packages for integrating just-bash with wterm. Ensure just-bash is installed as a peer dependency. ```bash npm install @wterm/just-bash just-bash ``` -------------------------------- ### Install Wterm for React Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Install the necessary packages for React integration. Includes the core DOM package and the React-specific package. ```bash npm install @wterm/dom @wterm/react ``` -------------------------------- ### Install @wterm/ghostty Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/ghostty/page.mdx Install the Ghostty core package using npm. This command adds the necessary dependencies to your project. ```bash npm install @wterm/ghostty ``` -------------------------------- ### Install Wterm for Vanilla JS Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Install the core DOM package for use in plain JavaScript projects. No framework-specific packages are needed. ```bash npm install @wterm/dom ``` -------------------------------- ### Quick Start Vanilla JS Terminal Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Initialize and mount the WTerm instance in a plain JavaScript environment. The WASM binary is loaded automatically. ```js import { WTerm } from "@wterm/dom"; import "@wterm/dom/css"; const term = new WTerm(document.getElementById("terminal")); await term.init(); ``` -------------------------------- ### Install Wterm for Vue Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Install the required packages for Vue.js integration. This includes the DOM package and the Vue-specific package. ```bash npm install @wterm/dom @wterm/vue ``` -------------------------------- ### Basic WTerm Initialization Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/vanilla/page.mdx Initialize the WTerm terminal in a plain HTML/JS setup. Ensure the target div exists and import the necessary WTerm module and CSS. ```html
``` -------------------------------- ### Quick Start Vue Terminal Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Set up the Terminal component in your Vue.js application. Import the component and its associated CSS. ```vue ``` -------------------------------- ### Configure Scripts with Portless Source: https://github.com/vercel-labs/wterm/blob/main/AGENTS.md Wrap the 'dev' script with 'portless ' to automatically assign random ports and expose apps via .localhost URLs. Ensure portless is installed globally. ```json { "scripts": { "predev": "command -v portless >/dev/null 2>&1 || (echo '\nportless is required but not installed. Run: npm i -g portless\nSee: https://github.com/vercel-labs/portless\n' && exit 1)", "dev": "portless my-example.wterm next dev --turbopack" } } ``` -------------------------------- ### Vanilla JS Quick Start Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/markdown/page.mdx Integrate the Markdown renderer in a Vanilla JavaScript application. It fetches data, streams it to the renderer, and writes the ANSI output to a WTerm instance. ```javascript import { WTerm } from "@wterm/dom"; import { MarkdownRenderer } from "@wterm/markdown"; import "@wterm/dom/css"; const term = new WTerm(document.getElementById("terminal")); await term.init(); const md = new MarkdownRenderer(); const response = await fetch("/api/chat", { method: "POST" }); const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const rendered = md.push(decoder.decode(value)); if (rendered) term.write(rendered); } term.write(md.flush()); ``` -------------------------------- ### Build WASM Binary Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Compile the WASM binary using Zig. Ensure you have Zig 0.16.0 installed. The output will be in the web directory. ```bash zig build -Doptimize=ReleaseSmall ``` -------------------------------- ### React Quick Start Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/markdown/page.mdx Integrate the Markdown renderer in a React application using @wterm/react. It streams data from an API and renders it within a Terminal component. ```typescript import { useCallback, useRef } from "react"; import { Terminal, useTerminal } from "@wterm/react"; import { MarkdownRenderer } from "@wterm/markdown"; import "@wterm/react/css"; function App() { const { ref, write } = useTerminal(); const mdRef = useRef(new MarkdownRenderer()); const handleReady = useCallback(async () => { const response = await fetch("/api/chat", { method: "POST" }); const reader = response.body!.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const rendered = mdRef.current.push(decoder.decode(value)); if (rendered) write(rendered); } write(mdRef.current.flush()); }, [write]); return ; } ``` -------------------------------- ### Headless WasmBridge Example Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/core/page.mdx Demonstrates headless terminal usage by loading the bridge, initializing it, writing strings, and reading cell data and cursor state. ```typescript import { WasmBridge } from "@wterm/core"; const bridge = await WasmBridge.load(); bridge.init(80, 24); bridge.writeString("Hello, world!\r\n"); bridge.writeString("\x1b[1;31mRed bold text\x1b[0m"); for (let col = 0; col < 13; col++) { const cell = bridge.getCell(0, col); process.stdout.write(String.fromCodePoint(cell.char)); } // → "Hello, world!" const cursor = bridge.getCursor(); // → { row: 1, col: 13, visible: true } ``` -------------------------------- ### Quick Start React Terminal Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Integrate the Terminal component into your React application. Ensure you import the component and its CSS. ```tsx import { Terminal } from "@wterm/react"; import "@wterm/react/css"; function App() { return ; } ``` -------------------------------- ### WebSocketTransport Example Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/core/page.mdx Connects a terminal to a remote shell via WebSocket, handling data transfer and connection events. ```typescript import { WTerm, WebSocketTransport } from "@wterm/dom"; import "@wterm/dom/css"; const term = new WTerm(document.getElementById("terminal"), { cols: 80, rows: 24, }); await term.init(); const ws = new WebSocketTransport({ url: "ws://localhost:8080/pty", onData: (data) => term.write(data), onOpen: () => console.log("connected"), onClose: () => console.log("disconnected"), }); ws.connect(); term.onData = (data) => ws.send(data); ``` -------------------------------- ### Serve Vanilla Demo Source: https://github.com/vercel-labs/wterm/blob/main/README.md Serves the 'web/' directory using Python's http.server for the vanilla demo. Navigate to the 'web/' directory first. ```bash cd web && python3 -m http.server 8000 ``` -------------------------------- ### Initialize Terminal with Different Cores Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/core/README.md Demonstrates initializing `WTerm` with the default lightweight core or an opt-in core like `GhosttyCore` for full VT emulation. ```typescript import { WTerm } from "@wterm/dom"; import { GhosttyCore } from "@wterm/ghostty"; // Default — uses built-in lightweight core const term = new WTerm(el); // Opt-in — uses libghostty for full VT emulation const core = await GhosttyCore.load(); const term = new WTerm(el, { core }); ``` -------------------------------- ### Build All Packages Source: https://github.com/vercel-labs/wterm/blob/main/README.md Builds all packages within the wterm project using pnpm. ```bash pnpm build ``` -------------------------------- ### getScrollbackLineLen Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Gets the length of a specific line in the scrollback buffer. ```APIDOC ## getScrollbackLineLen ### Description Get the length of a scrollback line. ### Method getScrollbackLineLen(offset: number): number ### Parameters #### Path Parameters - **offset** (number) - Required - The line offset from the most recent scrollback line. ``` -------------------------------- ### Get Terminal Dimensions Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Retrieve the current number of columns and rows in the terminal grid. ```typescript getCols() / getRows() ``` -------------------------------- ### Apply Theme in Vanilla JS Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/themes/page.mdx Add the theme class to the terminal element and initialize wterm. ```js const term = new WTerm(document.getElementById("terminal")); term.element.classList.add("theme-monokai"); await term.init(); ``` -------------------------------- ### Get Cursor State Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Obtain the current position (row and column) and visibility status of the terminal cursor. ```typescript getCursor(): CursorState ``` -------------------------------- ### BashShell Constructor Options Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/just-bash/page.mdx Configuration options for initializing the BashShell, including virtual filesystem, environment variables, working directory, greeting, prompt, and network access. ```APIDOC ## BashShell Options ### files - **Type**: `Record` - **Default**: `{}` - **Description**: Virtual filesystem where keys are absolute paths and values are file contents. ### env - **Type**: `Record` - **Default**: `{ SHELL, TERM }` - **Description**: Environment variables for the shell. ### cwd - **Type**: `string` - **Default**: `"/home/user"` - **Description**: Initial working directory. ### greeting - **Type**: `string | string[]` - **Default**: `—` - **Description**: Lines printed when the shell attaches. ### prompt - **Type**: `(cwd: string) => string` - **Default**: colored `user@wterm:~$` - **Description**: Custom prompt function that receives the current working directory. ### network - **Type**: `NetworkConfig` - **Default**: `—` - **Description**: Network access configuration. See [Network Access](#network-access) for details. ``` -------------------------------- ### Get Scrollback Line Length Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Returns the number of cells (characters) in a specific scrollback line, identified by its offset. ```typescript getScrollbackLineLen(offset): number ``` -------------------------------- ### init Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Initializes the terminal grid with the specified dimensions. ```APIDOC ## init ### Description Initialize the terminal grid. ### Method init(cols: number, rows: number): void ### Parameters #### Path Parameters - **cols** (number) - Required - The number of columns for the terminal grid. - **rows** (number) - Required - The number of rows for the terminal grid. ``` -------------------------------- ### Get Scrollback Buffer Line Count Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Returns the total number of lines currently stored in the scrollback buffer. ```typescript getScrollbackCount(): number ``` -------------------------------- ### Initialize WTerm in HTML Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/dom/README.md Basic HTML structure and JavaScript to initialize WTerm. Import the necessary modules and create a new WTerm instance, attaching it to a DOM element. Ensure the element exists before initializing. ```html
``` -------------------------------- ### Get Pending Host Response Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Retrieve any pending response from the host, such as a Device Status Report (DSR). Reading this buffer clears it. ```typescript getResponse(): string | null ``` -------------------------------- ### Get Scrollback Cell Data Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Retrieve cell data from a specific line within the scrollback buffer, identified by its offset from the most recent line. ```typescript getScrollbackCell(offset, col): CellData ``` -------------------------------- ### WTerm Constructor Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/dom/README.md Initializes a new WTerm instance, which is the main terminal class. It takes an HTMLElement as the target for rendering and an optional options object to configure its behavior. ```APIDOC ## WTerm Constructor ### Description Initializes a new WTerm instance, which is the main terminal class. It takes an HTMLElement as the target for rendering and an optional options object to configure its behavior. ### Signature ```ts new WTerm(element: HTMLElement, options?: WTermOptions) ``` ### Parameters #### element - **element** (HTMLElement) - Required - The DOM element where the terminal will be rendered. #### options - **options** (WTermOptions) - Optional - Configuration options for the terminal. ### Options | Option | Type | Default | Description | |---|---|---|---| | `cols` | `number` | `80` | Initial column count | | `rows` | `number` | `24` | Initial row count | | `wasmUrl` | `string` | — | Optional URL to serve the WASM binary separately (embedded by default) | | `autoResize` | `boolean` | `true` | Auto-resize based on container dimensions | | `cursorBlink` | `boolean` | `false` | Enable cursor blinking animation | | `debug` | `boolean` | `false` | Enable debug mode. Exposes a `DebugAdapter` on the instance (`wt.debug`) for inspecting escape sequences, cell data, render performance, and unhandled CSI sequences. | | `onData` | `(data: string) => void` | — | Called when the terminal produces data (user input or host response). When omitted, input is echoed back automatically. | | `onTitle` | `(title: string) => void` | — | Called when the terminal title changes | | `onResize` | `(cols: number, rows: number) => void` | — | Called on resize ``` -------------------------------- ### Get Cell Data Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Retrieve the data for a specific cell at the given row and column. This includes character, foreground/background colors, and style flags. ```typescript getCell(row, col): CellData ``` -------------------------------- ### WTerm Methods Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/dom/README.md Provides essential methods for interacting with the WTerm instance, including initialization, writing data, resizing, focusing, and cleanup. ```APIDOC ## WTerm Methods ### Description Provides essential methods for interacting with the WTerm instance, including initialization, writing data, resizing, focusing, and cleanup. ### Methods | Method | Description | |---|---| | `init(): Promise` | Load WASM and start rendering | | `write(data: string | Uint8Array)` | Write data to the terminal | | `resize(cols, rows)` | Resize the terminal grid | | `focus()` | Focus the terminal element | | `destroy()` | Clean up event listeners and DOM | ### `init()` #### Description Loads the WebAssembly binary and initializes the terminal rendering process. #### Returns - `Promise` - A promise that resolves with the WTerm instance once initialization is complete. ### `write(data: string | Uint8Array)` #### Description Writes data to the terminal. This can be user input or data received from a backend. #### Parameters - **data** (string | Uint8Array) - The data to write to the terminal. ### `resize(cols: number, rows: number)` #### Description Resizes the terminal grid to the specified number of columns and rows. #### Parameters - **cols** (number) - The new number of columns. - **rows** (number) - The new number of rows. ### `focus()` #### Description Sets the focus to the terminal element, making it ready to receive keyboard input. ### `destroy()` #### Description Cleans up any event listeners and DOM elements associated with the terminal instance, effectively removing it from the page. ``` -------------------------------- ### Basic HTML Structure for wterm with Vite Source: https://github.com/vercel-labs/wterm/blob/main/examples/vite/index.html This is the main HTML file for the Vite project. It includes essential meta tags and links the main JavaScript entry point. ```html wterm — Vite Example
``` -------------------------------- ### Get Pending Title Change Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Retrieve the most recent title change request sent via OSC escape sequences. Returns `null` if no title change is pending. ```typescript getTitle(): string | null ``` -------------------------------- ### WasmBridge Loading Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Demonstrates how to load the WasmBridge, either with default settings or by specifying a custom URL for the WASM binary. ```APIDOC ## WasmBridge Loading ### Description Loads the WasmBridge, which provides a low-level interface to the Zig/WASM terminal state machine. ### Usage ```ts import { WasmBridge } from "@wterm/core"; // Load with default settings const bridge = await WasmBridge.load(); // Load with a custom URL for the WASM binary const bridge = await WasmBridge.load("/wterm.wasm"); ``` When no URL is provided, the WASM binary is decoded from a base64 string inlined in the package. Pass a URL when you want to serve the binary separately for caching or CDN use. ``` -------------------------------- ### Build WASM Binary Source: https://github.com/vercel-labs/wterm/blob/main/README.md Builds the WebAssembly binary for the wterm core. Use '-Doptimize=ReleaseSmall' for a release build. ```bash zig build ``` ```bash zig build -Doptimize=ReleaseSmall ``` -------------------------------- ### WebSocket Client Options Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Configuration options for initializing the WebSocket client, including URL, reconnection behavior, and event handlers. ```APIDOC ## WebSocket Client Options ### Description Configuration options for the WebSocket client. ### Options Table | Option | Type | Default | Description | |---|---|---|---| | `url` | `string` | — | WebSocket server URL | | `reconnect` | `boolean` | `true` | Automatically reconnect on disconnect with exponential backoff | | `maxReconnectDelay` | `number` | `30000` | Maximum delay between reconnection attempts (ms) | | `onData` | `(data: Uint8Array | string) => void` | — | Called when data is received from the server | | `onOpen` | `() => void` | — | Called when the connection opens | | `onClose` | `() => void` | — | Called when the connection closes | | `onError` | `(event: Event) => void` | — | Called when a WebSocket error occurs | ``` -------------------------------- ### Load and Use GhosttyCore in Vanilla JS Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/ghostty/page.mdx Load the GhosttyCore asynchronously and initialize WTerm with it. Ensure the DOM element for the terminal is available. ```typescript import { WTerm } from "@wterm/dom"; import { GhosttyCore } from "@wterm/ghostty"; import "@wterm/dom/css"; const core = await GhosttyCore.load(); const term = new WTerm(document.getElementById("terminal"), { core }); await term.init(); ``` -------------------------------- ### BashShell Constructor Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/just-bash/README.md Initializes a new BashShell instance. You can configure the virtual filesystem, environment variables, initial directory, greeting message, prompt appearance, and network access. ```APIDOC ## `BashShell` Constructor ### Description Initializes a new `BashShell` instance with optional configuration. ### Signature ```ts new BashShell(options?: ShellOptions) ``` ### Options | Option | Type | Default | Description | |------------|--------------------------|----------------|--------------------------| | `files` | `Record` | `{}` | Virtual filesystem | | `env` | `Record` | `{ SHELL, TERM }` | Environment variables | | `cwd` | `string` | `"/home/user"` | Initial working directory | | `greeting` | `string | string[]` | — | Greeting printed on attach | | `prompt` | `(cwd: string) => string`| colored `user@wterm:~$` | Custom prompt function | | `network` | `NetworkConfig` | — | Network access config | ``` -------------------------------- ### WTerm Methods Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Instance methods available on the vanilla WTerm class for controlling terminal behavior. ```APIDOC ## WTerm Methods ### init - **Description**: Load WASM and start rendering. - **Returns**: `Promise` ### write - **Description**: Write data to the terminal. - **Parameters**: `data: string | Uint8Array` ### resize - **Description**: Resize the terminal grid. - **Parameters**: `cols: number, rows: number` ### focus - **Description**: Focus the terminal input. ### destroy - **Description**: Clean up event listeners, observers, and DOM. ``` -------------------------------- ### Network Access Configuration Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/just-bash/page.mdx How to enable network access for commands like `curl` or `fetch` by configuring the `network` option. ```APIDOC ## Network Access ### Enabling Network Access By default, the shell runs offline. To enable network access, pass the `network` option: ```ts const shell = new BashShell({ network: { dangerouslyAllowFullInternetAccess: true, }, }); ``` The `NetworkConfig` type is re-exported from `just-bash`. Refer to the [just-bash documentation](https://github.com/vercel-labs/just-bash) for all available network options. ``` -------------------------------- ### Display Welcome Message in WTerm Source: https://github.com/vercel-labs/wterm/blob/main/web/index.html Writes a formatted welcome message to the WTerm instance, demonstrating various ANSI escape codes for styling like bold, italic, underline, strikethrough, and colors. ```javascript const welcome = [ '\x1b[1;36m┌──────────────────────────────────────┐\x1b[0m', '\x1b[1;36m│\x1b[0m \x1b[1;33mwterm\x1b[0m — a terminal for the web \x1b[1;36m│\x1b[0m', '\x1b[1;36m│\x1b[0m powered by Zig + WebAssembly \x1b[1;36m│\x1b[0m', '\x1b[1;36m└──────────────────────────────────────┘\x1b[0m', '', 'Type anything — this is local echo mode.', 'Try: \x1b[1mbold\x1b[0m, \x1b[3mitalic\x1b[0m, \x1b[4munderline\x1b[0m, \x1b[9mstrikethrough\x1b[0m', 'Colors: \x1b[31mr\x1b[32mg\x1b[33my\x1b[34mb\x1b[35mm\x1b[36mc\x1b[0m | 256: \x1b[38;5;208m208\x1b[0m \x1b[38;5;135m135\x1b[0m \x1b[38;5;82m82\x1b[0m', '', '\x1b[32m$\x1b[0m ', ].join('\r\n'); term.write(welcome); ``` -------------------------------- ### Serve WASM Separately Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/get-started/page.mdx Copy the WASM binary to your public directory and configure the Terminal component to load it from a specific URL. This is useful for caching. ```bash cp node_modules/@wterm/core/wasm/wterm.wasm public/wterm.wasm ``` ```tsx ``` -------------------------------- ### Initialize WTerm Terminal Source: https://github.com/vercel-labs/wterm/blob/main/web/index.html Initializes a new WTerm instance with specified options and attaches it to a DOM element. Handles terminal data input, title updates, and theme selection. ```javascript import { WTerm } from './js/terminal.js'; const termEl = document.getElementById('terminal'); const themeSelect = document.getElementById('theme-select'); const titleDisplay = document.getElementById('title-display'); const term = new WTerm(termEl, { cols: 80, rows: 24, autoResize: false, onData(data) { let out = ''; for (const ch of data) { if (ch === '\r') { out += '\r\n'; } else if (ch === '\x7f' || ch === '\x08') { out += '\x08 \x08'; } else { out += ch; } } term.write(out); }, onTitle(title) { titleDisplay.textContent = title; document.title = title ? `${title} — wterm` : 'wterm'; }, }); await term.init(); themeSelect.addEventListener('change', () => { termEl.className = ''; termEl.classList.add('wterm'); if (themeSelect.value) termEl.classList.add(themeSelect.value); // Re-add the term-grid container class termEl.querySelector('.term-grid')?.classList.add('term-grid'); }); ``` -------------------------------- ### Initialize and Use MarkdownRenderer Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/markdown/README.md Initialize the MarkdownRenderer with a specified width and feed chunks of markdown text as they arrive. Flush any remaining content when the stream ends. ```typescript import { MarkdownRenderer } from "@wterm/markdown"; const renderer = new MarkdownRenderer({ width: 80 }); // Feed chunks as they arrive (e.g. from an LLM stream) const ansi = renderer.push("# Hello\n\nThis is **bold** and `code`.\n"); terminal.write(ansi); // Flush remaining content when the stream ends terminal.write(renderer.flush()); ``` -------------------------------- ### Configure BashShell with Virtual Filesystem Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/just-bash/page.mdx Populate the in-memory filesystem for the BashShell with initial files and their contents. Directories are created implicitly. ```typescript const shell = new BashShell({ files: { "/home/user/README.md": "# My Project\n\nHello, world!\n", "/home/user/src/main.zig": 'const std = @import("std");\n', "/home/user/data/config.json": '{ "key": "value" }\n', }, }); ``` -------------------------------- ### Import WTerm CSS Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/vanilla/page.mdx Import the default WTerm stylesheet to apply basic terminal styling. This should be done before applying any custom themes. ```js import "@wterm/dom/css"; ``` -------------------------------- ### Import Terminal Stylesheet Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/vue/README.md Import the default stylesheet to enable the default theme and all built-in themes. ```vue ``` -------------------------------- ### Terminal Options Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx These options are available for the React and Vue `` components, as well as the vanilla `WTerm` constructor. ```APIDOC ## Terminal Options The React and Vue `` components and the vanilla `WTerm` constructor all accept these options: ### `cols` - **Type**: `number` - **Default**: `80` - **Description**: Initial column count ### `rows` - **Type**: `number` - **Default**: `24` - **Description**: Initial row count ### `core` - **Type**: `TerminalCore` - **Default**: `—` - **Description**: A pre-constructed terminal core instance. When provided, `wasmUrl` is ignored and this core is used instead of loading the built-in Zig WASM binary. See [Ghostty Core](/ghostty) for an example. ### `wasmUrl` - **Type**: `string` - **Default**: `—` - **Description**: URL to serve the WASM binary separately. When omitted, the ~12 KB binary is decoded from an inlined base64 string. Ignored when `core` is provided. ### `autoResize` - **Type**: `boolean` - **Default**: `true` (vanilla) / `false` (React, Vue) - **Description**: Automatically resize the terminal to fit its container using a `ResizeObserver` ### `cursorBlink` - **Type**: `boolean` - **Default**: `false` - **Description**: Enable cursor blinking animation ### `debug` - **Type**: `boolean` - **Default**: `false` - **Description**: Enable debug mode. Exposes a `DebugAdapter` on the `WTerm` instance (`wt.debug`) for inspecting escape sequences, cell data, render performance, and unhandled CSI sequences. ### `onData` - **Type**: `(data: string) => void` - **Default**: `—` - **Description**: Called when the terminal produces data (user input or host response). When omitted, input is echoed back automatically. ### `onTitle` - **Type**: `(title: string) => void` - **Default**: `—` - **Description**: Called when the terminal title changes via an escape sequence ### `onResize` - **Type**: `(cols: number, rows: number) => void` - **Default**: `—` - **Description**: Called after the terminal is resized ``` -------------------------------- ### MarkdownRenderer Constructor Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/markdown/README.md Initializes a new instance of MarkdownRenderer. You can optionally specify the terminal width. ```APIDOC ## new MarkdownRenderer(options?: { width?: number }) ### Description Initializes a new instance of the MarkdownRenderer. The `width` option can be used to set the terminal's column width for proper formatting. ### Parameters #### Options - **width** (number) - Optional - The width of the terminal in columns. ``` -------------------------------- ### Accessing Terminal Instance via Template Ref Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/vue/page.mdx Use a template ref to imperatively access terminal methods like 'write', 'resize', and 'focus'. The 'ready' event provides the underlying WTerm instance. ```vue ``` -------------------------------- ### WasmBridge.load Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Loads the WASM binary and returns a new WasmBridge instance. This is the entry point for initializing the bridge. ```APIDOC ## WasmBridge.load(url?) ### Description Load the WASM binary and return a new bridge instance. ### Method WasmBridge.load(url?: string): Promise<WasmBridge> ### Parameters #### Query Parameters - **url** (string) - Optional - The URL to load the WASM binary from. ``` -------------------------------- ### WasmBridge Load Method Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Use this method to asynchronously load the WASM binary and obtain a new WasmBridge instance. This is the entry point for initializing the bridge. ```typescript WasmBridge.load(url?): Promise ``` -------------------------------- ### Custom Input Handling with onData Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/vanilla/page.mdx Implement custom input handling by providing an `onData` callback to the WTerm constructor. This allows you to process user input before it's echoed or sent elsewhere. ```js const term = new WTerm(document.getElementById("terminal"), { onData(data) { socket.send(data); }, }); await term.init(); ``` -------------------------------- ### Run Zig Tests Source: https://github.com/vercel-labs/wterm/blob/main/README.md Executes the tests defined within the Zig build system. ```bash zig build test ``` -------------------------------- ### Vue: Use Template Ref for Imperative Handle Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/configuration/page.mdx Access imperative methods on the Vue `Terminal` component using a template ref. The `@ready` event provides the `WTerm` instance. ```vue ``` -------------------------------- ### Define Custom Theme CSS Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/themes/page.mdx Create a CSS class to override wterm's custom properties for a custom theme. Apply it like a built-in theme. ```css .wterm.theme-tokyo-night { --term-bg: #1a1b26; --term-fg: #c0caf5; --term-cursor: #f7768e; --term-color-0: #15161e; --term-color-1: #f7768e; --term-color-2: #9ece6a; --term-color-3: #e0af68; --term-color-4: #7aa2f7; --term-color-5: #bb9af7; --term-color-6: #7dcfff; --term-color-7: #a9b1d6; --term-color-8: #414868; --term-color-9: #f7768e; --term-color-10: #9ece6a; --term-color-11: #e0af68; --term-color-12: #7aa2f7; --term-color-13: #bb9af7; --term-color-14: #7dcfff; --term-color-15: #c0caf5; } ``` -------------------------------- ### WebSocket Transport Initialization Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/vanilla/page.mdx Connect the WTerm terminal to a backend PTY using WebSocket. This involves initializing both WTerm and WebSocketTransport, and setting up data flow between them. ```js import { WTerm, WebSocketTransport } from "@wterm/dom"; const term = new WTerm(el, { cols: 80, rows: 24 }); await term.init(); const ws = new WebSocketTransport({ url: "ws://localhost:8080/pty", onData: (data) => term.write(data), }); ws.connect(); term.onData = (data) => ws.send(data); ``` -------------------------------- ### Apply Built-in Themes Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/themes/page.mdx Select from predefined themes like 'solarized-dark', 'monokai', or 'light' using the `theme` prop. ```tsx ``` ```tsx ``` ```tsx ``` -------------------------------- ### WasmBridge API Usage Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/core/README.md Shows how to load and interact with the `WasmBridge` for low-level terminal state management, including initialization, writing strings, and retrieving cell/cursor data. ```typescript import { WasmBridge } from "@wterm/core"; const bridge = await WasmBridge.load(); bridge.init(80, 24); bridge.writeString("Hello, world!\r\n"); const cell = bridge.getCell(0, 0); // { char, fg, bg, flags } const cursor = bridge.getCursor(); // { row, col, visible } ``` -------------------------------- ### Import Terminal Stylesheet Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/react/README.md Import the CSS file to enable default themes and styling for the Terminal component. ```tsx import "@wterm/react/css"; ``` -------------------------------- ### CSS Styling for wterm Terminal Source: https://github.com/vercel-labs/wterm/blob/main/examples/vite/index.html Basic CSS to ensure the terminal fills the screen and has a dark background. ```css * { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100%; background: #1a1a2e; } #terminal { height: 100%; } ``` -------------------------------- ### BashShell Methods Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/just-bash/README.md Provides methods to interact with the BashShell instance, such as connecting to the terminal's write function and handling user input. ```APIDOC ## `BashShell` Methods ### `attach(write): Promise` #### Description Connects the `BashShell` instance to the terminal's `write` function, enabling output to be displayed in the terminal. #### Parameters - **write** (function) - The terminal's write function to send output to. ### `handleInput(data): Promise` #### Description Processes input data received from the terminal, such as user keystrokes, and executes commands accordingly. #### Parameters - **data** (string) - The input string from the terminal. ``` -------------------------------- ### Apply Built-in Theme Class Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/vanilla/page.mdx Apply a pre-defined theme to the terminal element by adding a theme class. Themes like `theme-monokai` are available. ```js element.classList.add("theme-monokai"); ``` -------------------------------- ### MarkdownRenderer.push Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/markdown/README.md Feeds a chunk of Markdown text to the renderer and returns the rendered ANSI output. ```APIDOC ## push(delta: string): string ### Description Processes a chunk of Markdown text and returns the corresponding ANSI escape sequences. This method is designed to be called incrementally as text arrives, such as from a streaming LLM. ### Parameters #### Path Parameters - **delta** (string) - Required - A chunk of Markdown text to process. ``` -------------------------------- ### Load WasmBridge Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Load the WasmBridge instance. You can either load the WASM binary from an inlined base64 string or provide a URL to serve the binary separately. ```typescript import { WasmBridge } from "@wterm/core"; const bridge = await WasmBridge.load(); ``` ```typescript import { WasmBridge } from "@wterm/core"; const bridge = await WasmBridge.load("/wterm.wasm"); ``` -------------------------------- ### Apply Custom Theme Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/themes/page.mdx Apply a custom theme by using its name with the `theme` prop. ```tsx ``` -------------------------------- ### getResponse Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/api-reference/page.mdx Retrieves any pending host response (e.g., DSR), or null if none is available. Reading this clears the buffer. ```APIDOC ## getResponse ### Description Get pending host response (e.g. DSR), or null. Reading clears the buffer. ### Method getResponse(): string | null ### Response #### Success Response (200) - **string | null** - The pending host response string, or null if none. ``` -------------------------------- ### Rebuild WASM Binary for Ghostty Core Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/ghostty/page.mdx Rebuild the WASM binary for the Ghostty core package. This command is intended for maintainers and requires Zig 0.15.x. ```bash pnpm --filter @wterm/ghostty rebuild-wasm ``` -------------------------------- ### MarkdownRenderer Options Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/markdown/page.mdx Configuration options for the MarkdownRenderer. ```APIDOC ## Options ### width - **Type**: `number` - **Default**: `80` - **Description**: Terminal width in columns (used for horizontal rules) ``` -------------------------------- ### MarkdownRenderer push Method Source: https://github.com/vercel-labs/wterm/blob/main/packages/@wterm/markdown/README.md Feed a chunk of Markdown text to the renderer. This method returns the rendered ANSI output. ```typescript `push(delta: string): string` ``` -------------------------------- ### Next.js Transpile Configuration Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/react/page.mdx For Next.js projects, configure `transpilePackages` in your `next.config.mjs` to ensure that the @wterm packages are correctly processed. ```js // next.config.mjs const nextConfig = { transpilePackages: ["@wterm/dom", "@wterm/react"], }; ``` -------------------------------- ### React: Use Imperative Handle with useTerminal Source: https://github.com/vercel-labs/wterm/blob/main/apps/docs/src/app/configuration/page.mdx Access imperative methods like `resize` via the ref returned by `useTerminal` in React. The `onReady` callback receives the `WTerm` instance. ```tsx import { Terminal, useTerminal } from "@wterm/react"; function App() { const { ref } = useTerminal(); return ( { wt.resize(120, 40); }} /> ); } ```