or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

source-maps.mddocs/

0

# Source Maps

1

2

Inline source map support for debugging with accurate stack traces in transformed code. Provides essential debugging capabilities by mapping transformed code back to original source locations.

3

4

## Capabilities

5

6

### Source Map Installation

7

8

Install source map support for Node.js to enable accurate stack traces.

9

10

```typescript { .api }

11

/**

12

* Install source map support for Node.js error stack traces

13

* Enables accurate line numbers and file names in errors from transformed code

14

*/

15

function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void;

16

17

interface InstallSourceMapSupportOptions {

18

/** Function to retrieve source map for a given source file */

19

getSourceMap: (source: string) => EncodedSourceMap | null | undefined;

20

}

21

```

22

23

**Usage Examples:**

24

25

```typescript

26

import { installSourcemapsSupport } from "vite-node/source-map";

27

import { ViteNodeServer } from "vite-node/server";

28

29

const nodeServer = new ViteNodeServer(viteServer);

30

31

// Install source map support

32

installSourcemapsSupport({

33

getSourceMap: (source) => nodeServer.getSourceMap(source),

34

});

35

36

// Now errors will show original source locations instead of transformed code

37

```

38

39

### Inline Source Map Processing

40

41

Add inline source maps to transformation results for debugging support.

42

43

```typescript { .api }

44

/**

45

* Add inline source map to transformation result

46

* Embeds source map as base64 data URL in the transformed code

47

*/

48

function withInlineSourcemap(

49

result: TransformResult,

50

options: {

51

/** Project root path for resolving relative paths */

52

root: string;

53

/** File path of the transformed module */

54

filepath: string;

55

/** Skip first line mapping for Vite 6+ compatibility */

56

noFirstLineMapping?: boolean;

57

}

58

): TransformResult;

59

60

interface TransformResult {

61

/** Transformed JavaScript/TypeScript code */

62

code: string;

63

/** Source map for the transformation */

64

map?: any;

65

}

66

```

67

68

**Usage Examples:**

69

70

```typescript

71

import { withInlineSourcemap } from "vite-node/source-map";

72

73

// Add inline source map to transformation

74

const transformedResult = await viteServer.transformRequest('./app.ts');

75

const withSourceMap = withInlineSourcemap(transformedResult, {

76

root: '/project/root',

77

filepath: '/project/root/src/app.ts',

78

noFirstLineMapping: viteVersion >= 6,

79

});

80

81

// Code now includes inline source map

82

console.log(withSourceMap.code.includes('sourceMappingURL')); // true

83

```

84

85

### Source Map Extraction

86

87

Extract source maps from transformed code containing inline source maps.

88

89

```typescript { .api }

90

/**

91

* Extract source map from code containing inline source map

92

* Parses base64-encoded source map data from transformed code

93

*/

94

function extractSourceMap(code: string): EncodedSourceMap | null;

95

```

96

97

**Usage Examples:**

98

99

```typescript

100

import { extractSourceMap } from "vite-node/source-map";

101

102

// Extract source map from transformed code

103

const code = `

104

console.log('hello');

105

//# sourceMappingSource=vite-node

106

//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozfQ==

107

`;

108

109

const sourceMap = extractSourceMap(code);

110

if (sourceMap) {

111

console.log('Version:', sourceMap.version);

112

console.log('Sources:', sourceMap.sources);

113

}

114

```

115

116

## Source Map Types

117

118

Source maps use standard formats for maximum compatibility.

119

120

```typescript { .api }

121

/** Standard encoded source map format */

122

type EncodedSourceMap = {

123

version: number;

124

sources: string[];

125

names: string[];

126

mappings: string;

127

file?: string;

128

sourceRoot?: string;

129

sourcesContent?: (string | null)[];

130

};

131

```

132

133

## Source Map Features

134

135

### Vite-Node Specific Source Maps

136

137

Vite-node adds special handling for source maps:

138

139

- **Inline Embedding**: Source maps are embedded directly in transformed code

140

- **Path Normalization**: Ensures consistent path handling across platforms

141

- **Vite Integration**: Seamless integration with Vite's source map generation

