or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-line-config.mdindex.mdlanguage-services.mdnode-factory-transformers.mdparser-ast.mdprogram-compilation.mdtranspilation.mdtype-checker.mdutilities-helpers.md

program-compilation.mddocs/

0

# Program and Compilation

1

2

High-level compilation interface that manages multiple source files, handles module resolution, and orchestrates the compilation process from parsing to emit.

3

4

## Capabilities

5

6

### Program Creation

7

8

Create and manage TypeScript compilation programs.

9

10

```typescript { .api }

11

/**

12

* Create a TypeScript program from source files and options

13

* @param rootNames - Array of root file names to compile

14

* @param options - Compiler options

15

* @param host - Optional compiler host (defaults to system host)

16

* @param oldProgram - Previous program for incremental compilation

17

* @param configFileParsingDiagnostics - Diagnostics from config file parsing

18

* @returns Program instance

19

*/

20

function createProgram(

21

rootNames: readonly string[],

22

options: CompilerOptions,

23

host?: CompilerHost,

24

oldProgram?: Program,

25

configFileParsingDiagnostics?: readonly Diagnostic[]

26

): Program;

27

28

/**

29

* Create a default compiler host

30

* @param options - Compiler options

31

* @param setParentNodes - Whether to set parent node references

32

* @returns Compiler host instance

33

*/

34

function createCompilerHost(

35

options: CompilerOptions,

36

setParentNodes?: boolean

37

): CompilerHost;

38

39

/**

40

* Create a watch compiler host for file watching scenarios

41

* @param configFileName - Path to tsconfig.json

42

* @param optionsToExtend - Additional options to extend config

43

* @param system - System interface for file operations

44

* @param createProgram - Custom program creation function

45

* @param reportDiagnostic - Diagnostic reporting callback

46

* @param reportWatchStatus - Watch status reporting callback

47

* @returns Watch compiler host

48

*/

49

function createWatchCompilerHost<T extends BuilderProgram>(

50

configFileName: string,

51

optionsToExtend: CompilerOptions | undefined,

52

system: System,

53

createProgram?: CreateProgram<T>,

54

reportDiagnostic?: DiagnosticReporter,

55

reportWatchStatus?: WatchStatusReporter

56

): WatchCompilerHost<T>;

57

```

58

59

**Usage Examples:**

60

61

```typescript

62

import * as ts from "typescript";

63

64

// Create a simple program

65

const program = ts.createProgram({

66

rootNames: ["src/index.ts", "src/utils.ts"],

67

options: {

68

target: ts.ScriptTarget.ES2020,

69

module: ts.ModuleKind.CommonJS,

70

outDir: "dist",

71

declaration: true,

72

strict: true

73

}

74

});

75

76

// Get source files

77

const sourceFiles = program.getSourceFiles();

78

console.log(`Program has ${sourceFiles.length} source files`);

79

80

// Check for errors

81

const diagnostics = ts.getPreEmitDiagnostics(program);

82

if (diagnostics.length > 0) {

83

console.log(ts.formatDiagnosticsWithColorAndContext(diagnostics, {

84

getCurrentDirectory: () => ts.sys.getCurrentDirectory(),

85

getCanonicalFileName: (fileName) => fileName,

86

getNewLine: () => ts.sys.newLine

87

}));

88

}

89

90

// Emit JavaScript files

91

const emitResult = program.emit();

92

console.log(`Emit skipped: ${emitResult.emitSkipped}`);

93

```

94

95

### Program Interface

96

97

Core program methods for accessing compilation information.

98

99

