fallow-core 3.45.0

Internal detector backend for fallow-engine and fallow-api
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
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Hash of the non-source files and workspace facts that import resolution
//! reads, for the graph-cache mode.
//!
//! The graph-cache manifest fingerprints discovered source files only. The
//! resolver also reads `package.json` (`imports`, `exports`, `name`), Deno
//! configs (`name`, `exports`, import maps) and every `tsconfig.json` that
//! `oxc_resolver` discovers next to a source file, plus its `extends` and
//! `references` chain. An edit to one of these files changes import targets
//! without a change to any source file, so the mode must cover them.
//!
//! The resolver also reads `node_modules`, so an install changes import
//! targets too. A walk of `node_modules` costs too much, so the hash reads the
//! lockfile and the install marker that the package manager writes on each
//! install. Bun writes no install marker, so for a Bun project the hash reads
//! the package names at the top level of `node_modules`. Deno writes no
//! install marker either, so the hash reads the entry names of the Deno
//! store in `node_modules/.deno`. The graph cache payload keys the versions of
//! hoisted Bun packages (see `fallow_graph::installed_versions`).

use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use fallow_config::WorkspaceInfo;
use fallow_types::discover::DiscoveredFile;
use rustc_hash::{FxHashSet, FxHasher};

/// Manifests that the resolver loads from the project root and from each
/// workspace root (package maps, Deno names, exports and import maps).
const PACKAGE_MANIFESTS: &[&str] = &["package.json", "deno.json", "deno.jsonc"];

/// Files that `oxc_resolver` looks up in every ancestor directory of an
/// importing file: the nearest `package.json` (for `imports`) and the nearest
/// owning `tsconfig.json` (automatic tsconfig discovery).
const NEAREST_CONFIGS: &[&str] = &["package.json", "tsconfig.json"];

/// Lockfiles and install markers that change when a package manager adds,
/// removes or updates a package in `node_modules`. Each path is relative to
/// the project root or to a workspace root.
///
/// The hash reads the content of each file, not the modification time. A
/// fresh install in CI writes the same content with a new time, so a time
/// would make each restored cache miss. `node_modules/.modules.yaml` of pnpm
/// holds an install timestamp, so the hash reads the copy of the lockfile in
/// `node_modules/.pnpm/lock.yaml` instead.
///
/// Yarn Plug'n'Play writes `.pnp.cjs` and `.pnp.data.json` in place of
/// `node_modules`. The resolver turns on PnP resolution when it finds
/// `.pnp.cjs` at the root or above it. A switch of the Yarn linker can keep
/// `yarn.lock` the same, so the hash reads these files too.
const INSTALL_STATE_FILES: &[&str] = &[
    "package-lock.json",
    "npm-shrinkwrap.json",
    "pnpm-lock.yaml",
    "yarn.lock",
    "bun.lock",
    "bun.lockb",
    "deno.lock",
    "node_modules/.package-lock.json",
    "node_modules/.pnpm/lock.yaml",
    "node_modules/.yarn-state.yml",
    "node_modules/.yarn-integrity",
    ".pnp.cjs",
    ".pnp.data.json",
];

/// Lockfiles of Bun. Bun writes no install marker in `node_modules`, so a
/// directory with one of these files keys the package names in its
/// `node_modules` (see [`bun_install_listings`]).
const BUN_LOCKFILES: &[&str] = &["bun.lock", "bun.lockb"];

/// The directory in `node_modules` where the isolated linker of Bun puts one
/// `<name>@<version>` directory for each installed package.
const BUN_STORE_DIR: &str = ".bun";

/// The directory in `node_modules` where Deno, with a `nodeModulesDir`
/// setting, puts one `<name>@<version>` directory for each installed npm
/// package. The top-level entries of `node_modules` are links into it.
const DENO_STORE_DIR: &str = ".deno";

