Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 44 additions & 18 deletions crates/perry/src/commands/compile/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ pub fn find_perry_workspace_root() -> Option<PathBuf> {
#[cfg(test)]
mod bun_store_tests;
#[cfg(test)]
mod extension_resolution_tests;
#[cfg(test)]
mod tests;

/// Packages that Perry provides built-in native extensions for.
Expand Down Expand Up @@ -410,28 +412,50 @@ pub(super) fn parse_package_specifier(specifier: &str) -> (String, Option<String
(specifier.to_string(), None)
}

/// TypeScript *source* counterparts for an explicit JS module extension, in
/// preference order. Node resolves an explicit `.cjs`/`.mjs` specifier to that
/// exact file, and its only TypeScript source form is `.cts`/`.mts`
/// respectively — never a bare `.ts`. Blanket-mapping every JS extension to
/// `.ts`/`.tsx`/`.mts` made `require("./x.cjs")` prefer a co-located `x.ts`
/// (e.g. a `.ts` entry requiring a same-basename `.cjs` webpack bundle), so the
/// CJS module was never compiled and its exports read back `undefined` (#6535).
/// `.js`/`.jsx` keep the broader preference Perry uses to compile a co-located
/// `.ts` source in place of a stale `.js` build artifact. Non-JS extensions
/// return an empty slice (no TS redirect).
fn ts_source_counterparts(js_ext: &str) -> &'static [&'static str] {
match js_ext {
"js" | "jsx" => &[".ts", ".tsx", ".mts"],
"mjs" => &[".mts"],
"cjs" => &[".cts"],
_ => &[],
}
}

