diff --git a/AGENTS.md b/AGENTS.md index 78b705610015..5b30ab76d010 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ Never hand-edit generated output — change the source and regenerate. CI valida - Native modules and components are declared by JavaScript specs (`Native*.js`, `*NativeComponent.js`); their native counterparts are generated at build time. - Feature flags are declared in `packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js`; `yarn featureflags` regenerates the JavaScript, Java, and C++ accessors. - JavaScript sources are typed with Flow, and the public API is exported from `packages/react-native/index.js`. TypeScript types are generated from those sources, and `packages/react-native/ReactNativeApi.d.ts` is a committed snapshot of that API — run `yarn build-types` to regenerate both whenever the public API changes, then `yarn test-generated-typescript` to type-check the result. -- The public native API is snapshotted as well: C++ under `scripts/cxx-api` (`yarn cxx-api-build`), and Android in `packages/react-native/ReactAndroid/api/ReactAndroid.api`. +- The public native API is snapshotted as well: C++ under `scripts/cxx-api` (`yarn cxx-api-build`), and Android in `packages/react-native/ReactAndroid/api/ReactAndroid.api` (`yarn android-api-build`). - `CHANGELOG.md` is compiled at release time from pull request descriptions. ## Flow types for npm packages diff --git a/build.gradle.kts b/build.gradle.kts index e1320dc6d06c..900fe637a2a3 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +buildscript { dependencies { classpath(libs.kotlin.metadata.jvm) } } + plugins { alias(libs.plugins.nexus.publish) alias(libs.plugins.android.library) apply false diff --git a/package.json b/package.json index e3733e3a7ecb..5161ef40e59e 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,8 @@ "packageManager": "yarn@1.22.22", "scripts": { "android": "yarn --cwd packages/rn-tester android", + "android-api-build": "node ./scripts/android-api/build-android-api.js", + "android-api-validate": "node ./scripts/android-api/build-android-api.js --validate", "build-android": "./gradlew :packages:react-native:ReactAndroid:build", "build": "node ./scripts/build/build.js", "build-types": "node ./scripts/js-api/build-types", diff --git a/packages/react-native/ReactAndroid/build.gradle.kts b/packages/react-native/ReactAndroid/build.gradle.kts index 9cd0ed1545b4..cf985fe22d88 100644 --- a/packages/react-native/ReactAndroid/build.gradle.kts +++ b/packages/react-native/ReactAndroid/build.gradle.kts @@ -11,6 +11,10 @@ import com.facebook.react.tasks.internal.* import com.facebook.react.tasks.internal.utils.* import de.undercouch.gradle.tasks.download.Download import java.nio.file.Paths +import kotlinx.validation.api.dump +import kotlinx.validation.api.filterOutAnnotated +import kotlinx.validation.api.filterOutNonPublic +import kotlinx.validation.api.loadApiFromJvmClasses import org.jetbrains.kotlin.gradle.dsl.JvmDefaultMode import org.jetbrains.kotlin.gradle.tasks.KotlinCompile @@ -830,6 +834,50 @@ kotlin { tasks.withType { jvmArgs = listOf("-Xshare:off") } +abstract class PublicApiDumpTask : DefaultTask() { + @get:InputFiles + @get:PathSensitive(PathSensitivity.RELATIVE) + abstract val classFiles: ConfigurableFileCollection + + @get:Input abstract val ignoredPackages: ListProperty + + @get:Input abstract val ignoredClasses: ListProperty + + @get:Input abstract val nonPublicMarkers: ListProperty + + @get:OutputFile abstract val outputFile: RegularFileProperty + + @TaskAction + fun dump() { + val api = + classFiles.asFileTree + .matching { include("**/*.class") } + .files + .asSequence() + .map { it.readBytes().inputStream() } + .loadApiFromJvmClasses() + .filterOutNonPublic(ignoredPackages.get(), ignoredClasses.get()) + .filterOutAnnotated(nonPublicMarkers.get().map { it.replace(".", "/") }.toSet()) + .dump(StringBuilder()) + outputFile.get().asFile.writeText(api.toString()) + } +} + +tasks.register("publicApiDump") { + description = + "Dumps the public API of the release classes. Run `yarn android-api-build` to update ReactAndroid.api." + fun listProperty(key: String) = + project.property("binaryCompatibilityValidator.$key").toString().split(",").map { it.trim() } + classFiles.from(tasks.named("compileReleaseKotlin"), tasks.named("compileReleaseJavaWithJavac")) + ignoredPackages.set(listProperty("ignoredPackages")) + ignoredClasses.set(listProperty("ignoredClasses")) + nonPublicMarkers.set(listProperty("nonPublicMarkers")) + outputFile.set( + project.findProperty("publicApiDumpFile")?.let { file(it) } + ?: layout.buildDirectory.file("publicApi/ReactAndroid.api").get().asFile, + ) +} + /* Publishing Configuration */ apply(from = "./publish.gradle") diff --git a/packages/react-native/gradle/libs.versions.toml b/packages/react-native/gradle/libs.versions.toml index 4bb40034c831..8e5763d661e2 100644 --- a/packages/react-native/gradle/libs.versions.toml +++ b/packages/react-native/gradle/libs.versions.toml @@ -21,7 +21,7 @@ androidx-test-junit = "1.2.1" androidx-tracing = "1.1.0" androidx-window = "1.5.1" assertj = "3.21.0" -binary-compatibility-validator = "0.13.2" +binary-compatibility-validator = "0.17.0" download = "5.4.0" espresso-core = "3.6.1" fbjni = "0.8.1" @@ -89,6 +89,7 @@ okio = { module = "com.squareup.okio:okio", version.ref = "okio" } javax-inject = { module = "javax.inject:javax.inject", version.ref = "javax-inject" } javax-annotation-api = { module = "javax.annotation:javax.annotation-api", version.ref = "javax-annotation-api" } jsc-android = { module = "io.github.react-native-community:jsc-android", version.ref = "jsc-android" } +kotlin-metadata-jvm = { module = "org.jetbrains.kotlin:kotlin-metadata-jvm", version.ref = "kotlin" } junit = {module = "junit:junit", version.ref = "junit" } assertj = {module = "org.assertj:assertj-core", version.ref = "assertj" } diff --git a/scripts/android-api/README.md b/scripts/android-api/README.md new file mode 100644 index 000000000000..d28f46286056 --- /dev/null +++ b/scripts/android-api/README.md @@ -0,0 +1,37 @@ +# scripts/android-api + +Regenerate the React Native Android public API snapshot, +`packages/react-native/ReactAndroid/api/ReactAndroid.api`, which tracks the +public Java/Kotlin API surface of ReactAndroid. + +## Usage + +```sh +# Regenerate the snapshot after an intentional public API change +yarn android-api-build + +# Verify the committed snapshot is up to date without rewriting it (for CI) +yarn android-api-validate +``` + +These run ReactAndroid's `publicApiDump` Gradle task, which compiles the +release classes and dumps their public API with the +`binary-compatibility-validator` library, using the filters in +`packages/react-native/ReactAndroid/gradle.properties`. + +The snapshot is maintained from a build that also records a few entries the +Gradle build does not produce: Kotlin `$DefaultImpls` classes and forwarders to +inherited interface default methods, `$$ReactModuleInfoProvider` classes, and +bridges for some internal members. The script keeps the ones already in the +snapshot. `$DefaultImpls` members follow each interface's default methods, and +`$DefaultImpls` classes, forwarders and bridges go away with the class or +default method they belong to. It does not add new ones; those are added when +the change is imported into Meta's repository. + +## When to use it + +Run `yarn android-api-build` after any change to a Kotlin or Java API in +`packages/react-native/ReactAndroid/` that is effectively public or +protected, and commit the updated `.api` file. APIs annotated with +`@UnstableReactNativeAPI`, APIs inside an `internal` package, and +Kotlin-`internal`/`private` declarations are excluded from tracking. diff --git a/scripts/android-api/build-android-api.js b/scripts/android-api/build-android-api.js new file mode 100644 index 000000000000..337e4792bd7c --- /dev/null +++ b/scripts/android-api/build-android-api.js @@ -0,0 +1,368 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +const {REACT_NATIVE_PACKAGE_DIR, REPO_ROOT} = require('../shared/consts'); +const {spawnSync} = require('node:child_process'); +const fs = require('node:fs'); +const {createRequire} = require('node:module'); +const os = require('node:os'); +const path = require('node:path'); + +const API_FILE = path.join( + REACT_NATIVE_PACKAGE_DIR, + 'ReactAndroid', + 'api', + 'ReactAndroid.api', +); + +// The internal backend is stripped from the open source repo. Its existence is +// checked first so that a failure to load it is not mistaken for its absence. +const INTERNAL_BACKEND = path.join(__dirname, 'build-android-api.fb.js'); +const generateWithBuck /*: ?(outputFile: string) => number */ = fs.existsSync( + INTERNAL_BACKEND, +) + ? createRequire(__filename)(INTERNAL_BACKEND) + : null; + +function generateWithGradle(outputFile /*: string */) /*: number */ { + const gradlew = path.join( + REPO_ROOT, + process.platform === 'win32' ? 'gradlew.bat' : 'gradlew', + ); + // cmd.exe runs gradlew.bat and splits unquoted arguments on spaces. + const quote = (arg /*: string */) => + process.platform === 'win32' ? `"${arg}"` : arg; + const {status, error} = spawnSync( + quote(gradlew), + [ + ':packages:react-native:ReactAndroid:publicApiDump', + quote(`-PpublicApiDumpFile=${outputFile}`), + ], + {cwd: REPO_ROOT, stdio: 'inherit', shell: process.platform === 'win32'}, + ); + if (error != null) { + console.error(`Failed to run ${gradlew}: ${error.message}`); + return 1; + } + return status ?? 1; +} + +/*:: +type ApiClass = { + header: string, + name: string, + isInterface: boolean, + supertypes: Array, + members: Array, +}; +*/ + +const MEMBER = /^\t(.*) (fun|field) (\S+) (\S+)$/; +const DEFAULT_IMPLS = '$DefaultImpls'; +const MODULE_INFO_PROVIDER = '$$ReactModuleInfoProvider'; + +function parseApi(text /*: string */) /*: Array */ { + return text.split('\n}\n').flatMap(chunk => { + const lines = chunk.split('\n').filter(line => line !== ''); + if (lines.length === 0) { + return []; + } + const [header, ...members] = lines; + const [declaration, supertypes = ''] = header + .replace(/ \{$/, '') + .split(' : '); + return [ + { + header, + name: declaration.slice(declaration.lastIndexOf(' ') + 1), + isInterface: declaration.includes(' interface class '), + supertypes: supertypes.split(', ').filter(Boolean), + members, + }, + ]; + }); +} + +function renderApi(classes /*: ReadonlyArray */) /*: string */ { + return classes + .map( + apiClass => `${[apiClass.header, ...apiClass.members].join('\n')}\n}\n\n`, + ) + .join(''); +} + +function parseMember( + member /*: string */, +) /*: [string, string, string, string] */ { + const match = MEMBER.exec(member); + if (match == null) { + throw new Error(`Unexpected API member: ${member}`); + } + return [match[1], match[2], match[3], match[4]]; +} + +// The binary-compatibility-validator dump order: fields, then methods, each by +// name and then descriptor. +function compareMembers(a /*: string */, b /*: string */) /*: number */ { + const sortKey = (member /*: string */) /*: Array */ => { + const [, kind, name, desc] = parseMember(member); + return [kind === 'field' ? '1' : '2', name, desc]; + }; + const keyA = sortKey(a); + const keyB = sortKey(b); + for (let i = 0; i < keyA.length; i++) { + if (keyA[i] !== keyB[i]) { + return keyA[i] < keyB[i] ? -1 : 1; + } + } + return 0; +} + +/** + * ReactAndroid.api is generated from the Buck build, which also emits entries + * the Gradle build does not: `$DefaultImpls` classes and forwarders to + * inherited interface default methods (from modules compiled in + * DefaultImpls-compatible mode), `$$ReactModuleInfoProvider` classes, and + * bridges for internal members overridden across modules. + * + * Those entries are carried over from the committed snapshot. `$DefaultImpls` + * members follow their interface's default methods; `$DefaultImpls` classes, + * forwarders and bridges go away with the class or default method they belong + * to. New Buck-only entries are not predicted; internal CI reports them, and + * the internal build adds them. + */ +function mergeBuckOnlyEntries( + snapshot /*: string */, + dump /*: string */, +) /*: string */ { + const committed = new Map( + parseApi(snapshot).map(apiClass => [apiClass.name, apiClass]), + ); + const dumped = new Map( + parseApi(dump).map(apiClass => [apiClass.name, apiClass]), + ); + const memberKey = (member /*: string */) /*: string */ => { + const [, , name, desc] = parseMember(member); + return `${name} ${desc}`; + }; + const hasModifier = (member /*: string */, modifier /*: string */) => + new RegExp(`\\b${modifier}\\b`).test(parseMember(member)[0]); + + // Default methods of an interface, including those inherited from + // interfaces that have `$DefaultImpls` themselves. + const interfaceDefaults = ( + name /*: string */, + seen /*: Set */ = new Set(), + ) /*: Map */ => { + const apiClass = dumped.get(name); + const defaults = new Map /*:: */(); + if (apiClass == null || seen.has(name)) { + return defaults; + } + seen.add(name); + for (const supertype of apiClass.supertypes) { + if (committed.has(supertype + DEFAULT_IMPLS)) { + for (const [key, member] of interfaceDefaults(supertype, seen)) { + if (!defaults.has(key)) { + defaults.set(key, member); + } + } + } + } + for (const member of apiClass.members) { + if (parseMember(member)[1] !== 'fun' || hasModifier(member, 'static')) { + continue; + } + if (hasModifier(member, 'abstract')) { + defaults.delete(memberKey(member)); + } else { + defaults.set(memberKey(member), member); + } + } + return defaults; + }; + + const inheritedDefaults = (apiClass /*: ApiClass */) /*: Set */ => { + const inherited = new Set /*:: */(); + for (const supertype of apiClass.supertypes) { + const superclass = dumped.get(supertype); + if (superclass == null) { + continue; + } + const members = superclass.isInterface + ? interfaceDefaults(supertype).values() + : inheritedDefaults(superclass); + for (const member of members) { + inherited.add(member); + } + } + return inherited; + }; + + const defaultImpls = (name /*: string */) /*: Array */ => { + const members = new Set /*:: */(); + for (const key of interfaceDefaults(name).keys()) { + const [memberName, desc] = key.split(' '); + members.add( + `\tpublic static fun ${memberName} (L${name};${desc.slice(1)}`, + ); + } + for (const member of dumped.get(name)?.members ?? []) { + if ( + hasModifier(member, 'static') && + parseMember(member)[2].endsWith('$default') + ) { + members.add(member); + } + } + return [...members].sort(compareMembers); + }; + + const merged = new Map /*:: */(); + for (const apiClass of dumped.values()) { + const snapshotClass = committed.get(apiClass.name); + const members = [...apiClass.members]; + if (snapshotClass != null && !apiClass.isInterface) { + const dumpedMembers = new Set(members); + const inherited = inheritedDefaults(apiClass); + for (const member of snapshotClass.members) { + if ( + !dumpedMembers.has(member) && + (inherited.has(member) || / synthetic fun \S*\$xplat_js/.test(member)) + ) { + members.push(member); + } + } + } + merged.set(apiClass.name, { + ...apiClass, + members: members.sort(compareMembers), + }); + } + for (const [name, snapshotClass] of committed) { + if (name.endsWith(DEFAULT_IMPLS)) { + const owner = dumped.get(name.slice(0, -DEFAULT_IMPLS.length)); + const members = + owner?.isInterface === true ? defaultImpls(owner.name) : []; + if (members.length > 0) { + merged.set(name, {...snapshotClass, members}); + } + } else if (name.endsWith(MODULE_INFO_PROVIDER)) { + merged.set(name, snapshotClass); + } + } + return renderApi( + [...merged.entries()] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([, apiClass]) => apiClass), + ); +} + +function reportDifference( + expected /*: string */, + actual /*: string */, + tempDir /*: string */, +) { + for (const [directory, content] of [ + ['committed', expected], + ['generated', actual], + ]) { + fs.mkdirSync(path.join(tempDir, directory)); + fs.writeFileSync( + path.join(tempDir, directory, 'ReactAndroid.api'), + content, + ); + } + const {error} = spawnSync( + 'git', + [ + '--no-pager', + 'diff', + '--no-index', + '--', + 'committed/ReactAndroid.api', + 'generated/ReactAndroid.api', + ], + {cwd: tempDir, stdio: 'inherit'}, + ); + if (error != null) { + const expectedLines = new Set(expected.split('\n')); + const actualLines = new Set(actual.split('\n')); + for (const line of expectedLines) { + if (!actualLines.has(line)) { + console.log(`-${line}`); + } + } + for (const line of actualLines) { + if (!expectedLines.has(line)) { + console.log(`+${line}`); + } + } + } +} + +function main() /*: number */ { + const args = process.argv.slice(2); + if (args.includes('--help') || args.includes('-h')) { + console.log(` + Usage: node ./scripts/android-api/build-android-api.js [--validate] + + Regenerate the React Native Android public API snapshot + (packages/react-native/ReactAndroid/api/ReactAndroid.api). + + Options: + --validate | --compareApis + Verify the committed snapshot is up to date instead of + regenerating it. Exits non-zero when it differs. + `); + return 0; + } + const validate = + args.includes('--validate') || args.includes('--compareApis'); + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'android-api-')); + try { + return run(validate, tempDir); + } finally { + fs.rmSync(tempDir, {recursive: true, force: true}); + } +} + +function run(validate /*: boolean */, tempDir /*: string */) /*: number */ { + const rawFile = path.join(tempDir, 'ReactAndroid.raw.api'); + const status = (generateWithBuck ?? generateWithGradle)(rawFile); + if (status !== 0 || !fs.existsSync(rawFile)) { + console.error('Failed to generate the ReactAndroid API dump.'); + return status !== 0 ? status : 1; + } + const expected = fs.existsSync(API_FILE) + ? fs.readFileSync(API_FILE, 'utf8').replace(/\r\n/g, '\n') + : ''; + const dump = fs.readFileSync(rawFile, 'utf8'); + const api = + generateWithBuck != null ? dump : mergeBuckOnlyEntries(expected, dump); + + if (!validate) { + fs.writeFileSync(API_FILE, api); + console.log(`Wrote ${API_FILE}`); + return 0; + } + + if (expected === api) { + console.log('ReactAndroid.api is up to date.'); + return 0; + } + reportDifference(expected, api, tempDir); + console.error( + '\nThe public Android API of React Native changed. If the change is intended, run `yarn android-api-build` and commit ReactAndroid.api.', + ); + return 1; +} + +process.exitCode = main();