/// Hash the workspace `(name, root)` pairs and the content of every resolver
/// input file. Every path is spelled relative to `root`, so a copy of the
/// project under another absolute path hashes the same.
pub fn resolution_inputs_hash(
    root: &Path,
    workspaces: &[WorkspaceInfo],
    files: &[DiscoveredFile],
) -> u64 {
    let mut hasher = FxHasher::default();

    let mut workspace_keys: Vec<(&str, String)> = workspaces
        .iter()
        .map(|ws| (ws.name.as_str(), portable_key(root, &ws.root)))
        .collect();
    workspace_keys.sort_unstable();
    workspace_keys.len().hash(&mut hasher);
    for key in &workspace_keys {
        key.hash(&mut hasher);
    }

    let mut inputs: Vec<(String, Vec<u8>)> = collect_input_files(root, workspaces, files)
        .into_iter()
        .filter_map(|path| {
            let content = std::fs::read(&path).ok()?;
            Some((portable_key(root, &path), content))
        })
        .collect();
    inputs.sort_unstable();
    inputs.len().hash(&mut hasher);
    for (key, content) in &inputs {
        key.hash(&mut hasher);
        content.hash(&mut hasher);
    }

    let mut entry_targets = package_entry_target_states(root, workspaces);
    entry_targets.sort_unstable();
    entry_targets.len().hash(&mut hasher);
    for target in &entry_targets {
        target.hash(&mut hasher);
    }

    let mut install_states = node_modules_states(root, workspaces);
    install_states.sort_unstable();
    install_states.len().hash(&mut hasher);
    for state in &install_states {
        state.hash(&mut hasher);
    }

    let mut bun_listings = bun_install_listings(root, workspaces);
    bun_listings.sort_unstable();
    bun_listings.len().hash(&mut hasher);
    for listing in &bun_listings {
        listing.hash(&mut hasher);
    }

    let mut deno_listings = deno_store_listings(root, workspaces);
    deno_listings.sort_unstable();
    deno_listings.len().hash(&mut hasher);
    for listing in &deno_listings {
        listing.hash(&mut hasher);
    }

    hasher.finish()
}

/// Return `(path, exists)` for the `node_modules` directory of the project
/// root and of each workspace root.
///
/// The resolver reports a bare import with a query string as unresolved
/// only when the package is installed, so an install changes the result
/// without an edit to a source file or a manifest. Only the existence keys the
/// mode: a modification time changes on every fresh install in CI and would
/// make each restored cache miss. The lockfiles and install markers in
/// [`INSTALL_STATE_FILES`] key an install into an existing `node_modules`.
fn node_modules_states(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, bool)> {
    std::iter::once(root)
        .chain(workspaces.iter().map(|ws| ws.root.as_path()))
        .map(|dir| {
            let path = dir.join("node_modules");
            (portable_key(root, &path), path.is_dir())
        })
        .collect()
}

/// Return `(path, package names)` for the `node_modules` directory next to
/// each Bun lockfile at the project root, at a workspace root, or above the
/// root.
///
/// A Bun install into an existing `node_modules` does not change the lockfile
/// when the lockfile already lists the package, for example after a pull of a
/// lockfile change. The names are the top-level entries, the entries of each
/// `@scope` directory, and the `<name>@<version>` entries of the isolated
/// store. The list does not read file content or a modification time, so a
/// fresh install of the same packages keeps the hash. Other dot entries are
/// tool caches such as `.cache`, so the list skips them.
fn bun_install_listings(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, Vec<String>)> {
    let dirs: FxHashSet<&Path> = std::iter::once(root)
        .chain(workspaces.iter().map(|ws| ws.root.as_path()))
        .chain(root.ancestors().skip(1))
        .collect();
    dirs.into_iter()
        .filter(|dir| BUN_LOCKFILES.iter().any(|name| dir.join(name).is_file()))
        .filter_map(|dir| {
            let node_modules = dir.join("node_modules");
            let names = node_modules_package_names(&node_modules)?;
            Some((portable_key(root, &node_modules), names))
        })
        .collect()
}

/// Return `(path, entry names)` for each Deno store `node_modules/.deno` at
/// the project root, at a workspace root, or above the root.
///
/// A Deno install into an existing `node_modules` does not change
/// `deno.lock` when the lockfile already lists the package. Each store entry
/// name holds the package name and version, so the names key an install, a
/// removal and a version change. Dot entries are Deno state files, such as
/// `.deno.lock` and `.setup-cache.bin`, so the list skips them.
fn deno_store_listings(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, Vec<String>)> {
    let dirs: FxHashSet<&Path> = std::iter::once(root)
        .chain(workspaces.iter().map(|ws| ws.root.as_path()))
        .chain(root.ancestors().skip(1))
        .collect();
    dirs.into_iter()
        .filter_map(|dir| {
            let store = dir.join("node_modules").join(DENO_STORE_DIR);
            let mut names: Vec<String> = dir_entry_names(&store)?
                .into_iter()
                .filter(|name| !name.starts_with('.'))
                .collect();
            names.sort_unstable();
            Some((portable_key(root, &store), names))
        })
        .collect()
}

