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

utilities.mddocs/

Utilities

Cross-platform utilities for path handling, image processing, device pixel calculations, and platform abstraction to ensure consistent behavior across different operating systems.

Capabilities

Path Utilities

Cross-platform path manipulation and directory resolution with support for all major operating systems.

/**
 * Get platform-specific path separator
 * @returns Path separator ('/' on Unix, '\' on Windows)
 */
function sep(): Promise<string>;

/**
 * Get platform-specific PATH environment variable delimiter
 * @returns Delimiter (';' on Windows, ':' on Unix)
 */
function delimiter(): Promise<string>;

/**
 * Resolve an absolute path from path segments
 * @param paths - Path segments to resolve
 * @returns Absolute path
 */
function resolve(...paths: string[]): Promise<string>;

/**
 * Normalize a path by resolving '..' and '.' segments
 * @param path - Path to normalize
 * @returns Normalized path
 */
function normalize(path: string): Promise<string>;

/**
 * Join path segments using platform-specific separator
 * @param paths - Path segments to join
 * @returns Joined path
 */
function join(...paths: string[]): Promise<string>;

/**
 * Get directory name of a path
 * @param path - File path
 * @returns Directory containing the file
 */
function dirname(path: string): Promise<string>;

/**
 * Get file extension from a path
 * @param path - File path
 * @returns Extension including the dot (e.g., '.txt')
 */
function extname(path: string): Promise<string>;

/**
 * Get base filename from a path
 * @param path - File path
 * @param ext - Optional extension to remove from result
 * @returns Base filename
 */
function basename(path: string, ext?: string): Promise<string>;

/**
 * Check if a path is absolute
 * @param path - Path to check
 * @returns true if path is absolute
 */
function isAbsolute(path: string): Promise<boolean>;

/**
 * Resolve bundled resource path to absolute path
 * @param resourcePath - Relative path to resource in bundle
 * @returns Absolute path to resource
 */
function resolveResource(resourcePath: string): Promise<string>;

Directory Resolution

Get standard system and application-specific directories across platforms.

/**
 * User's home directory
 * @returns Path to user's home directory
 */
function homeDir(): Promise<string>;

/**
 * User's audio/music directory
 * @returns Path to audio directory
 */
function audioDir(): Promise<string>;

/**
 * User's cache directory
 * @returns Path to cache directory
 */
function cacheDir(): Promise<string>;

/**
 * User's configuration directory
 * @returns Path to config directory
 */
function configDir(): Promise<string>;

/**
 * User's data directory
 * @returns Path to data directory
 */
function dataDir(): Promise<string>;

/**
 * User's local data directory
 * @returns Path to local data directory
 */
function localDataDir(): Promise<string>;

/**
 * User's desktop directory
 * @returns Path to desktop directory
 */
function desktopDir(): Promise<string>;

/**
 * User's documents directory
 * @returns Path to documents directory
 */
function documentDir(): Promise<string>;

/**
 * User's downloads directory
 * @returns Path to downloads directory
 */
function downloadDir(): Promise<string>;

/**
 * Current executable's directory
 * @returns Path to directory containing executable
 */
function executableDir(): Promise<string>;

/**
 * System fonts directory
 * @returns Path to fonts directory
 */
function fontDir(): Promise<string>;

/**
 * User's pictures directory
 * @returns Path to pictures directory
 */
function pictureDir(): Promise<string>;

/**
 * User's public directory
 * @returns Path to public directory
 */
function publicDir(): Promise<string>;

/**
 * Application resources directory
 * @returns Path to bundled resources
 */
function resourceDir(): Promise<string>;

/**
 * Runtime directory for temporary files
 * @returns Path to runtime directory
 */
function runtimeDir(): Promise<string>;

/**
 * User's templates directory
 * @returns Path to templates directory
 */
function templateDir(): Promise<string>;

/**
 * User's videos directory
 * @returns Path to videos directory
 */
function videoDir(): Promise<string>;

/**
 * System temporary directory
 * @returns Path to temp directory
 */
function tempDir(): Promise<string>;

Application-Specific Directories

Directories specific to the current application for storing config, data, cache, and logs.

/**
 * Application-specific configuration directory
 * @returns Path to app config directory
 */
function appConfigDir(): Promise<string>;

/**
 * Application-specific data directory
 * @returns Path to app data directory
 */
function appDataDir(): Promise<string>;

/**
 * Application-specific local data directory
 * @returns Path to app local data directory
 */
function appLocalDataDir(): Promise<string>;

/**
 * Application-specific cache directory
 * @returns Path to app cache directory
 */
function appCacheDir(): Promise<string>;

/**
 * Application-specific log directory
 * @returns Path to app log directory
 */
function appLogDir(): Promise<string>;

Base Directory Enum

Enumeration of all available directory types for use with other APIs.

