0
# Programmatic API
1
2
RPC functions for programmatic access to inspection data from external tools and automated workflows.
3
4
## Capabilities
5
6
### Plugin API Access
7
8
Access to the plugin's RPC interface for programmatic inspection.
9
10
```typescript { .api }
11
interface ViteInspectAPI {
12
/** RPC functions for accessing inspection data */
13
rpc: RpcFunctions;
14
}
15
```
16
17
The plugin instance exposes an `api` property after being configured in a Vite server:
18
19
```typescript
20
// Access the API from a configured plugin
21
const inspect = Inspect({ dev: true });
22
23
// In configureServer hook or after server setup
24
const api: ViteInspectAPI = inspect.api;
25
const data = await api.rpc.getMetadata();
26
```
27
28
### RPC Functions Interface
29
30
Complete interface for all available RPC functions.
31
32
```typescript { .api }
33
interface RpcFunctions {
34
/** Get metadata about all Vite instances and their configurations */
35
getMetadata(): Promise<Metadata>;
36
/** Get list of all modules for a specific environment */
37
getModulesList(query: QueryEnv): Promise<ModulesList>;
38
/** Get detailed transformation info for a specific module */
39
getModuleTransformInfo(query: QueryEnv, id: string, clear?: boolean): Promise<ModuleTransformInfo>;
40
/** Get performance metrics for all plugins */
41
getPluginMetrics(query: QueryEnv): Promise<PluginMetricInfo[]>;
42
/** Get server middleware performance metrics */
43
getServerMetrics(query: QueryEnv): Promise<ServerMetrics>;
44
/** Resolve a module ID using Vite's resolution logic */
45
resolveId(query: QueryEnv, id: string): Promise<string>;
46
/** Notify when modules have been updated (for UI synchronization) */
47
onModuleUpdated(): Promise<void>;
48
}
49
```
50
51
### Query Parameters
52
53
Environment and instance identification for RPC calls.
54
55
```typescript { .api }
56
interface QueryEnv {
57
/** Vite instance ID */
58
vite: string;
59
/** Environment name ('client', 'ssr', etc.) */
60
env: string;
61
}
62
63
interface QueryId extends QueryEnv {
64
/** Module ID to query */
65
id: string;
66
}
67
```
68
69
**Usage Example:**
70
71
```typescript
72
// Query for client environment of a specific Vite instance
73
const query: QueryEnv = {
74
vite: 'vite-instance-id',
75
env: 'client'
76
};
77
78
const modules = await rpc.getModulesList(query);
79
const metrics = await rpc.getPluginMetrics(query);
80
```
81
82
### Metadata Access
83
84
Get comprehensive metadata about Vite instances and their configurations.
85
86
```typescript { .api }
87
interface Metadata {
88
/** Array of all Vite instance information */
89
instances: InstanceInfo[];
90
/** Whether embedded mode is enabled */
91
embedded?: boolean;
92
}
93
94
interface InstanceInfo {
95
/** Project root directory */
96
root: string;
97
/** Unique Vite instance identifier */
98
vite: string;
99
/** Array of environment names */
100
environments: string[];
101
/** Serialized plugin information */
102
plugins: SerializedPlugin[];
103
/** Mapping of environment names to plugin indices */
104
environmentPlugins: Record<string, number[]>;
105
}
106
107
interface SerializedPlugin {
108
/** Plugin name */
109
name: string;
110
/** Plugin enforcement mode */
111
enforce?: string;
112
/** Serialized resolveId hook */
113
resolveId: string;
114
/** Serialized load hook */
115
load: string;
116
/** Serialized transform hook */
117
transform: string;
118
/** Serialized generateBundle hook */
119
generateBundle: string;
120
/** Serialized handleHotUpdate hook */
121
handleHotUpdate: string;
122
/** Serialized api property */
123
api: string;
124
}
125
```
126
127
**Usage Example:**
128
129
```typescript
130
const metadata = await rpc.getMetadata();
131
132
console.log(`Found ${metadata.instances.length} Vite instances`);
133
metadata.instances.forEach(instance => {
134
console.log(`Instance: ${instance.vite}`);
135
console.log(`Root: ${instance.root}`);
136
console.log(`Environments: ${instance.environments.join(', ')}`);
137
console.log(`Plugins: ${instance.plugins.length}`);
138
});
139
```
140
141
### Module Resolution
142
143
Programmatically resolve module IDs using Vite's resolution logic.
144
145
```typescript { .api }
146
/**
147
* Resolve a module ID using Vite's resolution logic
148
* @param query - Environment query parameters
149
* @param id - Module ID to resolve
150
* @returns Promise resolving to the resolved module path
151
*/
152
resolveId(query: QueryEnv, id: string): Promise<string>;
153
```
154
155
**Usage Example:**
156
157
```typescript
158
// Resolve a relative import
159
const resolvedPath = await rpc.resolveId(
160
{ vite: 'instance-id', env: 'client' },
161
'./components/Button'
162
);
163
console.log('Resolved to:', resolvedPath);
164
165
// Resolve an npm package
166
const packagePath = await rpc.resolveId(
167
{ vite: 'instance-id', env: 'client' },
168
'vue'
169
);
170
console.log('Vue resolved to:', packagePath);
171
```
172
173
### Cache Management
174
175
Control caching behavior for module transformation info.
176
177
```typescript
178
// Get cached transformation info
179
const transformInfo = await rpc.getModuleTransformInfo(
180
{ vite: 'instance-id', env: 'client' },
181
'/src/App.vue',
182
false // don't clear cache
183
);
184
185
// Get fresh transformation info (clear cache)
186
const freshTransformInfo = await rpc.getModuleTransformInfo(
187
{ vite: 'instance-id', env: 'client' },
188
'/src/App.vue',
189
true // clear cache first
190
);
191
```
192
193
### Real-time Updates
194
195
Subscribe to module update notifications for real-time monitoring.
196
197
```typescript
198
// Set up update monitoring
199
const monitorUpdates = async () => {
200
try {
201
await rpc.onModuleUpdated();
202
console.log('Modules have been updated');
203
204
// Refresh data after updates
205
const updatedModules = await rpc.getModulesList({ vite: 'instance-id', env: 'client' });
206
console.log(`Now tracking ${updatedModules.length} modules`);
207
208
// Continue monitoring
209
monitorUpdates();
210
} catch (error) {
211
console.error('Update monitoring failed:', error);
212
// Retry after delay
213
setTimeout(monitorUpdates, 1000);
214
}
215
};
216
217
monitorUpdates();
218
```
219
220
### Automation Examples
221
222
#### Automated Performance Monitoring
223
224
```typescript
225
class PerformanceMonitor {
226
constructor(private rpc: RpcFunctions, private query: QueryEnv) {}
227
228
async generateReport() {
229
const [modules, metrics, serverMetrics] = await Promise.all([
230
this.rpc.getModulesList(this.query),
231
this.rpc.getPluginMetrics(this.query),
232
this.rpc.getServerMetrics(this.query)
233
]);
234
235
return {
236
timestamp: new Date().toISOString(),
237
moduleCount: modules.length,
238
slowestModules: modules
239
.sort((a, b) => b.totalTime - a.totalTime)
240
.slice(0, 10)
241
.map(m => ({ id: m.id, time: m.totalTime })),
242
pluginMetrics: metrics
243
.sort((a, b) => (b.transform.totalTime + b.resolveId.totalTime) - (a.transform.totalTime + a.resolveId.totalTime))
244
.slice(0, 5)
245
.map(p => ({
246
name: p.name,
247
totalTime: p.transform.totalTime + p.resolveId.totalTime,
248
calls: p.transform.invokeCount + p.resolveId.invokeCount
249
})),
250
serverMetrics
251
};
252
}
253
254
async watchPerformance(callback: (report: any) => void) {
255
const monitor = async () => {
256
try {
257
const report = await this.generateReport();
258
callback(report);
259
260
// Wait for next update
261
await this.rpc.onModuleUpdated();
262
setTimeout(monitor, 1000); // Debounce updates
263
} catch (error) {
264
console.error('Performance monitoring error:', error);
265
setTimeout(monitor, 5000); // Retry after error
266
}
267
};
268
269
monitor();
270
}
271
}
272
273
// Usage
274
const monitor = new PerformanceMonitor(rpc, { vite: 'instance-id', env: 'client' });
275
monitor.watchPerformance(report => {
276
console.log('Performance Report:', report);
277
278
// Alert on performance issues
279
if (report.slowestModules[0]?.time > 1000) {
280
console.warn(`Slow module detected: ${report.slowestModules[0].id} (${report.slowestModules[0].time}ms)`);
281
}
282
});
283
```
284
285
#### Build Analysis Tool
286
287
```typescript
288
async function analyzeBuild(rpc: RpcFunctions, query: QueryEnv) {
289
const metadata = await rpc.getMetadata();
290
const modules = await rpc.getModulesList(query);
291
const metrics = await rpc.getPluginMetrics(query);
292
293
const analysis = {
294
overview: {
295
totalModules: modules.length,
296
virtualModules: modules.filter(m => m.virtual).length,
297
totalSourceSize: modules.reduce((sum, m) => sum + m.sourceSize, 0),
298
totalDistSize: modules.reduce((sum, m) => sum + m.distSize, 0)
299
},
300
performance: {
301
totalPluginTime: metrics.reduce((sum, p) => sum + p.transform.totalTime + p.resolveId.totalTime, 0),
302
slowestPlugins: metrics
303
.sort((a, b) => (b.transform.totalTime + b.resolveId.totalTime) - (a.transform.totalTime + a.resolveId.totalTime))
304
.slice(0, 5),
305
modulesBySize: modules
306
.sort((a, b) => b.distSize - a.distSize)
307
.slice(0, 10)
308
},
309
dependencies: {
310
highlyImported: modules
311
.sort((a, b) => b.importers.length - a.importers.length)
312
.slice(0, 10)
313
.map(m => ({ id: m.id, importerCount: m.importers.length })),
314
heavyDependencies: modules
315
.sort((a, b) => b.deps.length - a.deps.length)
316
.slice(0, 10)
317
.map(m => ({ id: m.id, depCount: m.deps.length }))
318
}
319
};
320
321
return analysis;
322
}
323
```