fn node_modules_package_names(node_modules: &Path) -> Option<Vec<String>> {
    let mut names = Vec::new();
    for name in dir_entry_names(node_modules)? {
        let nested = name.starts_with('@') || name == BUN_STORE_DIR;
        if nested {
            for child in dir_entry_names(&node_modules.join(&name)).unwrap_or_default() {
                names.push(format!("{name}/{child}"));
            }
        } else if !name.starts_with('.') {
            names.push(name);
        }
    }
    names.sort_unstable();
    Some(names)
}

fn dir_entry_names(dir: &Path) -> Option<Vec<String>> {
    let entries = std::fs::read_dir(dir).ok()?;
    Some(
        entries
            .flatten()
            .map(|entry| entry.file_name().to_string_lossy().into_owned())
            .collect(),
    )
}

/// `package.json` fields whose paths the resolver follows for a package
/// import. `exports` is read separately because it nests.
const PACKAGE_ENTRY_FIELDS: &[&str] = &["main", "module", "types", "typings"];

/// Return `(path, exists)` for every static entry path that the project and
/// workspace `package.json` files name.
///
/// The resolver follows an entry that exists on disk (often build output that
/// discovery ignores) and maps an entry that is absent back to source. A build
/// that creates or removes the output changes the import target without an
/// edit to a source file or a manifest, so the existence of each entry keys
/// the mode too.
fn package_entry_target_states(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, bool)> {
    let mut states = Vec::new();
    let package_dirs = std::iter::once(root).chain(workspaces.iter().map(|ws| ws.root.as_path()));
    for dir in package_dirs {
        let Ok(content) = std::fs::read(dir.join("package.json")) else {
            continue;
        };
        let Ok(manifest) = serde_json::from_slice::<serde_json::Value>(&content) else {
            continue;
        };
        let mut targets = Vec::new();
        for field in PACKAGE_ENTRY_FIELDS {
            if let Some(serde_json::Value::String(target)) = manifest.get(*field) {
                targets.push(target.as_str());
            }
        }
        if let Some(exports) = manifest.get("exports") {
            collect_export_targets(exports, &mut targets);
        }
        for target in targets {
            if target.contains('*') {
                continue;
            }
            let relative = target.strip_prefix("./").unwrap_or(target);
            if relative.is_empty() || relative.starts_with('/') {
                continue;
            }
            let path = dir.join(relative);
            states.push((portable_key(root, &path), path.exists()));
        }
    }
    states
}

fn collect_export_targets<'a>(value: &'a serde_json::Value, targets: &mut Vec<&'a str>) {
    match value {
        serde_json::Value::String(target) => targets.push(target),
        serde_json::Value::Array(items) => {
            for item in items {
                collect_export_targets(item, targets);
            }
        }
        serde_json::Value::Object(map) => {
            for item in map.values() {
                collect_export_targets(item, targets);
            }
        }
        _ => {}
    }
}

fn collect_input_files(
    root: &Path,
    workspaces: &[WorkspaceInfo],
    files: &[DiscoveredFile],
) -> FxHashSet<PathBuf> {
    let mut inputs = FxHashSet::default();
    let manifest_dirs = std::iter::once(root).chain(workspaces.iter().map(|ws| ws.root.as_path()));
    for dir in manifest_dirs {
        for name in PACKAGE_MANIFESTS.iter().chain(INSTALL_STATE_FILES) {
            insert_if_file(&mut inputs, dir.join(name));
        }
        // The output-path fallback reads every root-level `tsconfig*.json`.
        for config in root_level_tsconfigs(dir) {
            inputs.insert(config);
        }
    }

    // The resolver also reads `node_modules` above the root, for example in a
    // monorepo where the project root is one package of the repository.
    for dir in root.ancestors().skip(1) {
        for name in INSTALL_STATE_FILES {
            insert_if_file(&mut inputs, dir.join(name));
        }
    }

    for dir in source_dirs_and_ancestors(root, files) {
        for name in NEAREST_CONFIGS {
            insert_if_file(&mut inputs, dir.join(name));
        }
    }

    let tsconfigs: Vec<PathBuf> = inputs
        .iter()
        .filter(|path| is_tsconfig_name(path))
        .cloned()
        .collect();
    for config in tsconfigs {
        inputs.extend(fallow_config::tsconfig_linked_files(&config));
    }
    inputs
}