enum BaseDirectory {
  Audio = 'audio',
  Cache = 'cache',
  Config = 'config',
  Data = 'data',
  LocalData = 'localData',
  Desktop = 'desktop',
  Document = 'document',
  Download = 'download',
  Executable = 'executable',
  Font = 'font',
  Home = 'home',
  Picture = 'picture',
  Public = 'public',
  Resource = 'resource',
  Runtime = 'runtime',
  Template = 'template',
  Video = 'video',
  AppConfig = 'appConfig',
  AppData = 'appData',
  AppLocalData = 'appLocalData',
  AppCache = 'appCache',
  AppLog = 'appLog',
  Temp = 'temp'
}

Image Processing

Image loading, processing, and format conversion utilities.

/**
 * Image representation with RGBA data
 */
class Image {
  /**
   * Create image from RGBA data
   * @param rgba - RGBA pixel data (4 bytes per pixel)
   * @param width - Image width in pixels
   * @param height - Image height in pixels
   * @returns Promise resolving to Image instance
   */
  static new(rgba: number[], width: number, height: number): Promise<Image>;
  
  /**
   * Create image from byte array (PNG, JPEG, etc.)
   * @param bytes - Image file bytes
   * @returns Promise resolving to Image instance
   */
  static fromBytes(bytes: number[] | Uint8Array | ArrayBuffer): Promise<Image>;
  
  /**
   * Load image from file path
   * @param path - Path to image file
   * @returns Promise resolving to Image instance
   */
  static fromPath(path: string): Promise<Image>;
  
  /**
   * Get RGBA pixel data
   * @returns RGBA data as Uint8Array
   */
  rgba(): Promise<Uint8Array>;
  
  /**
   * Get image dimensions
   * @returns Width and height in pixels
   */
  size(): Promise<ImageSize>;
}

interface ImageSize {
  width: number;
  height: number;
}

/**
 * Transform image data for different contexts
 * @param image - Image in various formats
 * @returns Transformed image data
 */
function transformImage<T>(image: string | Image | Uint8Array | ArrayBuffer | number[] | null): T;

Device Pixel Interface (DPI)

Handle device pixel scaling and convert between logical and physical coordinates.

/**
 * Size in logical (device-independent) pixels
 */
class LogicalSize {
  /**
   * Create logical size
   * @param width - Width in logical pixels
   * @param height - Height in logical pixels
   */
  constructor(width: number, height: number);
  
  /**
   * Convert to physical pixels
   * @param scaleFactor - Device scale factor
   * @returns Equivalent size in physical pixels
   */
  toPhysical(scaleFactor: number): PhysicalSize;
}

/**
 * Size in physical (actual screen) pixels
 */
class PhysicalSize {
  /**
   * Create physical size
   * @param width - Width in physical pixels
   * @param height - Height in physical pixels
   */
  constructor(width: number, height: number);
  
  /**
   * Convert to logical pixels
   * @param scaleFactor - Device scale factor
   * @returns Equivalent size in logical pixels
   */
  toLogical(scaleFactor: number): LogicalSize;
}

/**
 * Union wrapper for size that can be either logical or physical
 */
class Size {
  /**
   * Create logical size wrapper
   * @param width - Width in logical pixels
   * @param height - Height in logical pixels
   * @returns Size instance wrapping LogicalSize
   */
  static logical(width: number, height: number): Size;
  
  /**
   * Create physical size wrapper
   * @param width - Width in physical pixels
   * @param height - Height in physical pixels
   * @returns Size instance wrapping PhysicalSize
   */
  static physical(width: number, height: number): Size;
}

/**
 * Position in logical (device-independent) pixels
 */
class LogicalPosition {
  /**
   * Create logical position
   * @param x - X coordinate in logical pixels
   * @param y - Y coordinate in logical pixels
   */
  constructor(x: number, y: number);
  
  /**
   * Convert to physical pixels
   * @param scaleFactor - Device scale factor
   * @returns Equivalent position in physical pixels
   */
  toPhysical(scaleFactor: number): PhysicalPosition;
}

/**
 * Position in physical (actual screen) pixels
 */
class PhysicalPosition {
  /**
   * Create physical position
   * @param x - X coordinate in physical pixels
   * @param y - Y coordinate in physical pixels
   */
  constructor(x: number, y: number);
  
  /**
   * Convert to logical pixels
   * @param scaleFactor - Device scale factor
   * @returns Equivalent position in logical pixels
   */
  toLogical(scaleFactor: number): LogicalPosition;
}

/**
 * Union wrapper for position that can be either logical or physical
 */
class Position {
  /**
   * Create logical position wrapper
   * @param x - X coordinate in logical pixels
   * @param y - Y coordinate in logical pixels
   * @returns Position instance wrapping LogicalPosition
   */
  static logical(x: number, y: number): Position;
  
  /**
   * Create physical position wrapper
   * @param x - X coordinate in physical pixels
   * @param y - Y coordinate in physical pixels
   * @returns Position instance wrapping PhysicalPosition
   */
  static physical(x: number, y: number): Position;
}

Usage Examples

Path Operations

import { join, resolve, dirname, basename, extname } from '@tauri-apps/api/path';

// Join path segments
const configPath = await join('config', 'app.json');
const fullPath = await join(await homeDir(), '.myapp', 'config.toml');

