tsz-cli 0.1.9

CLI binaries for the tsz TypeScript compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! Incremental Compilation Support
//!
//! This module implements TypeScript's incremental compilation feature, which enables:
//! - Faster rebuilds by caching compilation results
//! - .tsbuildinfo file persistence for cross-session caching
//! - Smart dependency tracking for minimal recompilation
//!
//! # Build Info Format
//!
//! The .tsbuildinfo file stores:
//! - Version information for cache invalidation
//! - File hashes for change detection
//! - Dependency graphs between files
//! - Emitted file signatures for output caching

use anyhow::{Context, Result};
use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

/// Version of the build info format
pub const BUILD_INFO_VERSION: &str = "0.1.0";

/// Build information persisted between compilations
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildInfo {
    /// Version of the build info format
    pub version: String,
    /// Compiler version that created this build info
    pub compiler_version: String,
    /// Root files that were compiled
    pub root_files: Vec<String>,
    /// Information about each compiled file
    pub file_infos: BTreeMap<String, FileInfo>,
    /// Dependency graph: file -> files it imports
    pub dependencies: BTreeMap<String, Vec<String>>,
    /// Semantic diagnostics for files (cached from previous builds)
    #[serde(default)]
    pub semantic_diagnostics_per_file: BTreeMap<String, Vec<CachedDiagnostic>>,
    /// Emit output signatures (for output file caching)
    pub emit_signatures: BTreeMap<String, EmitSignature>,
    /// Path to the most recently changed .d.ts file
    /// Used by project references for fast invalidation checking
    #[serde(
        rename = "latestChangedDtsFile",
        skip_serializing_if = "Option::is_none"
    )]
    pub latest_changed_dts_file: Option<String>,
    /// Options that affect compilation
    #[serde(default)]
    pub options: BuildInfoOptions,
    /// Timestamp of when the build was completed
    pub build_time: u64,
}

/// Information about a single compiled file
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileInfo {
    /// File version (content hash or modification time)
    pub version: String,
    /// Signature of the file's exports (for dependency tracking)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    /// Whether this file has changed since last build
    #[serde(default)]
    pub affected_files_pending_emit: bool,
    /// The file's import dependencies
    #[serde(default)]
    pub implied_format: Option<String>,
}

/// Emit output signature for caching
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmitSignature {
    /// Hash of the emitted JavaScript
    #[serde(skip_serializing_if = "Option::is_none")]
    pub js: Option<String>,
    /// Hash of the emitted declaration file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dts: Option<String>,
    /// Hash of the emitted source map
    #[serde(skip_serializing_if = "Option::is_none")]
    pub map: Option<String>,
}

/// Compiler options that affect build caching
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildInfoOptions {
    /// Target ECMAScript version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// Module system
    #[serde(skip_serializing_if = "Option::is_none")]
    pub module: Option<String>,
    /// Whether to emit declarations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub declaration: Option<bool>,
    /// Strict mode enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strict: Option<bool>,
}

/// Cached diagnostic information for incremental builds
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedDiagnostic {
    pub file: String,
    pub start: u32,
    pub length: u32,
    pub message_text: String,
    pub category: u8,
    pub code: u32,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub related_information: Vec<CachedRelatedInformation>,
}

/// Cached related information for diagnostics
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedRelatedInformation {
    pub file: String,
    pub start: u32,
    pub length: u32,
    pub message_text: String,
    pub category: u8,
    pub code: u32,
}

impl Default for BuildInfo {
    fn default() -> Self {
        Self {
            version: BUILD_INFO_VERSION.to_string(),
            compiler_version: env!("CARGO_PKG_VERSION").to_string(),
            root_files: Vec::new(),
            file_infos: BTreeMap::new(),
            dependencies: BTreeMap::new(),
            semantic_diagnostics_per_file: BTreeMap::new(),
            emit_signatures: BTreeMap::new(),
            latest_changed_dts_file: None,
            options: BuildInfoOptions::default(),
            build_time: SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
        }
    }
}

impl BuildInfo {
    /// Create a new empty build info
    pub fn new() -> Self {
        Self::default()
    }

    /// Load build info from a file
    /// Returns Ok(None) if the file exists but is incompatible (version mismatch)
    /// Returns `Ok(Some(build_info))` if the file is valid and compatible
    pub fn load(path: &Path) -> Result<Option<Self>> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read build info: {}", path.display()))?;

        let build_info: Self = serde_json::from_str(&content)
            .with_context(|| format!("failed to parse build info: {}", path.display()))?;

        // Validate version compatibility (Format version)
        if build_info.version != BUILD_INFO_VERSION {
            return Ok(None);
        }

        // Validate compiler version compatibility
        // This ensures changes in hashing algorithms or internal logic trigger a rebuild
        if build_info.compiler_version != env!("CARGO_PKG_VERSION") {
            return Ok(None);
        }

