CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tauri-apps--api

TypeScript/JavaScript API bindings for Tauri applications providing comprehensive desktop app functionality

Pending
Overview
Eval results
Files

core-ipc.mddocs/

Core IPC & Plugins

The core module provides the foundation for all communication between the frontend and Rust backend in Tauri applications. It handles command invocation, plugin management, resource lifecycle, and IPC serialization.

Capabilities

Command Invocation

Execute Rust commands from the frontend with typed parameters and return values.

/**
 * Invoke a Rust command from the frontend
 * @param cmd - Command name registered in Rust
 * @param args - Arguments to pass to the command
 * @param options - Optional headers for the request
 * @returns Promise resolving to command result
 */
function invoke<T>(cmd: string, args?: InvokeArgs, options?: InvokeOptions): Promise<T>;

type InvokeArgs = Record<string, unknown> | number[] | ArrayBuffer | Uint8Array;

interface InvokeOptions {
  headers: HeadersInit;
}

Usage Examples:

import { invoke } from '@tauri-apps/api/core';

// Simple command with no parameters
const version = await invoke<string>('get_app_version');

// Command with object parameters
const result = await invoke<UserData>('create_user', {
  name: 'John Doe',
  email: 'john@example.com'
});

// Command with binary data
const imageData = new Uint8Array([/* image bytes */]);
const processed = await invoke<Uint8Array>('process_image', imageData);

// Command with custom headers
const data = await invoke<string>('authenticated_request', 
  { query: 'SELECT * FROM users' },
  { headers: { 'Authorization': 'Bearer token123' } }
);

Environment Detection

Check if the code is running in a Tauri environment.

/**
 * Check if the current environment is a Tauri application
 * @returns true if running in Tauri, false otherwise
 */
function isTauri(): boolean;

Usage Example:

import { isTauri } from '@tauri-apps/api/core';

if (isTauri()) {
  // Use Tauri-specific APIs
  const window = await getCurrentWindow();
} else {
  // Fallback for web environment
  console.log('Running in browser');
}

File URL Conversion

Convert local file paths to URLs that can be used in the frontend.

/**
 * Convert a file path to an asset URL that can be loaded by the frontend
 * @param filePath - Local file path
 * @param protocol - Optional protocol to use (defaults to 'asset')
 * @returns URL string that can be used in img src, etc.
 */
function convertFileSrc(filePath: string, protocol?: string): string;

Usage Example:

import { convertFileSrc } from '@tauri-apps/api/core';

// Convert local file to usable URL
const imagePath = '/path/to/local/image.png';
const imageUrl = convertFileSrc(imagePath);

// Use in HTML
const img = document.createElement('img');
img.src = imageUrl; // Will be something like 'asset://localhost/path/to/local/image.png'

// With custom protocol
const customUrl = convertFileSrc(imagePath, 'myprotocol');

IPC Channels

Bidirectional communication channels for streaming data between frontend and backend.

/**
 * Bidirectional IPC communication channel with message ordering
 */
class Channel<T> {
  /**
   * Create a new IPC channel
   * @param onmessage - Optional callback for incoming messages
   */
  constructor(onmessage?: (response: T) => void);
  
  /**
   * Channel identifier returned from transformCallback
   */
  readonly id: number;
  
  /**
   * Message handler that can be updated
   */
  onmessage: (response: T) => void;
}

Usage Example:

import { Channel } from '@tauri-apps/api/core';

// Create a channel for real-time data
const dataChannel = new Channel<{ type: string; data: any }>((message) => {
  console.log('Received:', message);
});

// The channel is used by passing its ID to Rust backend commands
// The backend can send messages to this channel using the ID
console.log('Channel ID:', dataChannel.id);

// Update the message handler
dataChannel.onmessage = (message) => {
  console.log('Updated handler received:', message);
};

Plugin System

Manage Tauri plugins and their permissions.

/**
 * Add a listener for plugin events
 * @param plugin - Plugin identifier
 * @param event - Event name to listen for
 * @param cb - Callback function for handling events
 * @returns Promise resolving to listener handle
 */
