or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

detection.mdfile-classes.mdfilesystem.mdindex.mdlambda.mdscript-execution.md

index.mddocs/

0

# @now/build-utils

1

2

@now/build-utils provides essential build utilities and abstractions for developing runtimes on the Now (later Vercel) serverless platform. It offers a comprehensive API for handling file operations, Lambda function creation and management, build process orchestration, and framework detection.

3

4

## Package Information

5

6

- **Package Name**: @now/build-utils

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @now/build-utils`

10

11

## Core Imports

12

13

```typescript

14

import {

15

FileBlob,

16

FileFsRef,

17

FileRef,

18

Lambda,

19

createLambda,

20

getLambdaOptionsFromFunction,

21

Prerender,

22

download,

23

DownloadedFiles,

24

glob,

25

GlobOptions,

26

rename,

27

getWriteableDirectory,

28

readConfigFile,

29

streamToBuffer,

30

isSymbolicLink,

31

execAsync,

32

spawnAsync,

33

execCommand,

34

spawnCommand,

35

runNpmInstall,

36

runBundleInstall,

37

runPipInstall,

38

runPackageJsonScript,

39

runShellScript,

40

installDependencies,

41

getNodeVersion,

42

getLatestNodeVersion,

43

getDiscontinuedNodeVersions,

44

getSpawnOptions,

45

detectBuilders,

46

detectFramework,

47

detectRoutes,

48

detectOutputDirectory,

49

detectApiDirectory,

50

detectApiExtensions,

51

DetectorFilesystem,

52

shouldServe,

53

debug,

54

NowBuildError

55

} from "@now/build-utils";

56

```

57

58

For CommonJS:

59

60

```javascript

61

const {

62

FileBlob,

63

FileFsRef,

64

FileRef,

65

Lambda,

66

createLambda,

67

getLambdaOptionsFromFunction,

68

Prerender,

69

download,

70

DownloadedFiles,

71

glob,

72

GlobOptions,

73

rename,

74

getWriteableDirectory,

75

readConfigFile,

76

streamToBuffer,

77

isSymbolicLink,

78

execAsync,

79

spawnAsync,

80

execCommand,

81

spawnCommand,

82

runNpmInstall,

83

runBundleInstall,

84

runPipInstall,

85

runPackageJsonScript,

86

runShellScript,

87

installDependencies,

88

getNodeVersion,

89

getLatestNodeVersion,

90

getDiscontinuedNodeVersions,

91

getSpawnOptions,

92

detectBuilders,

93

detectFramework,

94

detectRoutes,

95

detectOutputDirectory,

96

detectApiDirectory,

97

detectApiExtensions,

98

DetectorFilesystem,

99

shouldServe,

100

debug,

101

NowBuildError

102

} = require("@now/build-utils");

103

```

104

105

## Basic Usage

106

107

```typescript

108

import {

109

FileFsRef,

110

createLambda,

111

download,

112

execAsync

113

} from "@now/build-utils";

114

115

// Create file references

116

const entrypoint = new FileFsRef({ fsPath: "/path/to/index.js" });

117

118

// Download and process files

119

const files = {

120

"index.js": entrypoint,

121

"package.json": new FileFsRef({ fsPath: "/path/to/package.json" })

122

};

123

const downloadedFiles = await download(files, "/tmp/work");

124

125

// Execute build commands

126

await execAsync("npm", ["install"], { cwd: "/tmp/work" });

127

128

// Create Lambda function

129

const lambda = await createLambda({

130

files: downloadedFiles,

131

handler: "index.handler",

132

runtime: "nodejs14.x"

133

});

134

```

135

136

## Architecture

137

138

@now/build-utils is built around several key components:

139

140

- **File Abstractions**: Three file classes (`FileRef`, `FileFsRef`, `FileBlob`) representing different file storage types

141

- **Lambda System**: Tools for creating and managing serverless functions with proper bundling

142

- **Filesystem Utilities**: Functions for downloading, globbing, and manipulating files

143

- **Script Execution**: Utilities for running user scripts and package manager commands

144

- **Detection System**: Framework and builder detection for automatic configuration

145

- **Build Process**: Orchestration tools for the complete build pipeline

146

147

## Capabilities

148

149

### File System Operations

150

151

Core file handling utilities for managing different types of file references and performing filesystem operations during builds.

152

153

```typescript { .api }