142

- **Debug Support**: Special markers for vite-node generated source maps

143

144

### Path Resolution

145

146

Source maps handle complex path resolution scenarios:

147

148

```typescript

149

// Handles various path formats

150

const result = withInlineSourcemap(transformResult, {

151

root: '/project',

152

filepath: '/project/src/components/App.vue',

153

});

154

155

// Resolves relative paths correctly in source map

156

// Original: '/project/src/components/App.vue'

157

// In source map: 'src/components/App.vue' (relative to root)

158

```

159

160

### First Line Mapping

161

162

Special handling for import statements and module headers:

163

164

```typescript

165

// For Vite 5 and earlier - adds first line mapping

166

const older = withInlineSourcemap(result, {

167

root: projectRoot,

168

filepath: filePath,

169

noFirstLineMapping: false,

170

});

171

172

// For Vite 6+ - skips first line mapping (handled by Vite)

173

const newer = withInlineSourcemap(result, {

174

root: projectRoot,

175

filepath: filePath,

176

noFirstLineMapping: true,

177

});

178

```

179

180

## Debugging Workflow

181

182

Complete debugging setup with source maps:

183

184

```typescript

185

import { createServer } from "vite";

186

import { ViteNodeRunner } from "vite-node/client";

187

import { ViteNodeServer } from "vite-node/server";

188

import { installSourcemapsSupport } from "vite-node/source-map";

189

190

async function setupDebugging() {

191

// Create Vite server

192

const server = await createServer({

193

// Enable source maps in Vite

194

build: { sourcemap: true },

195

});

196

197

// Create vite-node server

198

const nodeServer = new ViteNodeServer(server, {

199

// Enable inline source maps

200

sourcemap: 'inline',

201

});

202

203

// Install source map support

204

installSourcemapsSupport({

205

getSourceMap: (source) => nodeServer.getSourceMap(source),

206

});

207

208

// Create runner

209

const runner = new ViteNodeRunner({

210

root: server.config.root,

211

fetchModule: (id) => nodeServer.fetchModule(id),

212

resolveId: (id, importer) => nodeServer.resolveId(id, importer),

213

});

214

215

// Execute with accurate stack traces

216

try {

217

await runner.executeFile('./src/app.ts');

218

} catch (error) {

219

// Error stack trace will show original TypeScript locations

220

console.error(error.stack);

221

}

222

}

223

```

224

225

## Performance Considerations

226

227

Source map processing is optimized for development use:

228

229

- **Lazy Generation**: Source maps are only processed when needed

230

- **Caching**: Source maps are cached to avoid repeated processing

231

- **Minimal Overhead**: Inline embedding has minimal impact on execution speed

232

- **Debug Mode**: Source map features can be disabled in production

233

234

## Error Handling

235

236

Source map functionality handles edge cases gracefully:

237

238

- **Missing Source Maps**: Functions continue to work without source maps

239

- **Invalid Format**: Graceful handling of malformed source map data

240

- **Path Resolution**: Fallback handling for unresolvable source paths

241

242

Common patterns:

243

244

```typescript

245

// Safe source map extraction

246

try {

247

const map = extractSourceMap(code);

248

if (map) {

249

// Use source map

250

processSourceMap(map);

251

}

252

} catch (error) {

253

// Fallback without source map

254

console.warn('Source map extraction failed:', error.message);

255

}

256

257

// Safe source map installation

258

try {

259

installSourcemapsSupport({

260

getSourceMap: (source) => {

261

try {

262

return nodeServer.getSourceMap(source);

263

} catch {

264

return null; // Fallback for missing maps

265

}

266

},

267

});

268

} catch (error) {

269

console.warn('Source map support installation failed:', error.message);

270

}

271

```

272

273

## Integration with Development Tools

274

275

Source maps work seamlessly with development tools:

276

277

- **VS Code**: Breakpoints work correctly in original TypeScript files

278

- **Chrome DevTools**: Stack traces show original source locations

279

- **Node.js Inspector**: Debugging sessions use original file paths

280

- **Error Reporting**: Production error tracking with source map support