// Path resolution
const absolutePath = await resolve('../config', 'settings.json');
const normalizedPath = await normalize('/path/to/../config/./app.json');

// Extract path components
const dir = await dirname('/path/to/file.txt'); // '/path/to'
const filename = await basename('/path/to/file.txt'); // 'file.txt'
const nameOnly = await basename('/path/to/file.txt', '.txt'); // 'file'
const extension = await extname('/path/to/file.txt'); // '.txt'

// Check path type
const isAbs = await isAbsolute('/absolute/path'); // true
const isRel = await isAbsolute('relative/path'); // false

Directory Access

import { 
  appDataDir, 
  appConfigDir, 
  homeDir, 
  downloadDir,
  tempDir 
} from '@tauri-apps/api/path';

// Application directories
const dataDir = await appDataDir(); // ~/.local/share/myapp on Linux
const configDir = await appConfigDir(); // ~/.config/myapp on Linux
const cacheDir = await appCacheDir(); // ~/.cache/myapp on Linux

// User directories
const home = await homeDir(); // /home/user on Linux
const downloads = await downloadDir(); // ~/Downloads
const temp = await tempDir(); // /tmp on Unix

// Create application directories
import { mkdir } from '@tauri-apps/api/fs';
await mkdir(await join(dataDir, 'databases'), { recursive: true });
await mkdir(await join(configDir, 'themes'), { recursive: true });

Resource Path Resolution

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

// Resolve bundled resource
const iconPath = await resolveResource('icons/app-icon.png');
const configPath = await resolveResource('config/default.json');

// Convert to URL for web content
const iconUrl = convertFileSrc(iconPath);
const backgroundUrl = convertFileSrc(await resolveResource('images/bg.jpg'));

// Use in HTML
document.getElementById('app-icon').src = iconUrl;
document.body.style.backgroundImage = `url(${backgroundUrl})`;

Image Processing

import { Image } from '@tauri-apps/api/image';
import { resolveResource } from '@tauri-apps/api/path';

// Load image from file
const iconPath = await resolveResource('icons/app-icon.png');
const icon = await Image.fromPath(iconPath);

// Get image info
const size = await icon.size();
console.log(`Icon size: ${size.width}x${size.height}`);

// Get raw pixel data
const rgba = await icon.rgba();
console.log(`Image has ${rgba.length / 4} pixels`);

// Create image from data
const redPixel = [255, 0, 0, 255]; // Red pixel
const redSquare = await Image.new(
  Array(64 * 64 * 4).fill(0).map((_, i) => redPixel[i % 4]),
  64,
  64
);

// Load from binary data
const response = await fetch('/api/image');
const buffer = await response.arrayBuffer();
const image = await Image.fromBytes(buffer);

DPI-Aware Sizing

import { LogicalSize, PhysicalSize, getCurrentWindow } from '@tauri-apps/api/window';

// Get current window
const window = getCurrentWindow();

// Work with logical coordinates (DPI-independent)
const logicalSize = new LogicalSize(800, 600);
await window.setSize(logicalSize);

// Convert between logical and physical
const scaleFactor = 2.0; // High-DPI display
const physicalSize = logicalSize.toPhysical(scaleFactor);
console.log(`Logical: 800x600, Physical: ${physicalSize.width}x${physicalSize.height}`);

// Position windows consistently across different DPI displays
const logicalPos = new LogicalPosition(100, 100);
await window.setPosition(logicalPos);

// Handle DPI changes
await window.listen('tauri://scale-change', (event) => {
  const newScaleFactor = event.payload.scaleFactor;
  // Adjust UI elements for new scale factor
});

Cross-Platform File Handling

import { 
  sep, 
  join, 
  homeDir, 
  appDataDir,
  BaseDirectory 
} from '@tauri-apps/api/path';

// Platform-aware path construction
const separator = await sep(); // '/' on Unix, '\' on Windows
const userFile = await join(await homeDir(), 'Documents', 'myfile.txt');

// Application data storage
const appData = await appDataDir();
const dbPath = await join(appData, 'database.sqlite');
const logPath = await join(await appLogDir(), 'app.log');

// Use BaseDirectory enum with other APIs
import { readTextFile, writeTextFile } from '@tauri-apps/api/fs';

const config = await readTextFile('config.json', { 
  dir: BaseDirectory.AppConfig 
});

await writeTextFile('settings.json', JSON.stringify(settings), {
  dir: BaseDirectory.AppData
});

Error Handling

import { join, appDataDir } from '@tauri-apps/api/path';

try {
  const dataDir = await appDataDir();
  const filePath = await join(dataDir, 'important.json');
  
  // Use the path...
} catch (error) {
  // Common errors:
  // - Directory doesn't exist
  // - Permission denied
  // - Invalid path characters
  console.error('Path operation failed:', error);
}

Platform Differences

Different operating systems have different directory conventions:

  • Windows: Uses \ as path separator, different directory locations
  • macOS: Unix-like paths but different app data locations
  • Linux: Follows XDG Base Directory specification

The Tauri path API abstracts these differences, providing consistent behavior across platforms while respecting platform conventions for directory locations.

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