```typescript { .api }

100

interface Program {

101

/**

102

* Get the root file names passed to the program

103

* @returns Array of root file names

104

*/

105

getRootFileNames(): readonly string[];

106

107

/**

108

* Get a specific source file by name

109

* @param fileName - Name of source file to retrieve

110

* @returns Source file or undefined

111

*/

112

getSourceFile(fileName: string): SourceFile | undefined;

113

114

/**

115

* Get all source files in the program

116

* @returns Array of all source files

117

*/

118

getSourceFiles(): readonly SourceFile[];

119

120

/**

121

* Get the compiler options used by the program

122

* @returns Compiler options

123

*/

124

getCompilerOptions(): CompilerOptions;

125

126

/**

127

* Get the current working directory

128

* @returns Current directory path

129

*/

130

getCurrentDirectory(): string;

131

132

/**

133

* Get the type checker for semantic analysis

134

* @returns Type checker instance

135

*/

136

getTypeChecker(): TypeChecker;

137

138

/**

139

* Check if a source file is from an external library

140

* @param file - Source file to check

141

* @returns True if from external library

142

*/

143

isSourceFileFromExternalLibrary(file: SourceFile): boolean;

144

145

/**

146

* Check if a source file is a default library file

147

* @param file - Source file to check

148

* @returns True if default library file

149

*/

150

isSourceFileDefaultLibrary(file: SourceFile): boolean;

151

}

152

```

153

154

### Program Diagnostics

155

156

Get compilation diagnostics and errors.

157

158

```typescript { .api }

159

interface Program {

160

/**

161

* Get syntactic diagnostics for a source file

162

* @param sourceFile - Source file to analyze (all files if undefined)

163

* @returns Array of syntactic diagnostics

164

*/

165

getSyntacticDiagnostics(sourceFile?: SourceFile): readonly Diagnostic[];

166

167

/**

168

* Get semantic diagnostics for a source file

169

* @param sourceFile - Source file to analyze (all files if undefined)

170

* @param cancellationToken - Token for cancelling operation

171

* @returns Array of semantic diagnostics

172

*/

173

getSemanticDiagnostics(

174

sourceFile?: SourceFile,

175

cancellationToken?: CancellationToken

176

): readonly Diagnostic[];

177

178

/**

179

* Get declaration diagnostics for a source file

180

* @param sourceFile - Source file to analyze (all files if undefined)

181

* @param cancellationToken - Token for cancelling operation

182

* @returns Array of declaration diagnostics

183

*/

184

getDeclarationDiagnostics(

185

sourceFile?: SourceFile,

186

cancellationToken?: CancellationToken

187

): readonly Diagnostic[];

188

189

/**

190

* Get configuration file diagnostics

191

* @returns Array of config file diagnostics

192

*/

193

getConfigFileParsingDiagnostics(): readonly Diagnostic[];

194

195

/**

196

* Get option diagnostics

197

* @param cancellationToken - Token for cancelling operation

198

* @returns Array of option diagnostics

199

*/

200

getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];

201

202

/**

203

* Get global diagnostics

204

* @param cancellationToken - Token for cancelling operation

205

* @returns Array of global diagnostics

206

*/

207

getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];

208

}

209

210

/**

211

* Get all pre-emit diagnostics for a program

212

* @param program - Program to analyze

213

* @param sourceFile - Specific source file (all files if undefined)

214

* @param cancellationToken - Token for cancelling operation

215

* @returns Combined array of all diagnostics

216

*/

217

function getPreEmitDiagnostics(

218

program: Program,

219

sourceFile?: SourceFile,

220

cancellationToken?: CancellationToken

221

): readonly Diagnostic[];

222

```

223

224

### Code Emission

225

226

Emit JavaScript and declaration files from TypeScript.

227

228

```typescript { .api }

229

interface Program {

230

/**

231

* Emit JavaScript and declaration files

232

* @param targetSourceFile - Specific file to emit (all files if undefined)

233

* @param writeFile - Custom file writing function

234

* @param cancellationToken - Token for cancelling operation

235

* @param emitOnlyDtsFiles - Only emit declaration files

236

* @param customTransformers - Custom AST transformers

237

* @returns Emit result with diagnostics and status

238

*/

239

emit(

240

targetSourceFile?: SourceFile,

241

writeFile?: WriteFileCallback,

242

cancellationToken?: CancellationToken,

243

emitOnlyDtsFiles?: boolean,

244

customTransformers?: CustomTransformers

245

): EmitResult;

246

}

247

248

interface EmitResult {

249

emitSkipped: boolean;

250

diagnostics: readonly Diagnostic[];

251

emittedFiles?: string[];

252

}

253

254

interface WriteFileCallback {

255

(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: readonly SourceFile[]): void;

256

}

257

258

interface CustomTransformers {

259

before?: readonly TransformerFactory<SourceFile>[];

260

after?: readonly TransformerFactory<SourceFile>[];

261

afterDeclarations?: readonly TransformerFactory<Bundle | SourceFile>[];

262

}

263

```