154

function download(files: Files, basePath: string, meta?: Meta): Promise<DownloadedFiles>;

155

function glob(pattern: string, options?: GlobOptions): Promise<string[]>;

156

function rename(files: Files, renameFn: (name: string) => string): Files;

157

```

158

159

[File System Operations](./filesystem.md)

160

161

### Lambda Functions

162

163

Utilities for creating and managing serverless Lambda functions, including bundling files into deployment packages.

164

165

```typescript { .api }

166

function createLambda(options: CreateLambdaOptions): Promise<Lambda>;

167

function getLambdaOptionsFromFunction(options: GetLambdaOptionsFromFunctionOptions): Promise<Pick<LambdaOptions, 'memory' | 'maxDuration'>>;

168

169

interface CreateLambdaOptions {

170

files: Files;

171

handler: string;

172

runtime: string;

173

memory?: number;

174

maxDuration?: number;

175

environment?: { [key: string]: string };

176

}

177

```

178

179

[Lambda Functions](./lambda.md)

180

181

### Script Execution

182

183

Tools for executing build scripts, package manager commands, and shell operations with proper environment setup.

184

185

```typescript { .api }

186

function execAsync(command: string, args: string[], opts?: SpawnOptions): Promise<{ stdout: string; stderr: string; code: number }>;

187

function spawnAsync(command: string, args: string[], opts?: SpawnOptions): Promise<void>;

188

function runNpmInstall(destPath: string, args?: string[], spawnOpts?: SpawnOptions, meta?: Meta): Promise<void>;

189

```

190

191

[Script Execution](./script-execution.md)

192

193

### Framework and Builder Detection

194

195

Automatic detection of project frameworks and appropriate builders for zero-configuration deployments.

196

197

```typescript { .api }

198

function detectBuilders(files: string[], pkg?: PackageJson, options?: Options): { builders: Builder[]; errors: ErrorResponse[]; warnings: WarningResponse[] };

199

function detectFramework(options: DetectFrameworkOptions): Promise<string | null>;

200

function detectRoutes(filePaths: string[], builders: Builder[], options?: DetectRoutesOptions): Route[];

201

```

202

203

[Detection System](./detection.md)

204

205

### File Classes

206

207

Three specialized file classes for representing different types of file storage and enabling seamless file operations.

208

209

```typescript { .api }

210

class FileRef implements File {

211

constructor(options: FileRefOptions);

212

toStream(): NodeJS.ReadableStream;

213

}

214

215

class FileFsRef implements File {

216

constructor(options: FileFsRefOptions);

217

static fromFsPath(options: FileFsRefOptions): Promise<FileFsRef>;

218

toStream(): NodeJS.ReadableStream;

219

}

220

221

class FileBlob implements File {

222

constructor(options: FileBlobOptions);

223

static fromStream(options: FromStreamOptions): Promise<FileBlob>;

224

toStream(): NodeJS.ReadableStream;

225

}

226

```

227

228

[File Classes](./file-classes.md)

229

230

### Prerendering

231

232

Static site generation and prerendering support with Lambda fallbacks for dynamic routes.

233

234

```typescript { .api }

235

class Prerender {

236

constructor(options: PrerenderOptions);

237

}

238

239

interface PrerenderOptions {

240

expiration: number;

241

lambda: Lambda;

242

fallback: FileBlob | FileFsRef | FileRef | null;

243

group?: number;

244

}

245

```

246

247

### Utilities

248

249

Additional utility functions for build processes and request handling.

250

251

```typescript { .api }

252

function shouldServe(options: ShouldServeOptions): boolean;

253

function debug(message: string, ...additional: any[]): void;

254

255

interface ShouldServeOptions {

256

requestPath: string;

257

entrypoint: string;

258

files: { [path: string]: FileFsRef };

259

workPath: string;

260

config: Config;

261

}

262

```

263

264

## Core Types

265

266

```typescript { .api }

267

interface File {

268

type: string;

269

mode: number;

270

contentType?: string;

271

toStream(): NodeJS.ReadableStream;

272

fsPath?: string;

273

}

274

275