        Ok(Some(build_info))
    }

    /// Save build info to a file
    pub fn save(&self, path: &Path) -> Result<()> {
        // Create parent directories if needed
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory: {}", parent.display()))?;
        }

        let content =
            serde_json::to_string_pretty(self).context("failed to serialize build info")?;

        std::fs::write(path, content)
            .with_context(|| format!("failed to write build info: {}", path.display()))?;

        Ok(())
    }

    /// Add or update file info
    pub fn set_file_info(&mut self, path: &str, info: FileInfo) {
        self.file_infos.insert(path.to_string(), info);
    }

    /// Get file info
    pub fn get_file_info(&self, path: &str) -> Option<&FileInfo> {
        self.file_infos.get(path)
    }

    /// Set dependencies for a file
    pub fn set_dependencies(&mut self, path: &str, deps: Vec<String>) {
        self.dependencies.insert(path.to_string(), deps);
    }

    /// Get dependencies for a file
    pub fn get_dependencies(&self, path: &str) -> Option<&[String]> {
        self.dependencies.get(path).map(std::vec::Vec::as_slice)
    }

    /// Set emit signature for a file
    pub fn set_emit_signature(&mut self, path: &str, signature: EmitSignature) {
        self.emit_signatures.insert(path.to_string(), signature);
    }

    /// Check if a file has changed since last build
    pub fn has_file_changed(&self, path: &str, current_version: &str) -> bool {
        match self.file_infos.get(path) {
            Some(info) => info.version != current_version,
            None => true, // New file
        }
    }

    /// Get all files that depend on a given file
    pub fn get_dependents(&self, path: &str) -> Vec<String> {
        self.dependencies
            .iter()
            .filter(|(_, deps)| deps.iter().any(|d| d == path))
            .map(|(file, _)| file.clone())
            .collect()
    }
}

/// Tracks changes between builds
#[derive(Debug, Default)]
pub struct ChangeTracker {
    /// Files that have been modified
    changed_files: FxHashSet<PathBuf>,
    /// Files that need to be recompiled (changed + dependents)
    affected_files: FxHashSet<PathBuf>,
    /// Files that are new since last build
    new_files: FxHashSet<PathBuf>,
    /// Files that have been deleted
    deleted_files: FxHashSet<PathBuf>,
}

impl ChangeTracker {
    /// Create a new change tracker
    pub fn new() -> Self {
        Self::default()
    }

    /// Compute changes by comparing current files with build info
    pub fn compute_changes(
        &mut self,
        build_info: &BuildInfo,
        current_files: &[PathBuf],
    ) -> Result<()> {
        let current_set: FxHashSet<_> = current_files.iter().collect();

        // Find new files
        for file in current_files {
            let path_str = file.to_string_lossy();
            if !build_info.file_infos.contains_key(path_str.as_ref()) {
                self.new_files.insert(file.clone());
                self.affected_files.insert(file.clone());
            }
        }

        // Find deleted files
        for path_str in build_info.file_infos.keys() {
            let path = PathBuf::from(path_str);
            if !current_set.contains(&path) {
                self.deleted_files.insert(path);
            }
        }

        // Check for modified files
        for file in current_files {
            if self.new_files.contains(file) {
                continue;
            }

            let current_version = compute_file_version(file)?;
            let path_str = file.to_string_lossy();

            if build_info.has_file_changed(&path_str, &current_version) {
                self.changed_files.insert(file.clone());
                self.affected_files.insert(file.clone());
            }
        }

        // Add dependents of changed files
        let mut dependents_to_add = Vec::new();
        for changed in &self.changed_files {
            let path_str = changed.to_string_lossy();
            for dep in build_info.get_dependents(&path_str) {
                dependents_to_add.push(PathBuf::from(dep));
            }
        }

        // Also handle deleted file dependents
        for deleted in &self.deleted_files {
            let path_str = deleted.to_string_lossy();
            for dep in build_info.get_dependents(&path_str) {
                dependents_to_add.push(PathBuf::from(dep));
            }
        }

        for dep in dependents_to_add {
            if current_set.contains(&dep) {
                self.affected_files.insert(dep);
            }
        }

        Ok(())
    }

    /// Compute changes with absolute file paths
    /// Automatically normalizes paths relative to `base_dir` for comparison with `BuildInfo`
    pub fn compute_changes_with_base(
        &mut self,
        build_info: &BuildInfo,
        current_files: &[PathBuf],
        base_dir: &Path,
    ) -> Result<()> {
        // Normalize absolute paths to relative paths for BuildInfo comparison
        let current_files_relative: Vec<PathBuf> = current_files
            .iter()
            .filter_map(|path| {
                path.strip_prefix(base_dir)
                    .ok()
                    .map(std::path::Path::to_path_buf)
            })
            .collect();

        // Compute changes using relative paths, but store absolute paths in results
        let current_set: FxHashSet<_> = current_files_relative.iter().collect();

        // Find new files
        for (i, file_rel) in current_files_relative.iter().enumerate() {
            let path_str = file_rel.to_string_lossy();
            if !build_info.file_infos.contains_key(path_str.as_ref()) {
                let abs_path = &current_files[i];
                self.new_files.insert(abs_path.clone());
                self.affected_files.insert(abs_path.clone());
            }
        }

        // Find deleted files
        for path_str in build_info.file_infos.keys() {
            let path = PathBuf::from(path_str);
            if !current_set.contains(&path) {
                self.deleted_files.insert(path);
            }
        }

        // Check for modified files
        for (i, file_rel) in current_files_relative.iter().enumerate() {
            let abs_path = &current_files[i];
            if self.new_files.contains(abs_path) {
                continue;
            }

            let current_version = compute_file_version(abs_path)?;
            let path_str = file_rel.to_string_lossy();

            if build_info.has_file_changed(&path_str, &current_version) {
                self.changed_files.insert(abs_path.clone());
                self.affected_files.insert(abs_path.clone());
            }
        }

        Ok(())
    }

    /// Get files that have changed
    pub const fn changed_files(&self) -> &FxHashSet<PathBuf> {
        &self.changed_files
    }

    /// Get all files that need to be recompiled
    pub const fn affected_files(&self) -> &FxHashSet<PathBuf> {
        &self.affected_files
    }

    /// Get new files
    pub const fn new_files(&self) -> &FxHashSet<PathBuf> {
        &self.new_files
    }

    /// Get deleted files
    pub const fn deleted_files(&self) -> &FxHashSet<PathBuf> {
        &self.deleted_files
    }

    /// Check if any files have changed
    pub fn has_changes(&self) -> bool {
        !self.changed_files.is_empty()
            || !self.new_files.is_empty()
            || !self.deleted_files.is_empty()
    }

    /// Get total number of affected files
    pub fn affected_count(&self) -> usize {
        self.affected_files.len()
    }
}

/// Compute a version string for a file (content hash)
pub fn compute_file_version(path: &Path) -> Result<String> {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let content =
        std::fs::read(path).with_context(|| format!("failed to read file: {}", path.display()))?;

    let mut hasher = DefaultHasher::new();
    content.hash(&mut hasher);
    let hash = hasher.finish();

    Ok(format!("{hash:016x}"))
}

/// Compute a signature for a file's exports (for dependency tracking)
pub fn compute_export_signature(exports: &[String]) -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    for export in exports {
        export.hash(&mut hasher);
    }

    format!("{:016x}", hasher.finish())
}

/// Builder for creating build info incrementally
pub struct BuildInfoBuilder {
    build_info: BuildInfo,
    base_dir: PathBuf,
}

impl BuildInfoBuilder {
    /// Create a new builder
    pub fn new(base_dir: PathBuf) -> Self {
        Self {
            build_info: BuildInfo::new(),
            base_dir,
        }
    }

    /// Create a builder from existing build info
    pub const fn from_existing(build_info: BuildInfo, base_dir: PathBuf) -> Self {
        Self {
            build_info,
            base_dir,
        }
    }

    /// Set root files
    pub fn set_root_files(&mut self, files: Vec<String>) -> &mut Self {
        self.build_info.root_files = files;
        self
    }

    /// Add a file to the build info
    pub fn add_file(&mut self, path: &Path, exports: &[String]) -> Result<&mut Self> {
        let relative_path = self.relative_path(path);
        let version = compute_file_version(path)?;
        let signature = if exports.is_empty() {
            None
        } else {
            Some(compute_export_signature(exports))
        };

        self.build_info.set_file_info(
            &relative_path,
            FileInfo {
                version,
                signature,
                affected_files_pending_emit: false,
                implied_format: None,
            },
        );

        Ok(self)
    }

    /// Set dependencies for a file
    pub fn set_file_dependencies(&mut self, path: &Path, deps: Vec<PathBuf>) -> &mut Self {
        let relative_path = self.relative_path(path);
        let relative_deps: Vec<String> = deps.iter().map(|d| self.relative_path(d)).collect();

        self.build_info
            .set_dependencies(&relative_path, relative_deps);
        self
    }

    /// Set emit signature for a file
    pub fn set_file_emit(
        &mut self,
        path: &Path,
        js_hash: Option<&str>,
        dts_hash: Option<&str>,
    ) -> &mut Self {
        let relative_path = self.relative_path(path);
        self.build_info.set_emit_signature(
            &relative_path,
            EmitSignature {
                js: js_hash.map(String::from),
                dts: dts_hash.map(String::from),
                map: None,
            },
        );
        self
    }

    /// Set compiler options
    pub fn set_options(&mut self, options: BuildInfoOptions) -> &mut Self {
        self.build_info.options = options;
        self
    }

    /// Build the final build info
    pub fn build(mut self) -> BuildInfo {
        self.build_info.build_time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        self.build_info
    }

    /// Get a relative path from the base directory
    fn relative_path(&self, path: &Path) -> String {
        path.strip_prefix(&self.base_dir)
            .unwrap_or(path)
            .to_string_lossy()
            .replace('\\', "/")
    }
}

/// Determine the default .tsbuildinfo path based on configuration
pub fn default_build_info_path(config_path: &Path, out_dir: Option<&Path>) -> PathBuf {
    let config_name = config_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("tsconfig");

    let build_info_name = format!("{config_name}.tsbuildinfo");

    if let Some(out) = out_dir {
        out.join(&build_info_name)
    } else {
        config_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join(&build_info_name)
    }
}

#[cfg(test)]
#[path = "incremental_tests.rs"]
mod tests;