fn insert_if_file(inputs: &mut FxHashSet<PathBuf>, path: PathBuf) {
    if path.is_file() {
        inputs.insert(path);
    }
}

/// Every directory that holds a source file, each ancestor of it up to the
/// project root, and each ancestor of the project root itself. Automatic
/// tsconfig discovery and nearest-`package.json` lookup walk the same chain.
fn source_dirs_and_ancestors(root: &Path, files: &[DiscoveredFile]) -> FxHashSet<PathBuf> {
    let mut dirs: FxHashSet<PathBuf> = root.ancestors().map(Path::to_path_buf).collect();
    for file in files {
        let mut dir = file.path.parent();
        while let Some(current) = dir {
            if !current.starts_with(root) || !dirs.insert(current.to_path_buf()) {
                break;
            }
            dir = current.parent();
        }
    }
    dirs
}

fn root_level_tsconfigs(dir: &Path) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| is_tsconfig_name(path) && path.is_file())
        .collect()
}

fn is_tsconfig_name(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.starts_with("tsconfig"))
        && path.extension().is_some_and(|extension| {
            extension.eq_ignore_ascii_case("json") || extension.eq_ignore_ascii_case("jsonc")
        })
}

/// Spell `path` relative to `root`, with `../` steps for a path outside the
/// root (an ancestor `tsconfig.json`, an `extends` target in a parent repo).
fn portable_key(root: &Path, path: &Path) -> String {
    for (depth, base) in root.ancestors().enumerate() {
        if let Ok(rest) = path.strip_prefix(base) {
            let mut key = "../".repeat(depth);
            key.push_str(&rest.to_string_lossy().replace('\\', "/"));
            return key;
        }
    }
    path.to_string_lossy().replace('\\', "/")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn portable_key_spells_inside_and_outside_paths_relative_to_root() {
        let root = Path::new("/repo/app");
        assert_eq!(
            portable_key(root, Path::new("/repo/app/src/a.json")),
            "src/a.json"
        );
        assert_eq!(
            portable_key(root, Path::new("/repo/tsconfig.json")),
            "../tsconfig.json"
        );
        assert_eq!(portable_key(root, Path::new("/repo/app")), "");
    }

    fn write(path: &Path, content: &str) {
        std::fs::create_dir_all(path.parent().expect("parent")).expect("directory");
        std::fs::write(path, content).expect("file");
    }

    #[test]
    fn install_markers_of_root_and_workspaces_key_the_hash() {
        let temp = tempfile::tempdir().expect("temp");
        let root = temp.path().join("repo");
        let workspace_root = root.join("packages/ui");
        let workspaces = vec![WorkspaceInfo {
            root: workspace_root.clone(),
            name: "ui".to_string(),
            is_internal_dependency: false,
        }];
        let root_marker = root.join("node_modules/.package-lock.json");
        let workspace_marker = workspace_root.join("node_modules/.yarn-state.yml");
        write(&root_marker, "a@1\n");
        write(&workspace_marker, "b@1\n");
        let initial = resolution_inputs_hash(&root, &workspaces, &[]);

        write(&root_marker, "a@1\n");
        assert_eq!(
            resolution_inputs_hash(&root, &workspaces, &[]),
            initial,
            "a rewrite with the same content must keep the hash"
        );

        write(&root_marker, "a@2\n");
        let root_changed = resolution_inputs_hash(&root, &workspaces, &[]);
        assert_ne!(root_changed, initial);

        write(&workspace_marker, "b@2\n");
        assert_ne!(
            resolution_inputs_hash(&root, &workspaces, &[]),
            root_changed
        );
    }

    #[test]
    fn bun_install_with_the_same_lockfile_keys_the_hash() {
        let temp = tempfile::tempdir().expect("temp");
        let root = temp.path().join("repo");
        write(&root.join("bun.lock"), "{}\n");
        write(&root.join("node_modules/a/package.json"), "{}");
        write(&root.join("node_modules/.cache/tool/data"), "1");
        let initial = resolution_inputs_hash(&root, &[], &[]);

        write(&root.join("node_modules/.cache/tool/other"), "2");
        assert_eq!(
            resolution_inputs_hash(&root, &[], &[]),
            initial,
            "a tool cache in node_modules must keep the hash"
        );

        write(&root.join("node_modules/@scope/b/package.json"), "{}");
        let scoped = resolution_inputs_hash(&root, &[], &[]);
        assert_ne!(scoped, initial, "a scoped package install must change it");

        write(&root.join("node_modules/.bun/c@1.0.0/node_modules/c/x"), "");
        assert_ne!(
            resolution_inputs_hash(&root, &[], &[]),
            scoped,
            "a package in the isolated store must change it"
        );
    }

    #[test]
    fn deno_lockfile_of_root_workspace_and_parent_keys_the_hash() {
        let temp = tempfile::tempdir().expect("temp");
        let root = temp.path().join("repo/app");
        let workspace_root = root.join("packages/ui");
        let workspaces = vec![WorkspaceInfo {
            root: workspace_root.clone(),
            name: "ui".to_string(),
            is_internal_dependency: false,
        }];
        let lockfiles = [
            root.join("deno.lock"),
            workspace_root.join("deno.lock"),
            temp.path().join("repo/deno.lock"),
        ];
        for lockfile in &lockfiles {
            write(lockfile, r#"{"version":"5"}"#);
        }
        let mut previous = resolution_inputs_hash(&root, &workspaces, &[]);
        for lockfile in &lockfiles {
            write(lockfile, r#"{"version":"5","npm":{"ms@2.1.3":{}}}"#);
            let next = resolution_inputs_hash(&root, &workspaces, &[]);
            assert_ne!(next, previous, "{} must key the hash", lockfile.display());
            previous = next;
        }
    }

    #[test]
    fn deno_store_entries_key_the_hash() {
        let temp = tempfile::tempdir().expect("temp");
        let root = temp.path().join("repo");
        let store = root.join("node_modules/.deno");
        write(&store.join("ms@2.1.3/node_modules/ms/package.json"), "{}");
        write(&store.join(".deno.lock"), "");
        let initial = resolution_inputs_hash(&root, &[], &[]);

        write(&store.join(".setup-cache.bin"), "state");
        assert_eq!(
            resolution_inputs_hash(&root, &[], &[]),
            initial,
            "a Deno state file in the store must keep the hash"
        );

        std::fs::rename(store.join("ms@2.1.3"), store.join("ms@2.1.2")).expect("rename");
        let downgraded = resolution_inputs_hash(&root, &[], &[]);
        assert_ne!(downgraded, initial, "a version change must change it");

        write(
            &store.join("chalk@5.6.2/node_modules/chalk/package.json"),
            "{}",
        );
        assert_ne!(
            resolution_inputs_hash(&root, &[], &[]),
            downgraded,
            "a new package in the store must change it"
        );
    }

    #[test]
    fn lockfile_above_the_root_keys_the_hash() {
        let temp = tempfile::tempdir().expect("temp");
        let root = temp.path().join("repo/packages/app");
        std::fs::create_dir_all(&root).expect("root");
        let lockfile = temp.path().join("repo/pnpm-lock.yaml");
        write(&lockfile, "a: 1\n");
        let initial = resolution_inputs_hash(&root, &[], &[]);
        write(&lockfile, "a: 2\n");
        assert_ne!(resolution_inputs_hash(&root, &[], &[]), initial);
    }

    #[test]
    fn yarn_pnp_manifest_keys_the_hash() {
        let temp = tempfile::tempdir().expect("temp");
        let root = temp.path().join("repo/packages/app");
        std::fs::create_dir_all(&root).expect("root");
        let initial = resolution_inputs_hash(&root, &[], &[]);

        let manifest = temp.path().join("repo/.pnp.cjs");
        write(&manifest, "// pnp v1\n");
        let with_pnp = resolution_inputs_hash(&root, &[], &[]);
        assert_ne!(
            with_pnp, initial,
            "a new PnP manifest above the root must change it"
        );

        write(&root.join(".pnp.data.json"), "{}");
        assert_ne!(
            resolution_inputs_hash(&root, &[], &[]),
            with_pnp,
            "a PnP data file at the root must change it"
        );
    }

    #[test]
    fn tsconfig_names_match_root_level_variants_only() {
        assert!(is_tsconfig_name(Path::new("tsconfig.json")));
        assert!(is_tsconfig_name(Path::new("tsconfig.app.jsonc")));
        assert!(!is_tsconfig_name(Path::new("package.json")));
        assert!(!is_tsconfig_name(Path::new("tsconfig.ts")));
    }
}