Skip to content
Closed
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
14 changes: 14 additions & 0 deletions .changeset/babel-plugin-js-precedence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
"react-native-node-api": patch
---

Fix the Babel plugin rewriting `require(...)` calls that resolve to a
same-named `.js`/`.cjs`/`.mjs`/`.json` file sitting next to a Node-API
prebuild. Node's own module resolution always picks the source file over a
`.node` addon in that case, so the plugin now leaves those calls alone
instead of rewriting them to `requireNodeAddon(...)`, which would have loaded
the wrong module at runtime.

Also exports `escapeBundleIdentifier`, used internally to derive a
framework's `CFBundleIdentifier`, so it can be reused to verify one against
its expected value.
3 changes: 2 additions & 1 deletion packages/host/src/node/babel-plugin/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ describe("plugin", () => {
itTransforms("and does not touch required JS files", {
files: {
"package.json": `{ "name": "my-package" }`,
// TODO: Add a ./my-addon.node to make this test complete
"my-addon.apple.node/my-addon.node":
"// This is supposed to be a binary file",
"my-addon.js": "// Some JS file",
"index.js": `
const addon = require('./my-addon');
Expand Down
1 change: 1 addition & 0 deletions packages/host/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export {
createXCframework,
createUniversalAppleLibrary,
determineXCFrameworkFilename,
escapeBundleIdentifier,
} from "./prebuilds/apple.js";

export {
Expand Down
21 changes: 20 additions & 1 deletion packages/host/src/node/path-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,37 @@ export type NamingStrategy = {
// Cache mapping package directory to package name across calls
const packageNameCache = new Map<string, string>();

/**
* Extensions Node's own `require()` resolves before it would ever consider `.node` -
* see https://nodejs.org/api/modules.html#file-modules. A colliding file always wins,
* so a module path resolving to one of these isn't ours to rewrite.
*/
const JS_RESOLVABLE_EXTENSIONS = [".js", ".cjs", ".mjs", ".json"];

/**
* @param modulePath Batch-scans the path to the module to check (must be extensionless or end in .node)
* @returns True if a platform specific prebuild exists for the module path, warns on unreadable modules.
* @throws If the parent directory cannot be read, or if a detected module is unreadable.
* TODO: Consider checking for a specific platform extension.
*/
export function isNodeApiModule(modulePath: string): boolean {
const hasExplicitNodeExtension = modulePath.endsWith(".node");
if (!hasExplicitNodeExtension) {
const dir = path.dirname(modulePath);
const baseName = path.basename(modulePath);
if (
JS_RESOLVABLE_EXTENSIONS.some((extension) =>
fs.existsSync(path.join(dir, baseName + extension)),
)
) {
return false;
}
}
{
// HACK: Take a shortcut (if applicable): existing `.node` files are addons
try {
fs.accessSync(
modulePath.endsWith(".node") ? modulePath : `${modulePath}.node`,
hasExplicitNodeExtension ? modulePath : `${modulePath}.node`,
);
return true;
} catch {
Expand Down
1 change: 1 addition & 0 deletions packages/node-addon-examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"bootstrap": "node --run copy-and-build"
},
"devDependencies": {
"@expo/plist": "0.4.7",
"cmake-rn": "workspace:*",
"node-addon-examples": "github:nodejs/node-addon-examples#4b7dd86a85644610e6de80154df9acac9329b509",
"gyp-to-cmake": "workspace:*",
Expand Down
37 changes: 35 additions & 2 deletions packages/node-addon-examples/scripts/verify-prebuilds.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@ import fs from "node:fs";
import assert from "node:assert/strict";
import path from "node:path";

import plistPackage from "@expo/plist";
import { escapeBundleIdentifier } from "react-native-node-api";

import { DIRS } from "./cmake-projects.mjs";

// `@expo/plist` is CommonJS; under Node's ESM interop the default import lands
// one level deeper than TS's `esModuleInterop` cjs-compiled callers see it.
const plist = plistPackage.default;

const EXPECTED_ANDROID_ARCHS = ["armeabi-v7a", "arm64-v8a", "x86_64", "x86"];

const EXPECTED_XCFRAMEWORK_PLATFORMS = [
Expand Down Expand Up @@ -37,6 +44,29 @@ async function verifyAndroidPrebuild(dirent: fs.Dirent) {
}
}

/**
* Asserts an Info.plist matches what `writeFrameworkInfoPlist` (in
* `packages/host/src/node/prebuilds/apple.ts`) writes for a framework named
* `libraryName`, built without a custom `--apple-bundle-identifier`.
*/
async function verifyFrameworkInfoPlist(
infoPlistPath: string,
libraryName: string,
) {
const contents = await fs.promises.readFile(infoPlistPath, "utf8");
const infoPlist = plist.parse(contents) as Record<string, unknown>;
assert.equal(
infoPlist.CFBundleExecutable,
libraryName,
`Unexpected CFBundleExecutable in ${infoPlistPath}`,
);
assert.equal(
infoPlist.CFBundleIdentifier,
escapeBundleIdentifier(`com.callstackincubator.node-api.${libraryName}`),
`Unexpected CFBundleIdentifier in ${infoPlistPath}`,
);
}

async function verifyApplePrebuild(dirent: fs.Dirent) {
console.log("Verifying Apple prebuild", dirent.name, "in", dirent.parentPath);
for (const arch of EXPECTED_XCFRAMEWORK_PLATFORMS) {
Expand All @@ -50,6 +80,7 @@ async function verifyApplePrebuild(dirent: fs.Dirent) {
);
assert(file.name.endsWith(".framework"), "Expected framework directory");
const frameworkDir = path.join(file.parentPath, file.name);
const libraryName = path.basename(file.name, ".framework");
for (const file of await fs.promises.readdir(frameworkDir, {
withFileTypes: true,
})) {
Expand All @@ -65,8 +96,10 @@ async function verifyApplePrebuild(dirent: fs.Dirent) {
"Expected only directory and files in framework",
);
if (file.name === "Info.plist") {
// TODO: Verify the contents of the Info.plist file
continue;
await verifyFrameworkInfoPlist(
path.join(frameworkDir, file.name),
libraryName,
);
} else {
assert(
!file.name.endsWith(".node"),
Expand Down
23 changes: 5 additions & 18 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading