Repository: awslabs/llrt
File: llrt_core/src/vm.rs (Rust)

Code before:

    let (scope, name) = if name != "." && fs::metadata(&package_json_path).is_err() {
        package_json_path.truncate(base_path_length);
        package_json_path.push_str(specifier);
        package_json_path.push_str("/package.json");
        (specifier, ".")
    } else {
        (scope, name.as_str())
    };

    if fs::metadata(&package_json_path).is_err() {
        return Err(Exception::throw_reference(
            ctx,
            &["Error resolving module '", specifier, "'"].concat(),
        ));
    };

    let package_json = fs::read(&package_json_path).unwrap_or_default();
    let package_json = simd_json::to_owned_value(&mut package_json.clone()).or_throw(ctx)?;

    let module_path = json_as_str(&package_json, &["exports", name, "require", "default"])
        .or_else(|| json_as_str(&package_json, &["exports", name, "require"]))
        .or_else(|| json_as_str(&package_json, &["exports", "require", "default"]))
        .or_else(|| json_as_str(&package_json, &["exports", "default"]))
        .or_else(|| json_as_str(&package_json, &["main"]))
        .unwrap_or("./index.js");

    Ok([&current_dir, "/node_modules/", scope, "/", module_path].concat())
}

fn json_as_str<'a>(value: &'a OwnedValue, keys: &[&str]) -> Option<&'a str> {
    let mut current_value = Some(value);

    for &key in keys {
        current_value = current_value.and_then(|v| v.get(key));
    }

    current_value.and_then(|v| v.as_str())
}


Review comment (performance):
I wonder here if we can do this a bit more elegantly. We sacrifice a bit of readability for better performance as we don't check each key several times and iterate trough the object multiple times:
```rust
let package_json = simd_json::to_borrowed_value(&mut json).or_throw(ctx)?;
let module_path = get_module_path(&package_json, name)?;

...

fn get_module_path<'a>(package_json: &'a BorrowedValue<'a>, name: &str) -> Result<&'a str> {
    if let BorrowedValue::Object(map) = package_json {
        if let Some(BorrowedValue::Object(exports)) = map.get("exports") {
            // Check for nested structure: exports -> name
            if let Some(BorrowedValue::Object(name_obj)) = exports.get(name) {
                // Check for name -> require -> default
                if let Some(BorrowedValue::Object(require)) = name_obj.get("require") {
                    if let Some(BorrowedValue::String(default)) = require.get("default") {
                        return Ok(default.as_ref());
                    }
                }
                // Check for name -> default
                if let Some(BorrowedValue::String(default)) = name_obj.get("default") {
                    return Ok(default.as_ref());
                }
            }

            // Check for nested structure: exports -> require -> default
            if let Some(BorrowedValue::Object(require)) = exports.get("require") {
                if let Some(BorrowedValue::String(default)) = require.get("default") {
                    return Ok(default.as_ref());
                }
            }

            // Check for exports -> default
            if let Some(BorrowedValue::String(default)) = exports.get("default") {
                return Ok(default.as_ref());
            }
        }

        // Check for main field
        if let Some(BorrowedValue::String(main)) = map.get("main") {
            return Ok(main.as_ref());
        }
    }

    Ok("./index.js")
}
```

Also no need to clone the Vec we read from the package ison path, simply return a mutable reference to it.

Code after:
    let (scope, name) = if name != "." && !Path::new(&package_json_path).exists() {
        package_json_path.truncate(base_path_length);
        package_json_path.push_str(specifier);
        package_json_path.push_str("/package.json");
        (specifier, ".")
    } else {
        (scope, name.as_str())
    };

    if !Path::new(&package_json_path).exists() {
        return Err(Exception::throw_reference(
            ctx,
            &["Error resolving module '", specifier, "'"].concat(),
        ));
    };

    let mut package_json = fs::read(&package_json_path).unwrap_or_default();
    let package_json = simd_json::to_borrowed_value(&mut package_json).or_throw(ctx)?;

    let module_path = get_module_path(&package_json, name)?;

    Ok([&current_dir, "/node_modules/", scope, "/", module_path].concat())
}

fn get_module_path<'a>(package_json: &'a BorrowedValue<'a>, module_name: &str) -> Result<&'a str> {
    if let BorrowedValue::Object(map) = package_json {
        if let Some(BorrowedValue::Object(exports)) = map.get("exports") {
            if let Some(BorrowedValue::Object(name)) = exports.get(module_name) {
                if let Some(BorrowedValue::Object(require)) = name.get("require") {
                    // Check for exports -> name -> require -> default
                    if let Some(BorrowedValue::String(default)) = require.get("default") {
                        return Ok(default.as_ref());
                    }
                }
                // Check for exports -> name -> require
                if let Some(BorrowedValue::String(require)) = name.get("require") {
                    return Ok(require.as_ref());
                }
            }

            if let Some(BorrowedValue::Object(require)) = exports.get("require") {
                // Check for exports -> require -> default
                if let Some(BorrowedValue::String(default)) = require.get("default") {
                    return Ok(default.as_ref());
                }
            }

            // Check for exports -> default
            if let Some(BorrowedValue::String(default)) = exports.get("default") {
                return Ok(default.as_ref());
            }