/// Try to resolve a path with common extensions
/// Prefers TypeScript source files over JavaScript for native compilation
pub(super) fn resolve_with_extensions(base: &Path) -> Option<PathBuf> {
// TypeScript extensions to try (in order of preference)
let ts_extensions = [".ts", ".tsx", ".mts"];
// JavaScript extensions (fallback)
let _js_extensions = [".js", ".mjs", ".cjs"];
// All extensions in order of preference
let all_extensions = [".ts", ".tsx", ".mts", ".js", ".mjs", ".cjs", ".json"];

// Check if the path has an explicit JS extension - if so, try TS equivalents first
// All extensions in order of preference (TypeScript sources first, then
// their JS counterparts, then data). `.cts` sits with the other TS
// extensions so a bare specifier resolves to a `.cts` source directly,
// consistent with `.mts`/`.ts` — not only via the `.cjs` counterpart fallback.
let all_extensions = [
".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json",
];

// Check if the path has an explicit JS extension - if so, try its TS source
// counterpart(s) first (`.cjs`→`.cts`, `.mjs`→`.mts`, `.js`→`.ts`/`.tsx`).
if let Some(ext) = base.extension().and_then(|e| e.to_str()) {
if matches!(ext, "js" | "mjs" | "cjs") {
// Strip the JS extension and try TS extensions first
let counterparts = ts_source_counterparts(ext);
if !counterparts.is_empty() {
// Strip the JS extension and try the TS counterpart(s) first
let stem = base.with_extension("");
for ts_ext in ts_extensions {
for ts_ext in counterparts {
let ts_path = stem.with_extension(ts_ext.trim_start_matches('.'));
if ts_path.exists() && ts_path.is_file() {
return Some(ts_path);
}
}
// If no TS file found, fall back to the original JS file
// If no TS source found, fall back to the original JS file
if base.exists() && base.is_file() {
return Some(base.to_path_buf());
}
Expand All @@ -440,11 +464,12 @@ pub(super) fn resolve_with_extensions(base: &Path) -> Option<PathBuf> {

// If it already exists as-is (and not a JS file that we already handled above)
if base.exists() && base.is_file() {
// Even if it exists, check for TS version first
// Even if it exists, check for a TS source counterpart first
if let Some(ext) = base.extension().and_then(|e| e.to_str()) {
if matches!(ext, "js" | "mjs" | "cjs") {
let counterparts = ts_source_counterparts(ext);
if !counterparts.is_empty() {
let stem = base.with_extension("");
for ts_ext in ts_extensions {
for ts_ext in counterparts {
let ts_path = stem.with_extension(ts_ext.trim_start_matches('.'));
if ts_path.exists() && ts_path.is_file() {
return Some(ts_path);
Expand Down Expand Up @@ -486,9 +511,10 @@ pub(super) fn resolve_with_extensions(base: &Path) -> Option<PathBuf> {
// APPEND: `./stream-ops.web` + `.js` -> `./stream-ops.web.js`.
let appended = PathBuf::from(format!("{}{}", path_str, ext));
if appended.exists() && appended.is_file() {
// If we landed on a JS file, prefer a co-located TS source.
if matches!(ext, ".js" | ".mjs" | ".cjs") {
for ts_ext in ts_extensions {
// If we landed on a JS file, prefer its co-located TS source.
let counterparts = ts_source_counterparts(ext.trim_start_matches('.'));
if !counterparts.is_empty() {
for ts_ext in counterparts {
let ts_path = PathBuf::from(format!("{}{}", path_str, ts_ext));
if ts_path.exists() && ts_path.is_file() {
return Some(ts_path);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! #6535: extension resolution must map an explicit JS module extension to its
//! OWN TypeScript source form (`.cjs`→`.cts`, `.mjs`→`.mts`, `.js`→`.ts`) — not
//! blanket-redirect every JS extension to a bare `.ts`. The blanket form made
//! `require("./x.cjs")` beside a same-basename `x.ts` entry resolve to that
//! `.ts` (the requiring module itself), so the CJS module was never compiled and
//! its exports read back `undefined`.

use super::{resolve_with_extensions, ts_source_counterparts};

#[test]
fn explicit_cjs_beside_same_basename_ts_resolves_to_cjs() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
std::fs::write(root.join("mod.cjs"), "module.exports = {};\n").unwrap();
std::fs::write(root.join("mod.ts"), "export const x = 1;\n").unwrap();

// The `.cjs`'s TS counterpart is `.cts` (absent here), so the actual
// `.cjs` wins — the bare `.ts` sibling must NOT shadow it.
let resolved = resolve_with_extensions(&root.join("mod.cjs")).expect("resolve");
assert_eq!(resolved, root.join("mod.cjs"));
}

#[test]
fn explicit_cjs_prefers_cts_source_when_present() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
std::fs::write(root.join("mod.cjs"), "module.exports = {};\n").unwrap();
std::fs::write(root.join("mod.cts"), "export const x = 1;\n").unwrap();
// A same-basename `.ts` must not win over the real `.cts` counterpart.
std::fs::write(root.join("mod.ts"), "export const x = 2;\n").unwrap();

let resolved = resolve_with_extensions(&root.join("mod.cjs")).expect("resolve");
assert_eq!(resolved, root.join("mod.cts"));
}

#[test]
fn explicit_mjs_beside_same_basename_ts_resolves_to_mjs() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
std::fs::write(root.join("mod.mjs"), "export default 1;\n").unwrap();
std::fs::write(root.join("mod.ts"), "export const x = 1;\n").unwrap();

let resolved = resolve_with_extensions(&root.join("mod.mjs")).expect("resolve");
assert_eq!(resolved, root.join("mod.mjs"));
}

#[test]
fn explicit_js_still_prefers_ts_source() {
// The load-bearing `.js`→`.ts` preference is unchanged: an explicit
// `.js` specifier still compiles a co-located `.ts` source over a
// (possibly stale) `.js` artifact.
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
std::fs::write(root.join("mod.js"), "export const x = 1;\n").unwrap();
std::fs::write(root.join("mod.ts"), "export const x = 2;\n").unwrap();

let resolved = resolve_with_extensions(&root.join("mod.js")).expect("resolve");
assert_eq!(resolved, root.join("mod.ts"));
}

#[test]
fn bare_specifier_resolves_to_cts_source() {
// A bare (extensionless) specifier must reach a `.cts` source directly,
// consistent with `.mts`/`.ts` — `.cts` is in `all_extensions`.
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
std::fs::write(root.join("mod.cts"), "export const x = 1;\n").unwrap();

let resolved = resolve_with_extensions(&root.join("mod")).expect("resolve");
assert_eq!(resolved, root.join("mod.cts"));
}

#[test]
fn ts_source_counterparts_map_each_js_extension_to_its_own_source() {
assert_eq!(ts_source_counterparts("cjs").to_vec(), vec![".cts"]);
assert_eq!(ts_source_counterparts("mjs").to_vec(), vec![".mts"]);
assert_eq!(
ts_source_counterparts("js").to_vec(),
vec![".ts", ".tsx", ".mts"]
);
assert_eq!(
ts_source_counterparts("jsx").to_vec(),
vec![".ts", ".tsx", ".mts"]
);
assert!(ts_source_counterparts("ts").is_empty());
assert!(ts_source_counterparts("json").is_empty());
}
Loading