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
4 changes: 2 additions & 2 deletions apps/test-app/babel.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
presets: ['module:@react-native/babel-preset'],
// plugins: [['module:react-native-node-api-modules/babel-plugin', { naming: "hash" }]],
plugins: [['module:react-native-node-api-modules/babel-plugin', { naming: "package-name" }]],
// plugins: [['module:react-native-node-api-modules/babel-plugin', { stripPathSuffix: true }]],
plugins: ['module:react-native-node-api-modules/babel-plugin'],
};
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,17 @@ CxxNodeApiHostModule::requireNodeAddon(jsi::Runtime &rt,
return jsi::Value::undefined();
}

jsi::Value CxxNodeApiHostModule::requireNodeAddon(jsi::Runtime &rt,
const jsi::String path) {
const std::string pathStr = path.utf8(rt);
jsi::Value
CxxNodeApiHostModule::requireNodeAddon(jsi::Runtime &rt,
const jsi::String libraryName) {
const std::string libraryNameStr = libraryName.utf8(rt);
Copy link

Copilot AI May 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Update inline comments in the native code to reference 'libraryName' consistently, improving clarity for future maintainers.

Copilot uses AI. Check for mistakes.

auto [it, inserted] = nodeAddons_.emplace(pathStr, NodeAddon());
auto [it, inserted] = nodeAddons_.emplace(libraryNameStr, NodeAddon());
NodeAddon &addon = it->second;

// Check if this module has been loaded already, if not then load it...
if (inserted) {
if (!loadNodeAddon(addon, pathStr)) {
if (!loadNodeAddon(addon, libraryNameStr)) {
return jsi::Value::undefined();
}
}
Expand All @@ -47,10 +48,19 @@ jsi::Value CxxNodeApiHostModule::requireNodeAddon(jsi::Runtime &rt,
}

bool CxxNodeApiHostModule::loadNodeAddon(NodeAddon &addon,
const std::string &path) const {
const std::string &libraryName) const {
#if defined(__APPLE__)
std::string libraryPath =
"@rpath/" + libraryName + ".framework/" + libraryName;
#elif defined(__ANDROID__)
std::string libraryPath = libraryName
#else
abort()
#endif

typename LoaderPolicy::Symbol initFn = NULL;
typename LoaderPolicy::Module library =
LoaderPolicy::loadLibrary(path.c_str());
LoaderPolicy::loadLibrary(libraryPath.c_str());
if (NULL != library) {
addon.moduleHandle = library;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ require_relative "./scripts/patch-hermes"

NODE_PATH ||= `which node`.strip
CLI_COMMAND ||= "'#{NODE_PATH}' '#{File.join(__dir__, "dist/node/cli/run.js")}'"
COPY_FRAMEWORKS_COMMAND ||= "#{CLI_COMMAND} copy-xcframeworks '#{Pod::Config.instance.installation_root}'"
STRIP_PATH_SUFFIX ||= ENV['NODE_API_MODULES_STRIP_PATH_SUFFIX'] === "true"
COPY_FRAMEWORKS_COMMAND ||= "#{CLI_COMMAND} xcframeworks copy --podfile '#{Pod::Config.instance.installation_root}' #{STRIP_PATH_SUFFIX ? '--strip-path-suffix' : ''}"

# We need to run this now to ensure the xcframeworks are copied vendored_frameworks are considered
XCFRAMEWORKS_DIR ||= File.join(__dir__, "xcframeworks")
unless defined?(@xcframeworks_copied)
puts "Executing #{COPY_FRAMEWORKS_COMMAND}"
system(COPY_FRAMEWORKS_COMMAND) or raise "Failed to copy xcframeworks"
# Setting a flag to avoid running this command on every require
@xcframeworks_copied = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { transformFileSync } from "@babel/core";

import { plugin } from "./plugin.js";
import { setupTempDirectory } from "../test-utils.js";
import { getLibraryInstallName } from "../path-utils.js";
import { getLibraryName } from "../path-utils.js";

describe("plugin", () => {
it("transforms require calls, regardless", (context) => {
Expand Down Expand Up @@ -38,19 +38,19 @@ describe("plugin", () => {
`,
});

const ADDON_1_REQUIRE_ARG = getLibraryInstallName(
const ADDON_1_REQUIRE_ARG = getLibraryName(
path.join(tempDirectoryPath, "addon-1"),
"hash"
{ stripPathSuffix: false }
);
const ADDON_2_REQUIRE_ARG = getLibraryInstallName(
const ADDON_2_REQUIRE_ARG = getLibraryName(
path.join(tempDirectoryPath, "addon-2"),
"hash"
{ stripPathSuffix: false }
);

{
const result = transformFileSync(
path.join(tempDirectoryPath, "./addon-1.js"),
{ plugins: [[plugin, { naming: "hash" }]] }
{ plugins: [[plugin, { stripPathSuffix: false }]] }
);
assert(result);
const { code } = result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,22 @@ import type { PluginObj, NodePath } from "@babel/core";
import * as t from "@babel/types";

import {
getLibraryInstallName,
getLibraryName,
isNodeApiModule,
replaceWithNodeExtension,
NamingStrategy,
NAMING_STATEGIES,
} from "../path-utils";

type PluginOptions = {
naming?: NamingStrategy;
stripPathSuffix?: boolean;
};

function assertOptions(opts: unknown): asserts opts is PluginOptions {
assert(typeof opts === "object" && opts !== null, "Expected an object");
if ("naming" in opts) {
assert(typeof opts.naming === "string", "Expected 'naming' to be a string");
if ("stripPathSuffix" in opts) {
Copy link

Copilot AI May 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider updating the plugin options documentation (and any inline comments) to clearly describe the new 'stripPathSuffix' boolean parameter replacing the old 'naming' option.

Copilot uses AI. Check for mistakes.
assert(
NAMING_STATEGIES.includes(opts.naming as NamingStrategy),
"Expected 'naming' to be either 'hash' or 'package-name'"
typeof opts.stripPathSuffix === "boolean",
"Expected 'stripPathSuffix' to be a boolean"
);
}
}
Expand All @@ -32,7 +30,7 @@ export function replaceWithRequireNodeAddon(
modulePath: string,
naming: NamingStrategy
) {
const requireCallArgument = getLibraryInstallName(
const requireCallArgument = getLibraryName(
replaceWithNodeExtension(modulePath),
naming
);
Expand All @@ -54,7 +52,7 @@ export function plugin(): PluginObj {
visitor: {
CallExpression(p) {
assertOptions(this.opts);
const { naming = "package-name" } = this.opts;
const { stripPathSuffix = false } = this.opts;
if (typeof this.filename !== "string") {
// This transformation only works when the filename is known
return;
Expand All @@ -77,15 +75,17 @@ export function plugin(): PluginObj {
const relativePath = path.join(from, id);
// TODO: Support traversing the filesystem to find the Node-API module
if (isNodeApiModule(relativePath)) {
replaceWithRequireNodeAddon(p.parentPath, relativePath, naming);
replaceWithRequireNodeAddon(p.parentPath, relativePath, {
stripPathSuffix,
});
}
}
} else if (
!path.isAbsolute(id) &&
isNodeApiModule(path.join(from, id))
) {
const relativePath = path.join(from, id);
replaceWithRequireNodeAddon(p, relativePath, naming);
replaceWithRequireNodeAddon(p, relativePath, { stripPathSuffix });
}
}
},
Expand Down
55 changes: 15 additions & 40 deletions packages/react-native-node-api-modules/src/node/cli/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { spawn } from "bufout";
import { packageDirectorySync } from "pkg-dir";
import { readPackageSync } from "read-pkg";

import { NamingStrategy, hashModulePath } from "../path-utils.js";
import { NamingStrategy, getLibraryName } from "../path-utils.js";

// Must be in all xcframeworks to be considered as Node-API modules
export const MAGIC_FILENAME = "react-native-node-api-module";
Expand Down Expand Up @@ -182,16 +182,8 @@ type RebuildXcframeworkOptions = {
type VendoredXcframework = {
originalPath: string;
outputPath: string;
} & (
| {
hash: string;
packageName?: never;
}
| {
hash?: never;
packageName: string;
}
);
libraryName: string;
};

type VendoredXcframeworkResult = VendoredXcframework & {
skipped: boolean;
Expand All @@ -201,24 +193,16 @@ export function determineVendoredXcframeworkDetails(
modulePath: string,
naming: NamingStrategy
): VendoredXcframework {
if (naming === "hash") {
const hash = hashModulePath(modulePath);
return {
hash,
originalPath: modulePath,
outputPath: path.join(XCFRAMEWORKS_PATH, `node-api-${hash}.xcframework`),
};
} else {
const packageRoot = packageDirectorySync({ cwd: modulePath });
assert(packageRoot, `Could not find package root from ${modulePath}`);
const { name } = readPackageSync({ cwd: packageRoot });
assert(name, `Could not find package name from ${packageRoot}`);
return {
packageName: name,
originalPath: modulePath,
outputPath: path.join(XCFRAMEWORKS_PATH, `${name}.xcframework`),
};
}
const packageRoot = packageDirectorySync({ cwd: modulePath });
assert(packageRoot, `Could not find package root from ${modulePath}`);
const { name } = readPackageSync({ cwd: packageRoot });
assert(name, `Could not find package name from ${packageRoot}`);
const libraryName = getLibraryName(modulePath, naming);
return {
originalPath: modulePath,
outputPath: path.join(XCFRAMEWORKS_PATH, `${libraryName}.xcframework`),
libraryName,
};
}

export function hasDuplicatesWhenVendored(
Expand All @@ -243,13 +227,8 @@ export async function vendorXcframework({
}: RebuildXcframeworkOptions): Promise<VendoredXcframeworkResult> {
// Copy the xcframework to the output directory and rename the framework and binary
const details = determineVendoredXcframeworkDetails(modulePath, naming);
const { outputPath } = details;
const discriminator =
typeof details.hash === "string" ? details.hash : details.packageName;
const tempPath = path.join(
XCFRAMEWORKS_PATH,
`node-api-${discriminator}-temp`
);
const { outputPath, libraryName: newLibraryName } = details;
const tempPath = path.join(XCFRAMEWORKS_PATH, `${newLibraryName}.temp`);
try {
if (incremental && existsSync(outputPath)) {
const moduleModified = getLatestMtime(modulePath);
Expand Down Expand Up @@ -284,10 +263,6 @@ export async function vendorXcframework({
".framework"
);
const oldLibraryPath = path.join(frameworkPath, oldLibraryName);
const newLibraryName = path.basename(
details.outputPath,
".xcframework"
);
const newFrameworkPath = path.join(
tripletPath,
`${newLibraryName}.framework`
Expand Down
Loading