264

265

### Compiler Host

266

267

Interface for providing file system operations to the compiler.

268

269

```typescript { .api }

270

interface CompilerHost extends ModuleResolutionHost {

271

/**

272

* Get a source file by name

273

* @param fileName - Name of file to get

274

* @param languageVersion - Target language version

275

* @param onError - Error callback

276

* @param shouldCreateNewSourceFile - Whether to create new source file

277

* @returns Source file or undefined

278

*/

279

getSourceFile(

280

fileName: string,

281

languageVersion: ScriptTarget,

282

onError?: (message: string) => void,

283

shouldCreateNewSourceFile?: boolean

284

): SourceFile | undefined;

285

286

/**

287

* Write a file to disk

288

* @param fileName - Name of file to write

289

* @param data - File content

290

* @param writeByteOrderMark - Whether to write BOM

291

* @param onError - Error callback

292

* @param sourceFiles - Source files that generated this output

293

*/

294

writeFile: WriteFileCallback;

295

296

/**

297

* Get current directory

298

* @returns Current directory path

299

*/

300

getCurrentDirectory(): string;

301

302

/**

303

* Get directories in a path

304

* @param path - Directory path

305

* @returns Array of directory names

306

*/

307

getDirectories(path: string): string[];

308

309

/**

310

* Check if file exists

311

* @param fileName - File name to check

312

* @returns True if file exists

313

*/

314

fileExists(fileName: string): boolean;

315

316

/**

317

* Read file content

318

* @param fileName - File name to read

319

* @returns File content or undefined

320

*/

321

readFile(fileName: string): string | undefined;

322

323

/**

324

* Get canonical file name (for case sensitivity)

325

* @param fileName - File name to canonicalize

326

* @returns Canonical file name

327

*/

328

getCanonicalFileName(fileName: string): string;

329

330

/**

331

* Check if file names are case sensitive

332

* @returns True if case sensitive

333

*/

334

useCaseSensitiveFileNames(): boolean;

335

336

/**

337

* Get new line character

338

* @returns New line string

339

*/

340

getNewLine(): string;

341

}

342

```

343

344

### Configuration Management

345

346

Find and parse TypeScript configuration files.

347

348

```typescript { .api }

349

/**

350

* Find a configuration file starting from a path

351

* @param searchPath - Path to start searching from

352

* @param fileExists - Function to check if file exists

353

* @param configName - Configuration file name (default: "tsconfig.json")

354

* @returns Path to config file or undefined

355

*/

356

function findConfigFile(

357

searchPath: string,

358

fileExists: (fileName: string) => boolean,

359

configName?: string

360

): string | undefined;

361

362

/**

363

* Read a configuration file

364

* @param fileName - Path to configuration file

365

* @param readFile - Function to read file content

366

* @returns Configuration object and any errors

367

*/

368

function readConfigFile(

369

fileName: string,

370

readFile: (path: string) => string | undefined

371

): { config?: any; error?: Diagnostic };

372

373

/**

374

* Parse configuration file JSON text

375

* @param fileName - Configuration file name

376

* @param jsonText - JSON content of config file

377

* @returns Parsed configuration and any errors

378

*/

379

function parseConfigFileTextToJson(

380

fileName: string,

381

jsonText: string

382

): { config?: any; error?: Diagnostic };

383

384

/**

385

* Parse a JSON configuration file into compiler options

386

* @param json - Parsed JSON configuration

387

* @param host - Configuration parsing host

388

* @param basePath - Base path for resolving relative paths

389

* @param existingOptions - Existing options to extend

390

* @param configFileName - Name of configuration file

391

* @param resolutionStack - Stack for circular reference detection

392

* @returns Parsed command line options

393

*/

394

function parseJsonConfigFileContent(

395

json: any,

396

host: ParseConfigHost,

397

basePath: string,

398

existingOptions?: CompilerOptions,

399

configFileName?: string,

400

resolutionStack?: Path[]

401

): ParsedCommandLine;

402

```

403

404

### Module Resolution

405

406

Resolve module names and type reference directives.

407

408

