CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vite-node

Vite as Node.js runtime that enables on-demand evaluation with full ESM and TypeScript support

Pending
Overview
Eval results
Files

utils.mddocs/

Utilities

Path handling, module resolution, and platform utilities for working with file systems and import paths. These utilities provide cross-platform compatibility and normalization for module handling.

Capabilities

Path Utilities

Functions for handling and normalizing file paths across different platforms.

/** Convert backslashes to forward slashes for consistent path handling */
function slash(str: string): string;

/** Add trailing slash to path if not already present */
function withTrailingSlash(path: string): string;

/** Remove query parameters and hash from URL */  
function cleanUrl(url: string): string;

/** 
 * Convert ID to file path with existence check
 * Returns both the resolved path and whether the file exists
 */
function toFilePath(id: string, root: string): { path: string; exists: boolean };

Usage Examples:

import { slash, withTrailingSlash, cleanUrl, toFilePath } from "vite-node/utils";

// Convert Windows paths to Unix-style
const unixPath = slash("C:\\Users\\name\\file.js");
// Result: "C:/Users/name/file.js"

// Ensure trailing slash for directories
const dirPath = withTrailingSlash("/path/to/dir");
// Result: "/path/to/dir/"

// Clean URLs
const cleanPath = cleanUrl("/path/to/file.js?v=123#section");
// Result: "/path/to/file.js"

// Convert to file path with existence check
const { path, exists } = toFilePath("./src/app.ts", "/project/root");
// Result: { path: "/project/root/src/app.ts", exists: true }

Module ID Utilities

Functions for normalizing and working with module identifiers.

/** Normalize request ID by removing query parameters and handling base paths */
function normalizeRequestId(id: string, base?: string): string;

/** Normalize module ID for consistent caching and resolution */
function normalizeModuleId(id: string): string;

/** Check if import is a bare import (no relative/absolute path) */
function isBareImport(id: string): boolean;

/** Check if request is for internal Vite modules */
function isInternalRequest(id: string): boolean;

/** Check if module is a Node.js builtin module */
function isNodeBuiltin(id: string): boolean;

Usage Examples:

import { 
  normalizeRequestId, 
  normalizeModuleId, 
  isBareImport, 
  isInternalRequest,
  isNodeBuiltin 
} from "vite-node/utils";

// Normalize request IDs
const normalized = normalizeRequestId("/@id/__x00__virtual:my-module?v=123");
// Result: "\0virtual:my-module"

// Normalize module IDs
const moduleId = normalizeModuleId("file:///path/to/module.js");
// Result: "/path/to/module.js"

// Check import types
const isBare = isBareImport("lodash");          // true
const isRelative = isBareImport("./local");     // false

// Check for internal requests
const isInternal = isInternalRequest("@vite/client");  // true

// Check for Node builtins
const isBuiltin = isNodeBuiltin("fs");          // true
const isPrefixed = isNodeBuiltin("node:fs");    // true

Type Utilities

Type checking and conversion utilities.

/** Check if value is a primitive type */
function isPrimitive(v: any): boolean;

/** Convert value to array, handling null/undefined */
function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;

Usage Examples:

import { isPrimitive, toArray } from "vite-node/utils";

// Check primitive types
const isPrim = isPrimitive("string");    // true
const isObj = isPrimitive({});           // false

// Convert to array
const arr1 = toArray("single");          // ["single"]
const arr2 = toArray(["already", "array"]); // ["already", "array"]
const arr3 = toArray(null);              // []

Environment Utilities

Utilities for working with environment variables and platform detection.

/** Platform detection - true on Windows */
const isWindows: boolean;

/** Create import.meta.env proxy for environment variables */
function createImportMetaEnvProxy(): NodeJS.ProcessEnv;

Usage Examples:

import { isWindows, createImportMetaEnvProxy } from "vite-node/utils";

// Platform-specific code
if (isWindows) {
  // Handle Windows-specific paths
}

// Create environment proxy
const env = createImportMetaEnvProxy();
console.log(env.NODE_ENV); // Properly typed environment access

Package Resolution

Utilities for finding and parsing package.json files.

/**
 * Find the nearest package.json file walking up the directory tree
 * Returns package data including module type information
 */
function findNearestPackageData(basedir: string): Promise<{ type?: 'module' | 'commonjs' }>;

Usage Examples:

import { findNearestPackageData } from "vite-node/utils";

// Find package information
const pkgData = await findNearestPackageData("/project/src/components");
if (pkgData.type === 'module') {
  // Handle ESM package
} else {
  // Handle CommonJS package  
}

Cache Utilities

Generic caching utilities for performance optimization.

/**
 * Get cached data with path traversal optimization
 * Optimizes cache lookups by sharing data across directory paths
 */
function getCachedData<T>(
  cache: Map<string, T>,
  basedir: string,
  originalBasedir: string
): NonNullable<T> | undefined;

/**
 * Set cached data with path traversal optimization
 * Shares cache entries across directory paths for efficiency
 */
function setCacheData<T>(
  cache: Map<string, T>,
  data: T,
  basedir: string,
  originalBasedir: string
): void;

Usage Examples:

import { getCachedData, setCacheData } from "vite-node/utils";

const cache = new Map<string, PackageInfo>();

// Set cache data (will be shared across path hierarchy)
setCacheData(cache, packageInfo, "/project/src/deep/path", "/project");

// Get cached data (may return data from parent directories)
const cached = getCachedData(cache, "/project/src", "/project");

Constants

Useful constants for module and path handling.

/** Valid ID prefix for special Vite module IDs */
const VALID_ID_PREFIX: string; // "/@id/"

Platform Compatibility

All utilities are designed to work consistently across platforms:

  • Windows: Handles drive letters, backslashes, and UNC paths
  • Unix/Linux: Standard Unix path handling
  • macOS: Full compatibility with case-sensitive/insensitive filesystems

Performance Considerations

Many utilities include performance optimizations:

  • Path Normalization: Cached regex patterns for fast processing
  • Module Resolution: Efficient builtin module detection
  • Cache Utilities: Path traversal optimization for hierarchical caching

Error Handling

Utilities handle edge cases gracefully:

  • Invalid Paths: Return sensible defaults or empty results
  • Missing Files: Existence checks return boolean flags
  • Platform Differences: Normalized handling across operating systems

Common error handling patterns:

// Safe file path conversion
const { path, exists } = toFilePath(userInput, projectRoot);
if (!exists) {
  // Handle missing file case
}

// Safe module ID normalization
try {
  const normalized = normalizeModuleId(userInput);
} catch (error) {
  // Handle invalid module ID
}

Install with Tessl CLI

npx tessl i tessl/npm-vite-node

docs

cli.md

client.md

hmr.md

index.md

server.md

source-maps.md

utils.md

tile.json