A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
mobile: autolink prebuilt libraries and skip java/cpp compilation step
Ammar Ahmed774df77bd273
diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradleindex 619e3dd50..bc1180f36 100644--- a/apps/mobile/android/app/build.gradle+++ b/apps/mobile/android/app/build.gradle@@ -10,6 +10,8 @@ import com.android.build.OutputFileimport groovy.json.JsonSlurperimport org.apache.tools.ant.taskdefs.condition.Os+apply from: new File(rootDir, "prebuilt-aars.gradle")+react {/* Folders */// The root of your project, i.e. where "package.json" lives. Default is '..'@@ -257,8 +259,6 @@ dependencies {}-apply from: new File(rootDir, "prebuilt-aars.gradle")-task deleteFiles(type: Delete) {delete './src/main/assets/static'}diff --git a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainApplication.kt b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainApplication.ktindex 7b060297d..3dbe88059 100644--- a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainApplication.kt+++ b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainApplication.kt@@ -4,11 +4,9 @@ import android.app.Applicationimport com.facebook.react.PackageListimport com.facebook.react.ReactApplicationimport com.facebook.react.ReactHost-import com.facebook.react.ReactPackageimport com.facebook.react.defaults.DefaultReactHost.getDefaultReactHostimport com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNativeimport org.wonday.orientation.OrientationActivityLifecycle;-class MainApplication : Application(), ReactApplication {override val reactHost: ReactHost by lazy {getDefaultReactHost(@@ -18,31 +16,9 @@ class MainApplication : Application(), ReactApplication {// Packages that cannot be autolinked yet can be added manually here, for example:// add(MyReactNativePackage())add(NNativeModulePackage());- // Prebuilt JSI/Fabric packages that are excluded from autolinking:- addIfMissing("com.margelo.rnquicksqlite.SequelPackage")- addIfMissing("com.fastopenpgp.FastOpenpgpPackage")- addIfMissing("com.swmansion.rnscreens.RNScreensPackage")- addIfMissing("com.swmansion.gesturehandler.RNGestureHandlerPackage")- addIfMissing("com.ammarahmed.mmkv.RNMMKVPackage")- addIfMissing("com.margelo.nitro.NitroModulesPackage")- addIfMissing("com.margelo.nitro.nitroclouduploader.NitroCloudUploaderPackage")- addIfMissing("com.worklets.WorkletsPackage")- addIfMissing("com.swmansion.reanimated.ReanimatedPackage")},)}-- private fun MutableList<ReactPackage>.addIfMissing(className: String) {- if (none { it.javaClass.name == className }) {- try {- val clazz = Class.forName(className)- val pkg = clazz.getConstructor().newInstance() as ReactPackage- add(pkg)- } catch (e: Throwable) {- // Ignored: package class not found or instantiation failed- }- }- }override fun onCreate() {super.onCreate()diff --git a/apps/mobile/android/prebuilt-aars.gradle b/apps/mobile/android/prebuilt-aars.gradleindex 11b9b8da3..dc70d022b 100644--- a/apps/mobile/android/prebuilt-aars.gradle+++ b/apps/mobile/android/prebuilt-aars.gradle@@ -17,78 +17,43 @@ import org.gradle.api.initialization.Settingsdef isSettings = this instanceof Settings || hasProperty("settingsDir")if (isSettings) {- // In Settings context: synchronize autolinking cache and disabled flag with .prebuilt-aars statedef prebuiltDir = new File(settingsDir, ".prebuilt-aars")def propVal = gradle.startParameter.projectProperties.get("usePrebuiltAars")if (propVal == null && settings.providers.gradleProperty("usePrebuiltAars").isPresent()) {propVal = settings.providers.gradleProperty("usePrebuiltAars").get()}- def disabledByProp = (propVal == "false")- def autolinkDir = new File(settingsDir, "build/generated/autolinking")- def disabledMarker = new File(autolinkDir, ".prebuilt-disabled")-- if (disabledByProp) {- if (!disabledMarker.exists()) {- autolinkDir.mkdirs()- disabledMarker.createNewFile()- autolinkDir.deleteDir()- }- } else {- if (disabledMarker.exists()) {- disabledMarker.delete()- autolinkDir.deleteDir()- }- }+ def state = propVal == "false"+ ? "disabled"+ : (prebuiltDir.exists() ? (prebuiltDir.list()?.sort()?.join(",") ?: "empty") : "none")- def prebuiltState = prebuiltDir.exists() ? (prebuiltDir.list()?.sort()?.join(",") ?: "empty") : "none"- def markerFile = new File(autolinkDir, ".prebuilt-aars.marker")- if (!markerFile.exists() || markerFile.text != prebuiltState) {+ def autolinkDir = new File(settingsDir, "build/generated/autolinking")+ def stateFile = new File(autolinkDir, ".prebuilt-aars.state")+ if (!stateFile.exists() || stateFile.text != state) {autolinkDir.deleteDir()- markerFile.parentFile?.mkdirs()- markerFile.text = prebuiltState+ autolinkDir.mkdirs()+ stateFile.text = state}} else {- // In Project (app) context: add prebuilt dependencies and re-declare transitives- def propVal = project.hasProperty("usePrebuiltAars") ? project.findProperty("usePrebuiltAars") : gradle.startParameter.projectProperties.get("usePrebuiltAars")- def usePrebuilts = (propVal != "false")- def prebuiltDir = new File(rootDir, ".prebuilt-aars")-- def allHashes = [:]- try {- def proc = ["node", "${rootDir}/scripts/build-prebuilt-aars.js", "--hash-all"].execute(null, rootDir)- def json = new groovy.json.JsonSlurper().parseText(proc.text.trim())- if (json instanceof Map) {- allHashes = json- }- } catch (Exception e) {- // Ignored, getAarHash will fallback per lib+ def prebuiltConfiguration = "prebuiltAar"+ configurations.maybeCreate(prebuiltConfiguration).with {+ canBeResolved = false+ canBeConsumed = false}- def getAarHash = { String libName ->- if (allHashes.containsKey(libName)) {- return allHashes[libName]- }- try {- def proc = ["node", "${rootDir}/scripts/build-prebuilt-aars.js", "--hash", libName].execute(null, rootDir)- return proc.text.trim()- } catch (Exception e) {- return ""+ def autolinkingFile = new File(rootDir, "build/generated/autolinking/autolinking.json")+ def prebuiltLibs = []+ if (autolinkingFile.exists()) {+ def autolinking = new groovy.json.JsonSlurper().parse(autolinkingFile)+ autolinking.dependencies?.each { name, dep ->+ if (dep?.platforms?.android?.dependencyConfiguration == prebuiltConfiguration) {+ prebuiltLibs << name+ }}}- // Configured prebuilt libraries and their transitive dependenciesdef prebuiltLibraries = [- "react-native-quick-sqlite": [- prefix: "react-native-quick-sqlite",- transitive: []- ],- "react-native-fast-openpgp": [- prefix: "react-native-fast-openpgp",- transitive: []- ],"react-native-screens": [- prefix: "react-native-screens",transitive: ['androidx.appcompat:appcompat:1.6.1','androidx.fragment:fragment-ktx:1.6.1',@@ -100,24 +65,17 @@ if (isSettings) {]],"react-native-gesture-handler": [- prefix: "react-native-gesture-handler",transitive: ['androidx.core:core-ktx:1.8.0']],"react-native-mmkv-storage": [- prefix: "react-native-mmkv-storage",transitive: ['androidx.security:security-crypto:1.1.0-alpha03','com.google.code.gson:gson:2.8.6']],- "react-native-nitro-modules": [- prefix: "react-native-nitro-modules",- transitive: []- ],"react-native-nitro-cloud-uploader": [- prefix: "react-native-nitro-cloud-uploader",transitive: ['org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3','org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3',@@ -126,7 +84,6 @@ if (isSettings) {]],"react-native-worklets": [- prefix: "react-native-worklets",transitive: ['com.facebook.yoga:proguard-annotations:1.19.0','androidx.transition:transition:1.1.0',@@ -134,7 +91,6 @@ if (isSettings) {]],"react-native-reanimated": [- prefix: "react-native-reanimated",transitive: ['com.facebook.yoga:proguard-annotations:1.19.0','androidx.transition:transition:1.1.0',@@ -143,33 +99,30 @@ if (isSettings) {]]- android {- packagingOptions {- pickFirst '**/libworklets.so'- pickFirst '**/libNitroModules.so'- }- }+ if (!prebuiltLibs.isEmpty()) {+ def proc = ["node", "${rootDir}/scripts/build-prebuilt-aars.js", "--aars"].execute(null, rootDir)+ def aars = new groovy.json.JsonSlurper().parseText(proc.text.trim())- dependencies {- prebuiltLibraries.each { libName, config ->- def hash = getAarHash(libName)- def prefix = config.prefix- def debugAar = new File(prebuiltDir, "${prefix}-debug-${hash}.aar")- def releaseAar = new File(prebuiltDir, "${prefix}-release-${hash}.aar")+ android {+ packagingOptions {+ pickFirst '**/libworklets.so'+ pickFirst '**/libNitroModules.so'+ }+ }- if (usePrebuilts && debugAar.exists() && releaseAar.exists()) {- debugImplementation files(debugAar)- releaseImplementation files(releaseAar)+ dependencies {+ prebuiltLibs.each { libName ->+ def aar = aars[libName]+ if (aar == null) {+ throw new GradleException("[Prebuilt AAR] ${libName}: no AAR matches the current hash. Run ./gradlew clean to refresh autolinking.")+ }- // Re-declare external transitive dependencies- config.transitive.each { dep ->+ debugImplementation files(aar.debug)+ releaseImplementation files(aar.release)+ prebuiltLibraries[libName]?.transitive?.each { dep ->implementation dep}-- println "[Prebuilt AAR] ${libName}: Using prebuilt AAR (${prefix}-${hash})"- } else {- def reason = !usePrebuilts ? "disabled via -PusePrebuiltAars=false" : "AAR missing or hash mismatch (${hash})"- println "[Prebuilt AAR] ${libName}: Building from source (${reason})"+ println "[Prebuilt AAR] ${libName}: Using prebuilt AAR"}}}diff --git a/apps/mobile/android/scripts/build-prebuilt-aars.js b/apps/mobile/android/scripts/build-prebuilt-aars.jsindex 4fc9dcb20..a0e79ae46 100644--- a/apps/mobile/android/scripts/build-prebuilt-aars.js+++ b/apps/mobile/android/scripts/build-prebuilt-aars.js@@ -1,126 +1,167 @@-const fs = require('fs');-const path = require('path');-const { execSync } = require('child_process');-const crypto = require('crypto');+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/+const fs = require("fs");+const path = require("path");+const { execSync } = require("child_process");+const crypto = require("crypto");// Resolve important directory paths relative to this script-const androidDir = path.resolve(__dirname, '..');-const mobileDir = path.resolve(androidDir, '..');-const rootDir = path.resolve(mobileDir, '..', '..');-const prebuiltDir = path.join(androidDir, '.prebuilt-aars');+const androidDir = path.resolve(__dirname, "..");+const mobileDir = path.resolve(androidDir, "..");+const rootDir = path.resolve(mobileDir, "..", "..");+const prebuiltDir = path.join(androidDir, ".prebuilt-aars");// Library registry configuration// gradleProject: Gradle project name (defaults to lib name with @ stripped and / replaced with _)// filePrefix: Output file prefix (defaults to lib name with @ stripped and / replaced with -)// customFlagsProp: gradle.properties property key containing extra compile flagsconst ALL_LIBRARIES = {- 'react-native-quick-sqlite': {- gradleProject: 'react-native-quick-sqlite',- filePrefix: 'react-native-quick-sqlite',- customFlagsProp: 'quickSqliteFlags',- },- 'react-native-fast-openpgp': {- gradleProject: 'react-native-fast-openpgp',- filePrefix: 'react-native-fast-openpgp',+ "react-native-quick-sqlite": {+ gradleProject: "react-native-quick-sqlite",+ filePrefix: "react-native-quick-sqlite",+ customFlagsProp: "quickSqliteFlags"},- 'react-native-screens': {- gradleProject: 'react-native-screens',- filePrefix: 'react-native-screens',+ "react-native-fast-openpgp": {+ gradleProject: "react-native-fast-openpgp",+ filePrefix: "react-native-fast-openpgp"},- 'react-native-gesture-handler': {- gradleProject: 'react-native-gesture-handler',- filePrefix: 'react-native-gesture-handler',+ "react-native-screens": {+ gradleProject: "react-native-screens",+ filePrefix: "react-native-screens"},- 'react-native-mmkv-storage': {- gradleProject: 'react-native-mmkv-storage',- filePrefix: 'react-native-mmkv-storage',+ "react-native-gesture-handler": {+ gradleProject: "react-native-gesture-handler",+ filePrefix: "react-native-gesture-handler"},- '@callstack/repack': {- gradleProject: 'callstack_repack',- filePrefix: 'callstack-repack',+ "react-native-mmkv-storage": {+ gradleProject: "react-native-mmkv-storage",+ filePrefix: "react-native-mmkv-storage"},- 'react-native-nitro-modules': {- gradleProject: 'react-native-nitro-modules',- filePrefix: 'react-native-nitro-modules',+ "@callstack/repack": {+ gradleProject: "callstack_repack",+ filePrefix: "callstack-repack"},- 'react-native-nitro-cloud-uploader': {- gradleProject: 'react-native-nitro-cloud-uploader',- filePrefix: 'react-native-nitro-cloud-uploader',+ "react-native-nitro-modules": {+ gradleProject: "react-native-nitro-modules",+ filePrefix: "react-native-nitro-modules"},- 'react-native-worklets': {- gradleProject: 'react-native-worklets',- filePrefix: 'react-native-worklets',+ "react-native-nitro-cloud-uploader": {+ gradleProject: "react-native-nitro-cloud-uploader",+ filePrefix: "react-native-nitro-cloud-uploader"},- 'react-native-reanimated': {- gradleProject: 'react-native-reanimated',- filePrefix: 'react-native-reanimated',+ "react-native-worklets": {+ gradleProject: "react-native-worklets",+ filePrefix: "react-native-worklets"},+ "react-native-reanimated": {+ gradleProject: "react-native-reanimated",+ filePrefix: "react-native-reanimated"+ }};// All configured prebuilt libraries in dependency orderconst ACTIVE_LIBRARIES = [- 'react-native-quick-sqlite',- 'react-native-fast-openpgp',- 'react-native-screens',- 'react-native-gesture-handler',- 'react-native-mmkv-storage',- 'react-native-nitro-modules',- 'react-native-nitro-cloud-uploader',- 'react-native-worklets',- 'react-native-reanimated',+ "react-native-quick-sqlite",+ "react-native-fast-openpgp",+ "react-native-screens",+ "react-native-gesture-handler",+ "react-native-mmkv-storage",+ "react-native-nitro-modules",+ "react-native-nitro-cloud-uploader",+ "react-native-worklets",+ "react-native-reanimated"];function computeHash(libName) {const libConfig = ALL_LIBRARIES[libName] || {- gradleProject: libName.replace(/^@/, '').replace(/\//g, '_'),- filePrefix: libName.replace(/^@/, '').replace(/\//g, '-'),+ gradleProject: libName.replace(/^@/, "").replace(/\//g, "_"),+ filePrefix: libName.replace(/^@/, "").replace(/\//g, "-")};// 1. Library version from its package.json- const libPkgPath = path.join(mobileDir, 'node_modules', libName, 'package.json');+ const libPkgPath = path.join(+ mobileDir,+ "node_modules",+ libName,+ "package.json"+ );if (!fs.existsSync(libPkgPath)) {- throw new Error(`Cannot find package.json for library: ${libName} at ${libPkgPath}`);+ throw new Error(+ `Cannot find package.json for library: ${libName} at ${libPkgPath}`+ );}- const libVersion = JSON.parse(fs.readFileSync(libPkgPath, 'utf8')).version;+ const libVersion = JSON.parse(fs.readFileSync(libPkgPath, "utf8")).version;// 2. React Native version- const rnPkgPath = path.join(mobileDir, 'node_modules', 'react-native', 'package.json');+ const rnPkgPath = path.join(+ mobileDir,+ "node_modules",+ "react-native",+ "package.json"+ );const rnVersion = fs.existsSync(rnPkgPath)- ? JSON.parse(fs.readFileSync(rnPkgPath, 'utf8')).version- : '';+ ? JSON.parse(fs.readFileSync(rnPkgPath, "utf8")).version+ : "";// 3. Flags and architectures from gradle.properties- const gradlePropsPath = path.join(androidDir, 'gradle.properties');- const gradleProps = fs.existsSync(gradlePropsPath) ? fs.readFileSync(gradlePropsPath, 'utf8') : '';- const newArch = (gradleProps.match(/^newArchEnabled\s*=\s*(.+)$/m) || [])[1]?.trim() || '';- const hermes = (gradleProps.match(/^hermesEnabled\s*=\s*(.+)$/m) || [])[1]?.trim() || '';- const archs = (gradleProps.match(/^reactNativeArchitectures\s*=\s*(.+)$/m) || [])[1]?.trim() || '';+ const gradlePropsPath = path.join(androidDir, "gradle.properties");+ const gradleProps = fs.existsSync(gradlePropsPath)+ ? fs.readFileSync(gradlePropsPath, "utf8")+ : "";+ const newArch =+ (gradleProps.match(/^newArchEnabled\s*=\s*(.+)$/m) || [])[1]?.trim() || "";+ const hermes =+ (gradleProps.match(/^hermesEnabled\s*=\s*(.+)$/m) || [])[1]?.trim() || "";+ const archs =+ (gradleProps.match(/^reactNativeArchitectures\s*=\s*(.+)$/m) ||+ [])[1]?.trim() || "";// 4. NDK version from build.gradle- const buildGradlePath = path.join(androidDir, 'build.gradle');- const buildGradle = fs.existsSync(buildGradlePath) ? fs.readFileSync(buildGradlePath, 'utf8') : '';+ const buildGradlePath = path.join(androidDir, "build.gradle");+ const buildGradle = fs.existsSync(buildGradlePath)+ ? fs.readFileSync(buildGradlePath, "utf8")+ : "";const ndkMatch = buildGradle.match(/ndkVersion\s*=\s*['"]([^'"]+)['"]/);- const ndkVersion = ndkMatch ? ndkMatch[1] : '';+ const ndkVersion = ndkMatch ? ndkMatch[1] : "";// 5. Library-specific custom flags if configured- let customFlags = '';+ let customFlags = "";if (libConfig.customFlagsProp) {- const re = new RegExp(`^${libConfig.customFlagsProp}\\s*=\\s*(.+)$`, 'm');- customFlags = (gradleProps.match(re) || [])[1]?.trim() || '';+ const re = new RegExp(`^${libConfig.customFlagsProp}\\s*=\\s*(.+)$`, "m");+ customFlags = (gradleProps.match(re) || [])[1]?.trim() || "";}// 6. Relevant patch files from apps/mobile/patches- const patchesDir = path.join(mobileDir, 'patches');- const patchPrefix = libName.replace(/\//g, '+');- let patchContent = '';+ const patchesDir = path.join(mobileDir, "patches");+ const patchPrefix = libName.replace(/\//g, "+");+ let patchContent = "";if (fs.existsSync(patchesDir)) {- const patchFiles = fs.readdirSync(patchesDir)- .filter((f) => f.startsWith(patchPrefix) && f.endsWith('.patch'))+ const patchFiles = fs+ .readdirSync(patchesDir)+ .filter((f) => f.startsWith(patchPrefix) && f.endsWith(".patch")).sort();- patchContent = patchFiles.map((f) => fs.readFileSync(path.join(patchesDir, f), 'utf8')).join('\n');+ patchContent = patchFiles+ .map((f) => fs.readFileSync(path.join(patchesDir, f), "utf8"))+ .join("\n");}- const hash = crypto.createHash('sha1');+ const hash = crypto.createHash("sha1");hash.update(`lib:${libName}@${libVersion}\n`);hash.update(`rn:${rnVersion}\n`);hash.update(`archs:${archs}\n`);@@ -132,7 +173,7 @@ function computeHash(libName) {}hash.update(`patch:${patchContent}\n`);- return hash.digest('hex').substring(0, 8);+ return hash.digest("hex").substring(0, 8);}function buildPrebuiltAar(libName, targetVariant) {@@ -141,17 +182,21 @@ function buildPrebuiltAar(libName, targetVariant) {}const libConfig = ALL_LIBRARIES[libName] || {- gradleProject: libName.replace(/^@/, '').replace(/\//g, '_'),- filePrefix: libName.replace(/^@/, '').replace(/\//g, '-'),+ gradleProject: libName.replace(/^@/, "").replace(/\//g, "_"),+ filePrefix: libName.replace(/^@/, "").replace(/\//g, "-")};const hash = computeHash(libName);- const variants = targetVariant ? [targetVariant] : ['debug', 'release'];+ const variants = targetVariant ? [targetVariant] : ["debug", "release"];// Read target ABIs- const gradlePropsPath = path.join(androidDir, 'gradle.properties');- const gradleProps = fs.existsSync(gradlePropsPath) ? fs.readFileSync(gradlePropsPath, 'utf8') : '';- const archs = (gradleProps.match(/^reactNativeArchitectures\s*=\s*(.+)$/m) || [])[1]?.trim() || 'armeabi-v7a,arm64-v8a,x86,x86_64';+ const gradlePropsPath = path.join(androidDir, "gradle.properties");+ const gradleProps = fs.existsSync(gradlePropsPath)+ ? fs.readFileSync(gradlePropsPath, "utf8")+ : "";+ const archs =+ (gradleProps.match(/^reactNativeArchitectures\s*=\s*(.+)$/m) ||+ [])[1]?.trim() || "armeabi-v7a,arm64-v8a,x86,x86_64";for (const variant of variants) {const aarFileName = `${libConfig.filePrefix}-${variant}-${hash}.aar`;@@ -167,38 +212,44 @@ function buildPrebuiltAar(libName, targetVariant) {console.log(`[BUILD] Running ${task} for ${libName} (hash: ${hash})...`);// Invalidate autolinking cache prior to build to avoid stale state- const autolinkCache = path.join(androidDir, 'build', 'generated', 'autolinking');+ const autolinkCache = path.join(+ androidDir,+ "build",+ "generated",+ "autolinking"+ );if (fs.existsSync(autolinkCache)) {fs.rmSync(autolinkCache, { recursive: true, force: true });}- execSync(- `./gradlew ${task} -PreactNativeArchitectures=${archs}`,- {- cwd: androidDir,- stdio: 'inherit',- env: {- ...process.env,- BUILDING_PREBUILT_AARS: 'true',- },+ execSync(`./gradlew ${task} -PreactNativeArchitectures=${archs}`, {+ cwd: androidDir,+ stdio: "inherit",+ env: {+ ...process.env,+ BUILDING_PREBUILT_AARS: "true"}- );+ });const aarOutputDir = path.join(mobileDir,- 'node_modules',+ "node_modules",libName,- 'android',- 'build',- 'outputs',- 'aar'+ "android",+ "build",+ "outputs",+ "aar");if (!fs.existsSync(aarOutputDir)) {- throw new Error(`AAR output dir not found for ${libName} at ${aarOutputDir}`);+ throw new Error(+ `AAR output dir not found for ${libName} at ${aarOutputDir}`+ );}- const aarFiles = fs.readdirSync(aarOutputDir).filter((f) => f.endsWith('.aar'));+ const aarFiles = fs+ .readdirSync(aarOutputDir)+ .filter((f) => f.endsWith(".aar"));const matchedAar = aarFiles.find((f) => f.includes(variant)) || aarFiles[0];if (!matchedAar) {throw new Error(`No .aar file generated in ${aarOutputDir}`);@@ -209,50 +260,50 @@ function buildPrebuiltAar(libName, targetVariant) {}// Refresh autolinking cache state and touch react-native.config.js- const autolinkCache = path.join(androidDir, 'build', 'generated', 'autolinking');+ const autolinkCache = path.join(+ androidDir,+ "build",+ "generated",+ "autolinking"+ );if (fs.existsSync(autolinkCache)) {fs.rmSync(autolinkCache, { recursive: true, force: true });}- const configPath = path.join(mobileDir, 'react-native.config.js');+ const configPath = path.join(mobileDir, "react-native.config.js");if (fs.existsSync(configPath)) {const now = new Date();fs.utimesSync(configPath, now, now);}}+function findPrebuiltAars() {+ const result = {};+ for (const lib of ACTIVE_LIBRARIES) {+ try {+ const hash = computeHash(lib);+ const { filePrefix } = ALL_LIBRARIES[lib];+ const debug = path.join(prebuiltDir, `${filePrefix}-debug-${hash}.aar`);+ const release = path.join(+ prebuiltDir,+ `${filePrefix}-release-${hash}.aar`+ );+ if (fs.existsSync(debug) && fs.existsSync(release)) {+ result[lib] = { debug, release };+ }+ } catch (e) {}+ }+ return result;+}+// CLI Handlingif (require.main === module) {const args = process.argv.slice(2);- if (args[0] === '--hash-all') {- const result = {};- for (const lib of ACTIVE_LIBRARIES) {- try {- result[lib] = computeHash(lib);- } catch (e) {- result[lib] = '';- }- }- process.stdout.write(JSON.stringify(result) + '\n');+ if (args[0] === "--aars") {+ process.stdout.write(JSON.stringify(findPrebuiltAars()) + "\n");process.exit(0);}- if (args[0] === '--hash') {- const libName = args[1];- if (!libName) {- console.error('Usage: node build-prebuilt-aars.js --hash <lib-name>');- process.exit(1);- }- try {- const hash = computeHash(libName);- process.stdout.write(hash + '\n');- process.exit(0);- } catch (err) {- console.error(err.message);- process.exit(1);- }- }-const targetLib = args[0];const targetVariant = args[1];@@ -266,5 +317,6 @@ module.exports = {ALL_LIBRARIES,ACTIVE_LIBRARIES,computeHash,- buildPrebuiltAar,+ findPrebuiltAars,+ buildPrebuiltAar};diff --git a/apps/mobile/react-native.config.js b/apps/mobile/react-native.config.jsindex 4ebfc9cca..c4aff0c2a 100644--- a/apps/mobile/react-native.config.js+++ b/apps/mobile/react-native.config.js@@ -1,6 +1,24 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/const fs = require("fs");const path = require("path");-const { computeHash, ALL_LIBRARIES } = require("./android/scripts/build-prebuilt-aars");+const { findPrebuiltAars } = require("./android/scripts/build-prebuilt-aars");const isGithubRelease = false;const config = {@@ -9,48 +27,29 @@ const config = {if (!config.dependencies) config.dependencies = {};-const isBuildingPrebuilt = process.env.BUILDING_PREBUILT_AARS === "true";-const disabledMarker = path.join(__dirname, "android", "build", "generated", "autolinking", ".prebuilt-disabled");-const isPrebuiltDisabled = fs.existsSync(disabledMarker) || process.env.USE_PREBUILT_AARS === "false";-const prebuiltDir = path.join(__dirname, "android", ".prebuilt-aars");+const prebuiltState = path.join(+ __dirname,+ "android",+ "build",+ "generated",+ "autolinking",+ ".prebuilt-aars.state"+);+const isPrebuiltDisabled =+ process.env.BUILDING_PREBUILT_AARS === "true" ||+ process.env.USE_PREBUILT_AARS === "false" ||+ (fs.existsSync(prebuiltState) &&+ fs.readFileSync(prebuiltState, "utf8") === "disabled");-function hasPrebuiltAars(libName) {- if (!fs.existsSync(prebuiltDir)) return false;- try {- const hash = computeHash(libName);- const libConfig = ALL_LIBRARIES[libName] || { filePrefix: libName.replace(/^@/, "").replace(/\//g, "-") };- const debugAar = path.join(prebuiltDir, `${libConfig.filePrefix}-debug-${hash}.aar`);- const releaseAar = path.join(prebuiltDir, `${libConfig.filePrefix}-release-${hash}.aar`);- return fs.existsSync(debugAar) && fs.existsSync(releaseAar);- } catch (e) {- return false;- }-}--// Configured prebuilt libraries to check-const CONFIGURED_PREBUILT_LIBS = [- "react-native-quick-sqlite",- "react-native-fast-openpgp",- "react-native-screens",- "react-native-gesture-handler",- "react-native-mmkv-storage",- "react-native-nitro-modules",- "react-native-nitro-cloud-uploader",- "react-native-worklets",- "react-native-reanimated"-];--if (!isBuildingPrebuilt && !isPrebuiltDisabled) {- for (const lib of CONFIGURED_PREBUILT_LIBS) {- if (hasPrebuiltAars(lib)) {- config.dependencies[lib] = {- ...(config.dependencies[lib] || {}),- platforms: {- ...((config.dependencies[lib] && config.dependencies[lib].platforms) || {}),- android: null+if (!isPrebuiltDisabled) {+ for (const lib of Object.keys(findPrebuiltAars())) {+ config.dependencies[lib] = {+ platforms: {+ android: {+ dependencyConfiguration: "prebuiltAar"}- };- }+ }+ };}}