interface Files {

276

[filePath: string]: File;

277

}

278

279

interface Config {

280

[key: string]: string | string[] | boolean | number | { [key: string]: string } | BuilderFunctions | undefined;

281

maxLambdaSize?: string;

282

includeFiles?: string | string[];

283

excludeFiles?: string | string[];

284

bundle?: boolean;

285

ldsflags?: string;

286

helpers?: boolean;

287

rust?: string;

288

debug?: boolean;

289

zeroConfig?: boolean;

290

import?: { [key: string]: string };

291

functions?: BuilderFunctions;

292

outputDirectory?: string;

293

buildCommand?: string;

294

devCommand?: string;

295

framework?: string;

296

nodeVersion?: string;

297

}

298

299

interface Meta {

300

isDev?: boolean;

301

skipDownload?: boolean;

302

requestPath?: string;

303

filesChanged?: string[];

304

filesRemoved?: string[];

305

env?: Env;

306

buildEnv?: Env;

307

}

308

309

interface BuildOptions {

310

files: Files;

311

entrypoint: string;

312

workPath: string;

313

config: Config;

314

meta?: Meta;

315

}

316

317

interface Env {

318

[name: string]: string | undefined;

319

}

320

321

interface BuilderFunctions {

322

[key: string]: {

323

memory?: number;

324

maxDuration?: number;

325

runtime?: string;

326

includeFiles?: string;

327

excludeFiles?: string;

328

};

329

}

330

331

interface NodeVersion {

332

major: number;

333

range: string;

334

runtime: string;

335

discontinueDate?: Date;

336

}

337

338

interface Builder {

339

use: string;

340

src: string;

341

config?: Config;

342

}

343

344

class NowBuildError extends Error {

345

public hideStackTrace: boolean;

346

public code: string;

347

public link?: string;

348

349

constructor(options: { message: string; code: string; link?: string });

350

}

351

352

interface AnalyzeOptions {

353

/** All source files of the project */

354

files: { [filePath: string]: FileRef };

355

/** Name of entrypoint file for this particular build job */

356

entrypoint: string;

357

/** A writable temporary directory where you are encouraged to perform your build process */

358

workPath: string;

359

/** An arbitrary object passed by the user in the build definition */

360

config: Config;

361

}

362

363

interface PrepareCacheOptions {

364

/** All source files of the project */

365

files: Files;

366

/** Name of entrypoint file for this particular build job */

367

entrypoint: string;

368

/** A writable temporary directory where you are encouraged to perform your build process */

369

workPath: string;

370

/** A writable temporary directory where you can build a cache to use for the next run */

371

cachePath: string;

372

/** An arbitrary object passed by the user in the build definition */

373

config: Config;

374

}

375

376

interface NowRewrite {

377

source: string;

378

destination: string;

379

}

380

381

interface NowRedirect {

382

source: string;

383

destination: string;

384

statusCode?: number;

385

}

386

387

interface NowHeader {

388

source: string;

389

headers: NowHeaderKeyValue[];

390

}

391

392

interface NowHeaderKeyValue {

393

key: string;

394

value: string;

395

}

396

397

// JSON Schema definitions for validation

398

const functionsSchema: {

399

type: 'object';

400

minProperties: 1;

401

maxProperties: 50;

402

additionalProperties: false;

403

patternProperties: {

404

'^.{1,256}$': {

405

type: 'object';

406

additionalProperties: false;

407

properties: {

408

runtime?: { type: 'string'; maxLength: 256 };

409

memory?: { enum: number[] };

410

maxDuration?: { type: 'number'; minimum: 1; maximum: 900 };

411

includeFiles?: { type: 'string'; maxLength: 256 };

412

excludeFiles?: { type: 'string'; maxLength: 256 };

413

};

414

};

415

};

416

};

417

418

const buildsSchema: {

419

type: 'array';

420

minItems: 0;

421

maxItems: 128;

422

items: {

423

type: 'object';

424

additionalProperties: false;

425

required: ['use'];

426

properties: {

427

src?: { type: 'string'; minLength: 1; maxLength: 4096 };

428

use: { type: 'string'; minLength: 3; maxLength: 256 };

429

config?: { type: 'object' };

430

};

431

};

432

};

433

```