or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdclient.mdhmr.mdindex.mdserver.mdsource-maps.mdutils.md

utils.mddocs/

0

# Utilities

1

2

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.

3

4

## Capabilities

5

6

### Path Utilities

7

8

Functions for handling and normalizing file paths across different platforms.

9

10

```typescript { .api }

11

/** Convert backslashes to forward slashes for consistent path handling */

12

function slash(str: string): string;

13

14

/** Add trailing slash to path if not already present */

15

function withTrailingSlash(path: string): string;

16

17

/** Remove query parameters and hash from URL */

18

function cleanUrl(url: string): string;

19

20

/**

21

* Convert ID to file path with existence check

22

* Returns both the resolved path and whether the file exists

23

*/

24

function toFilePath(id: string, root: string): { path: string; exists: boolean };

25

```

26

27

**Usage Examples:**

28

29

```typescript

30

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

31

32

// Convert Windows paths to Unix-style

33

const unixPath = slash("C:\\Users\\name\\file.js");

34

// Result: "C:/Users/name/file.js"

35

36

// Ensure trailing slash for directories

37

const dirPath = withTrailingSlash("/path/to/dir");

38

// Result: "/path/to/dir/"

39

40

// Clean URLs

41

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

42

// Result: "/path/to/file.js"

43

44

// Convert to file path with existence check

45

const { path, exists } = toFilePath("./src/app.ts", "/project/root");

46

// Result: { path: "/project/root/src/app.ts", exists: true }

47

```

48

49

### Module ID Utilities

50

51

Functions for normalizing and working with module identifiers.

52

53

```typescript { .api }

54

/** Normalize request ID by removing query parameters and handling base paths */

55

function normalizeRequestId(id: string, base?: string): string;

56

57

/** Normalize module ID for consistent caching and resolution */

58

function normalizeModuleId(id: string): string;

59

60

/** Check if import is a bare import (no relative/absolute path) */

61

function isBareImport(id: string): boolean;

62

63

/** Check if request is for internal Vite modules */

64

function isInternalRequest(id: string): boolean;

65

66

/** Check if module is a Node.js builtin module */

67

function isNodeBuiltin(id: string): boolean;

68

```

69

70

**Usage Examples:**

71

72

```typescript

73

import {

74

normalizeRequestId,

75

normalizeModuleId,

76

isBareImport,

77

isInternalRequest,

78

isNodeBuiltin

79

} from "vite-node/utils";

80

81

// Normalize request IDs

82

const normalized = normalizeRequestId("/@id/__x00__virtual:my-module?v=123");

83

// Result: "\0virtual:my-module"

84

85

// Normalize module IDs

86

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

87

// Result: "/path/to/module.js"

88

89

// Check import types

90

const isBare = isBareImport("lodash"); // true

91

const isRelative = isBareImport("./local"); // false

92

93

// Check for internal requests

94

const isInternal = isInternalRequest("@vite/client"); // true

95

96

// Check for Node builtins

97

const isBuiltin = isNodeBuiltin("fs"); // true

98

const isPrefixed = isNodeBuiltin("node:fs"); // true

99

```

100

101

### Type Utilities

102

103

Type checking and conversion utilities.

104

105

```typescript { .api }

106

/** Check if value is a primitive type */

107

function isPrimitive(v: any): boolean;

108

109

/** Convert value to array, handling null/undefined */

110

function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;

111

```

112

113

**Usage Examples:**

114

115

```typescript

116

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

117

118

// Check primitive types

119

const isPrim = isPrimitive("string"); // true

120

const isObj = isPrimitive({}); // false

121

122

// Convert to array

123

const arr1 = toArray("single"); // ["single"]

124

const arr2 = toArray(["already", "array"]); // ["already", "array"]

125

const arr3 = toArray(null); // []

126

```

127

128

### Environment Utilities

129

130

Utilities for working with environment variables and platform detection.

131

132

```typescript { .api }

133

/** Platform detection - true on Windows */

134

const isWindows: boolean;

135

136

/** Create import.meta.env proxy for environment variables */

137

function createImportMetaEnvProxy(): NodeJS.ProcessEnv;

138

```

139

140

**Usage Examples:**

141

142

```typescript

143

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

144

145

// Platform-specific code

146

if (isWindows) {

147

// Handle Windows-specific paths

148

}

149

150

// Create environment proxy

151

const env = createImportMetaEnvProxy();

152

console.log(env.NODE_ENV); // Properly typed environment access

153

```

154

155

### Package Resolution

156

157

Utilities for finding and parsing package.json files.

158

159

```typescript { .api }

160

/**

161

* Find the nearest package.json file walking up the directory tree

162

* Returns package data including module type information

163

*/

164

function findNearestPackageData(basedir: string): Promise<{ type?: 'module' | 'commonjs' }>;

165

```

166

167

**Usage Examples:**

168

169

```typescript

170

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

171

172

// Find package information

173

const pkgData = await findNearestPackageData("/project/src/components");

174

if (pkgData.type === 'module') {

175

// Handle ESM package

176

} else {

177

// Handle CommonJS package

178

}

179

```

180

181

### Cache Utilities

182

183

Generic caching utilities for performance optimization.

184

185

```typescript { .api }

186

/**

187

* Get cached data with path traversal optimization

188

* Optimizes cache lookups by sharing data across directory paths

189

*/

190

function getCachedData<T>(

191

cache: Map<string, T>,

192

basedir: string,

193

originalBasedir: string

194

): NonNullable<T> | undefined;

195

196

/**

197

* Set cached data with path traversal optimization

198

* Shares cache entries across directory paths for efficiency

199

*/

200

function setCacheData<T>(

201

cache: Map<string, T>,

202

data: T,

203

basedir: string,

204

originalBasedir: string

205

): void;

206

```

207

208

**Usage Examples:**

209

210

```typescript

211

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

212

213

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

214

215

// Set cache data (will be shared across path hierarchy)

216

setCacheData(cache, packageInfo, "/project/src/deep/path", "/project");

217

218

// Get cached data (may return data from parent directories)

219

const cached = getCachedData(cache, "/project/src", "/project");

220

```

221

222

### Constants

223

224

Useful constants for module and path handling.

225

226

```typescript { .api }

227

/** Valid ID prefix for special Vite module IDs */

228

const VALID_ID_PREFIX: string; // "/@id/"

229

```

230

231

## Platform Compatibility

232

233

All utilities are designed to work consistently across platforms:

234

235

- **Windows**: Handles drive letters, backslashes, and UNC paths

236

- **Unix/Linux**: Standard Unix path handling

237

- **macOS**: Full compatibility with case-sensitive/insensitive filesystems

238

239

## Performance Considerations

240

241

Many utilities include performance optimizations:

242

243

- **Path Normalization**: Cached regex patterns for fast processing

244

- **Module Resolution**: Efficient builtin module detection

245

- **Cache Utilities**: Path traversal optimization for hierarchical caching

246

247

## Error Handling

248

249

Utilities handle edge cases gracefully:

250

251

- **Invalid Paths**: Return sensible defaults or empty results

252

- **Missing Files**: Existence checks return boolean flags

253

- **Platform Differences**: Normalized handling across operating systems

254

255

Common error handling patterns:

256

257

```typescript

258

// Safe file path conversion

259

const { path, exists } = toFilePath(userInput, projectRoot);

260

if (!exists) {

261

// Handle missing file case

262

}

263

264

// Safe module ID normalization

265

try {

266

const normalized = normalizeModuleId(userInput);

267

} catch (error) {

268

// Handle invalid module ID

269

}

270

```