Build utilities for Vercel platform builders and serverless functions, providing utilities for creating and managing Lambda functions, file operations, and build-time helpers for the Vercel deployment platform
npx @tessl/cli install tessl/npm-vercel--build-utils@2.7.00
# @vercel/build-utils
1
2
@vercel/build-utils is a comprehensive TypeScript library providing essential build utilities for the Vercel platform. It serves as the foundation for creating custom builders and managing serverless functions, offering file system operations, Lambda function creation and management, process execution utilities, and framework detection capabilities.
3
4
## Package Information
5
6
- **Package Name**: @vercel/build-utils
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @vercel/build-utils`
10
- **Version**: 2.7.0
11
- **License**: MIT
12
13
## Core Imports
14
15
```typescript
16
import {
17
FileBlob,
18
FileFsRef,
19
FileRef,
20
Lambda,
21
createLambda,
22
Prerender,
23
download,
24
glob,
25
getWriteableDirectory,
26
rename,
27
streamToBuffer,
28
readConfigFile,
29
spawnAsync,
30
execAsync,
31
spawnCommand,
32
execCommand,
33
installDependencies,
34
runNpmInstall,
35
runPackageJsonScript,
36
walkParentDirs,
37
getNodeVersion,
38
getNodeBinPath,
39
detectBuilders,
40
detectOutputDirectory,
41
detectApiDirectory,
42
detectFramework,
43
DetectorFilesystem,
44
isOfficialRuntime,
45
isStaticRuntime,
46
getPlatformEnv,
47
shouldServe,
48
debug,
49
NowBuildError
50
} from "@vercel/build-utils";
51
```
52
53
For CommonJS:
54
55
```javascript
56
const {
57
FileBlob,
58
FileFsRef,
59
FileRef,
60
Lambda,
61
createLambda,
62
Prerender,
63
download,
64
glob,
65
getWriteableDirectory,
66
rename,
67
streamToBuffer,
68
readConfigFile,
69
spawnAsync,
70
execAsync,
71
spawnCommand,
72
execCommand,
73
installDependencies,
74
runNpmInstall,
75
runPackageJsonScript,
76
walkParentDirs,
77
getNodeVersion,
78
getNodeBinPath,
79
detectBuilders,
80
detectOutputDirectory,
81
detectApiDirectory,
82
detectFramework,
83
DetectorFilesystem,
84
isOfficialRuntime,
85
isStaticRuntime,
86
getPlatformEnv,
87
shouldServe,
88
debug,
89
NowBuildError
90
} = require("@vercel/build-utils");
91
```
92
93
## Basic Usage
94
95
```typescript
96
import {
97
FileBlob,
98
FileFsRef,
99
createLambda,
100
download,
101
glob,
102
spawnAsync,
103
detectBuilders,
104
getPlatformEnv,
105
NowBuildError
106
} from "@vercel/build-utils";
107
108
// Create file references
109
const fileBlob = new FileBlob({ data: "console.log('Hello World')" });
110
const fileFsRef = await FileFsRef.fromFsPath({ fsPath: "/path/to/file.js" });
111
112
// Create a Lambda function
113
const files = { "index.js": fileBlob };
114
const lambda = await createLambda({
115
files,
116
handler: "index.handler",
117
runtime: "nodejs18.x",
118
environment: { NODE_ENV: "production" }
119
});
120
121
// Download files to filesystem
122
const downloadedFiles = await download(files, "/tmp/build", { isDev: false });
123
124
// Find files with patterns
125
const sourceFiles = await glob("**/*.js", "/src");
126
127
// Execute shell commands
128
await spawnAsync("npm", ["install"], { cwd: "/project" });
129
130
// Detect appropriate builders
131
const fileList = ["package.json", "pages/index.js", "api/users.js"];
132
const result = await detectBuilders(fileList);
133
134
// Handle environment variables
135
const deploymentUrl = getPlatformEnv("URL");
136
const region = getPlatformEnv("REGION");
137
138
// Error handling
139
try {
140
await spawnAsync("npm", ["run", "build"]);
141
} catch (error) {
142
if (error instanceof NowBuildError) {
143
console.error(`Build failed [${error.code}]: ${error.message}`);
144
}
145
}
146
```
147
148
## Architecture
149
150
@vercel/build-utils is organized around several key components:
151
152
- **File System**: File abstraction classes (`FileBlob`, `FileFsRef`, `FileRef`) for representing different file sources
153
- **Lambda Management**: Creation and configuration of serverless Lambda functions
154
- **Build Process**: Utilities for downloading, processing, and executing build steps
155
- **Framework Detection**: Automatic detection of project frameworks and appropriate builders
156
- **Process Execution**: Safe execution of user scripts and system commands
157
- **Platform Utilities**: Helper functions for environment variables and runtime detection
158
159
## Capabilities
160
161
### File System Operations
162
163
File handling, downloading, and pattern matching utilities for managing build assets and source files.
164
165
```typescript { .api }
166
function download(files: Files, basePath: string, meta?: Meta): Promise<DownloadedFiles>;
167
function glob(pattern: string, opts: GlobOptions | string, mountpoint?: string): Promise<FsFiles>;
168
```
169
170
[File Operations](./file-operations.md)
171
172
### Lambda Functions
173
174
Creation and management of serverless Lambda functions with ZIP packaging and configuration options.
175
176
```typescript { .api }
177
function createLambda(options: CreateLambdaOptions): Promise<Lambda>;
178
179
interface CreateLambdaOptions {
180
files: Files;
181
handler: string;
182
runtime: string;
183
memory?: number;
184
maxDuration?: number;
185
environment?: Environment;
186
}
187
188
class Lambda {
189
type: 'Lambda';
190
zipBuffer: Buffer;
191
handler: string;
192
runtime: string;
193
memory?: number;
194
maxDuration?: number;
195
environment: Environment;
196
}
197
```
198
199
[Lambda Functions](./lambda.md)
200
201
### Process Execution
202
203
Utilities for executing shell commands, installing dependencies, and running user scripts safely.
204
205
```typescript { .api }
206
function spawnAsync(command: string, args: string[], opts?: SpawnOptionsExtended): Promise<void>;
207
function execAsync(command: string, args: string[], opts?: SpawnOptionsExtended): Promise<{ stdout: string; stderr: string; code: number }>;
208
```
209
210
[Process Execution](./process-execution.md)
211
212
### Builder Detection
213
214
Automatic detection of project frameworks and configuration of appropriate build strategies.
215
216
```typescript { .api }
217
function detectBuilders(files: string[], pkg?: PackageJson, options?: Options): Promise<{
218
builders: Builder[] | null;
219
errors: ErrorResponse[] | null;
220
warnings: ErrorResponse[];
221
defaultRoutes: Route[] | null;
222
redirectRoutes: Route[] | null;
223
rewriteRoutes: Route[] | null;
224
errorRoutes: Route[] | null;
225
}>;
226
```
227
228
[Builder Detection](./builder-detection.md)
229
230
### Platform Utilities
231
232
Helper functions for Vercel platform integration, environment variable handling, and runtime detection.
233
234
```typescript { .api }
235
function isOfficialRuntime(desired: string, name?: string): boolean;
236
function getPlatformEnv(name: string): string | undefined;
237
```
238
239
[Platform Utilities](./platform-utilities.md)
240
241
## Core Types
242
243
```typescript { .api }
244
interface Files {
245
[filePath: string]: File;
246
}
247
248
interface File {
249
type: string;
250
mode: number;
251
contentType?: string;
252
toStream: () => NodeJS.ReadableStream;
253
fsPath?: string;
254
}
255
256
interface Config {
257
[key: string]: string | string[] | boolean | number | { [key: string]: string } | BuilderFunctions | undefined;
258
maxLambdaSize?: string;
259
includeFiles?: string | string[];
260
excludeFiles?: string | string[];
261
bundle?: boolean;
262
functions?: BuilderFunctions;
263
outputDirectory?: string;
264
installCommand?: string;
265
buildCommand?: string;
266
devCommand?: string;
267
framework?: string;
268
nodeVersion?: string;
269
}
270
271
interface Meta {
272
isDev?: boolean;
273
devCacheDir?: string;
274
skipDownload?: boolean;
275
requestPath?: string | null;
276
filesChanged?: string[];
277
filesRemoved?: string[];
278
env?: Env;
279
buildEnv?: Env;
280
}
281
282
interface Env {
283
[name: string]: string | undefined;
284
}
285
286
interface Environment {
287
[key: string]: string;
288
}
289
290
interface BuildOptions {
291
files: Files;
292
entrypoint: string;
293
workPath: string;
294
repoRootPath?: string;
295
config: Config;
296
meta?: Meta;
297
}
298
299
interface AnalyzeOptions {
300
files: {
301
[filePath: string]: FileRef;
302
};
303
entrypoint: string;
304
workPath: string;
305
config: Config;
306
}
307
308
interface PrepareCacheOptions {
309
files: Files;
310
entrypoint: string;
311
workPath: string;
312
cachePath: string;
313
config: Config;
314
}
315
316
interface Builder {
317
use: string;
318
src?: string;
319
config?: Config;
320
}
321
322
interface BuilderFunctions {
323
[key: string]: {
324
memory?: number;
325
maxDuration?: number;
326
runtime?: string;
327
includeFiles?: string;
328
excludeFiles?: string;
329
};
330
}
331
332
interface NodeVersion {
333
major: number;
334
range: string;
335
runtime: string;
336
discontinueDate?: Date;
337
}
338
339
namespace PackageJson {
340
export interface Author {
341
name: string;
342
email?: string;
343
homepage?: string;
344
}
345
346
export interface BinMap {
347
[commandName: string]: string;
348
}
349
350
export interface Repository {
351
type: string;
352
url: string;
353
}
354
355
export interface DependencyMap {
356
[dependencyName: string]: string;
357
}
358
359
export interface ScriptsMap {
360
[scriptName: string]: string;
361
}
362
363
export interface Engines {
364
node?: string;
365
npm?: string;
366
}
367
}
368
369
interface PackageJson {
370
readonly name?: string;
371
readonly version?: string;
372
readonly description?: string;
373
readonly keywords?: string[];
374
readonly homepage?: string;
375
readonly license?: string;
376
readonly author?: string | PackageJson.Author;
377
readonly main?: string;
378
readonly bin?: string | PackageJson.BinMap;
379
readonly repository?: string | PackageJson.Repository;
380
readonly scripts?: PackageJson.ScriptsMap;
381
readonly dependencies?: PackageJson.DependencyMap;
382
readonly devDependencies?: PackageJson.DependencyMap;
383
readonly peerDependencies?: PackageJson.DependencyMap;
384
readonly engines?: PackageJson.Engines;
385
readonly private?: boolean;
386
}
387
```