```typescript { .api }

409

/**

410

* Resolve a module name to a file

411

* @param moduleName - Name of module to resolve

412

* @param containingFile - File that contains the import

413

* @param compilerOptions - Compiler options

414

* @param host - Module resolution host

415

* @param cache - Optional resolution cache

416

* @param redirectedReferences - Optional redirected project references

417

* @returns Resolved module with failed lookup locations

418

*/

419

function resolveModuleName(

420

moduleName: string,

421

containingFile: string,

422

compilerOptions: CompilerOptions,

423

host: ModuleResolutionHost,

424

cache?: ModuleResolutionCache,

425

redirectedReferences?: readonly ResolvedProjectReference[]

426

): ResolvedModuleWithFailedLookupLocations;

427

428

/**

429

* Resolve type reference directive to declaration file

430

* @param typeReferenceDirectiveName - Name of type reference

431

* @param containingFile - File that contains the reference

432

* @param options - Compiler options

433

* @param host - Module resolution host

434

* @param redirectedReference - Optional redirected project reference

435

* @param cache - Optional resolution cache

436

* @returns Resolved type reference directive

437

*/

438

function resolveTypeReferenceDirective(

439

typeReferenceDirectiveName: string,

440

containingFile: string | undefined,

441

options: CompilerOptions,

442

host: ModuleResolutionHost,

443

redirectedReference?: ResolvedProjectReference,

444

cache?: TypeReferenceDirectiveResolutionCache

445

): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;

446

447

/**

448

* Create module resolution cache for performance

449

* @param currentDirectory - Current working directory

450

* @param getCanonicalFileName - Function to canonicalize file names

451

* @param options - Compiler options

452

* @returns Module resolution cache

453

*/

454

function createModuleResolutionCache(

455

currentDirectory: string,

456

getCanonicalFileName: (fileName: string) => string,

457

options?: CompilerOptions

458

): ModuleResolutionCache;

459

460

interface ModuleResolutionHost {

461

fileExists(fileName: string): boolean;

462

readFile(fileName: string): string | undefined;

463

trace?(s: string): void;

464

directoryExists?(directoryName: string): boolean;

465

realpath?(path: string): string;

466

getCurrentDirectory?(): string;

467

getDirectories?(path: string): string[];

468

}

469

470

interface ResolvedModule {

471

resolvedFileName: string;

472

isExternalLibraryImport?: boolean;

473

packageId?: PackageId;

474

}

475

476

interface ResolvedModuleWithFailedLookupLocations {

477

resolvedModule: ResolvedModule | undefined;

478

failedLookupLocations: string[];

479

}

480

```

481

482

### Diagnostic Formatting

483

484

Format diagnostics for display.

485

486

```typescript { .api }

487

/**

488

* Format diagnostics as plain text

489

* @param diagnostics - Array of diagnostics to format

490

* @param host - Format host for path resolution

491

* @returns Formatted diagnostic string

492

*/

493

function formatDiagnostics(

494

diagnostics: readonly Diagnostic[],

495

host: FormatDiagnosticsHost

496

): string;

497

498

/**

499

* Format diagnostics with color and context

500

* @param diagnostics - Array of diagnostics to format

501

* @param host - Format host for path resolution

502

* @returns Formatted diagnostic string with colors

503

*/

504

function formatDiagnosticsWithColorAndContext(

505

diagnostics: readonly Diagnostic[],

506

host: FormatDiagnosticsHost

507

): string;

508

509

interface FormatDiagnosticsHost {

510

getCurrentDirectory(): string;

511

getCanonicalFileName(fileName: string): string;

512

getNewLine(): string;

513

}

514

```

515

516

## Types

517

518

### Compiler Options

519

520

```typescript { .api }

521

interface CompilerOptions {

522

// Target and Module

523

target?: ScriptTarget;

524

module?: ModuleKind;

525

lib?: string[];

526

allowJs?: boolean;

527

checkJs?: boolean;

528

declaration?: boolean;

529

declarationMap?: boolean;

530

emitDeclarationOnly?: boolean;

531

sourceMap?: boolean;

532

inlineSourceMap?: boolean;

533

inlineSources?: boolean;

534

535

// Output

536

outFile?: string;

537

outDir?: string;

538

rootDir?: string;

539

composite?: boolean;

540

tsBuildInfoFile?: string;

541

removeComments?: boolean;

542

noEmit?: boolean;

543

importHelpers?: boolean;

544

importsNotUsedAsValues?: ImportsNotUsedAsValues;

545

downlevelIteration?: boolean;

546

isolatedModules?: boolean;

547

548

// Strict Checks

549

strict?: boolean;

550

noImplicitAny?: boolean;

551

strictNullChecks?: boolean;

552

strictFunctionTypes?: boolean;

553

strictBindCallApply?: boolean;

554

strictPropertyInitialization?: boolean;

555

noImplicitThis?: boolean;

556

useUnknownInCatchVariables?: boolean;

557

alwaysStrict?: boolean;

558

559

// Additional Checks

560

noUnusedLocals?: boolean;

561

noUnusedParameters?: boolean;

562

exactOptionalPropertyTypes?: boolean;

563

noImplicitReturns?: boolean;

564

noFallthroughCasesInSwitch?: boolean;

565

noUncheckedIndexedAccess?: boolean;

566

noImplicitOverride?: boolean;

567

noPropertyAccessFromIndexSignature?: boolean;

568

569

// Module Resolution

570

moduleResolution?: ModuleResolutionKind;

571

baseUrl?: string;

572

paths?: MapLike<string[]>;

573

rootDirs?: string[];

574

typeRoots?: string[];

575

types?: string[];

576

allowSyntheticDefaultImports?: boolean;

577

esModuleInterop?: boolean;

578

preserveSymlinks?: boolean;

579

allowUmdGlobalAccess?: boolean;

580

581

// Source Maps

582

sourceRoot?: string;

583

mapRoot?: string;

584

585

// Experimental

586

experimentalDecorators?: boolean;

587

emitDecoratorMetadata?: boolean;

588

589

// Advanced

590

skipLibCheck?: boolean;

591

skipDefaultLibCheck?: boolean;

592

maxNodeModuleJsDepth?: number;

593

allowUnusedLabels?: boolean;

594

allowUnreachableCode?: boolean;

595

suppressExcessPropertyErrors?: boolean;

596

suppressImplicitAnyIndexErrors?: boolean;

597

forceConsistentCasingInFileNames?: boolean;

598

allowArbitraryExtensions?: boolean;

599

noErrorTruncation?: boolean;

600

preserveWatchOutput?: boolean;

601

pretty?: boolean;

602

disableSizeLimit?: boolean;

603

disableSourceOfProjectReferenceRedirect?: boolean;

604

disableReferencedProjectLoad?: boolean;

605

606

// Plugin System

607

plugins?: PluginImport[];

608

609

// Project References

610

incremental?: boolean;

611

assumeChangesOnlyAffectDirectDependencies?: boolean;

612

}

613

614

enum ScriptTarget {

615

ES3 = 0,

616

ES5 = 1,

617

ES2015 = 2,

618

ES2016 = 3,

619

ES2017 = 4,

620

ES2018 = 5,

621

ES2019 = 6,

622

ES2020 = 7,

623

ES2021 = 8,

624

ES2022 = 9,

625

ESNext = 99,

626

Latest = ESNext

627

}

628

629

enum ModuleKind {

630

None = 0,

631

CommonJS = 1,

632

AMD = 2,

633

UMD = 3,

634

System = 4,

635

ES2015 = 5,

636

ES2020 = 6,

637

ES2022 = 7,

638

ESNext = 99,

639

Node16 = 100,

640

NodeNext = 199

641

}

642

```

643

644

### Parse Results

645

646

```typescript { .api }

647

interface ParsedCommandLine {

648

options: CompilerOptions;

649

typeAcquisition?: TypeAcquisition;

650

fileNames: string[];

651

projectReferences?: readonly ProjectReference[] | undefined;

652

watchOptions?: WatchOptions;

653

raw?: any;

654

errors: Diagnostic[];

655

wildcardDirectories?: MapLike<WatchDirectoryFlags>;

656

compileOnSave?: boolean;

657

}

658

659

interface ProjectReference {

660

path: string;

661

originalPath?: string;

662

prepend?: boolean;

663

circular?: boolean;

664

}

665

```