function addPluginListener<T>(
  plugin: string, 
  event: string, 
  cb: (payload: T) => void
): Promise<PluginListener>;

/**
 * Check current permissions for a plugin
 * @param plugin - Plugin identifier
 * @returns Promise resolving to current permission state
 */
function checkPermissions<T>(plugin: string): Promise<T>;

/**
 * Request permissions for a plugin
 * @param plugin - Plugin identifier  
 * @returns Promise resolving to granted permission state
 */
function requestPermissions<T>(plugin: string): Promise<T>;

/**
 * Plugin event listener handle
 */
class PluginListener {
  /**
   * Remove the event listener
   */
  unregister(): Promise<void>;
}

type PermissionState = 'granted' | 'denied' | 'prompt' | 'prompt-with-rationale';

Usage Examples:

import { addPluginListener, checkPermissions, requestPermissions } from '@tauri-apps/api/core';

// Listen for plugin events
const listener = await addPluginListener('notifications', 'received', (payload) => {
  console.log('Notification received:', payload);
});

// Check permissions
const currentPerms = await checkPermissions('camera');
if (currentPerms.camera !== 'granted') {
  // Request permissions
  const newPerms = await requestPermissions('camera');
  console.log('Camera permission:', newPerms.camera);
}

// Clean up listener
await listener.unregister();

Resource Management

Base class for managing Rust-backed resources with automatic cleanup.

/**
 * Base class for Rust-backed resources that need cleanup
 */
class Resource {
  /**
   * Create a resource with the given Rust resource ID
   * @param rid - Resource identifier from Rust
   */
  constructor(rid: number);
  
  /**
   * Close the resource and free associated memory
   */
  close(): Promise<void>;
}

Usage Example:

import { Resource } from '@tauri-apps/api/core';

class MyCustomResource extends Resource {
  async doSomething() {
    // Resource operations here
  }
  
  async cleanup() {
    await this.close(); // Clean up Rust resource
  }
}

Custom IPC Serialization

Define custom serialization for complex objects passed through IPC.

/**
 * Symbol key for implementing custom IPC serialization
 */
const SERIALIZE_TO_IPC_FN: string;

Usage Example:

import { SERIALIZE_TO_IPC_FN } from '@tauri-apps/api/core';

// Custom class with IPC serialization
class UserId {
  constructor(private id: string) {}
  
  // Custom serialization for IPC
  [SERIALIZE_TO_IPC_FN]() {
    return { String: this.id };
  }
}

// Usage with invoke
const userId = new UserId('user123');
const result = await invoke('process_user', { userId });

Callback Management

Low-level callback transformation for IPC communication.

/**
 * Transform a callback function for IPC communication
 * @param callback - Callback function to transform
 * @param once - Whether callback should only be called once
 * @returns Callback ID for IPC
 */
function transformCallback<T>(
  callback?: (response: T) => void, 
  once?: boolean
): number;

Note: This is typically used internally by other Tauri APIs and rarely needed in application code.

Error Handling

IPC operations can fail for various reasons:

import { invoke } from '@tauri-apps/api/core';

try {
  const result = await invoke('my_command', { data: 'test' });
  console.log('Success:', result);
} catch (error) {
  // Common error types:
  // - Command not found
  // - Invalid arguments
  // - Backend error
  // - Permission denied
  console.error('IPC error:', error);
}

Performance Considerations

  • Use Channel for streaming/real-time data instead of repeated invoke calls
  • Batch multiple operations when possible to reduce IPC overhead
  • Consider using binary data types (Uint8Array, ArrayBuffer) for large payloads
  • Implement proper resource cleanup with Resource.close() to prevent memory leaks

Install with Tessl CLI

npx tessl i tessl/npm-tauri-apps--api

docs

app-lifecycle.md

core-ipc.md

events.md

index.md

menu-system.md

system-integration.md

testing.md

utilities.md

window-management.md

tile.json