diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index 82dd4ccb0..eb175e9b2 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -63,6 +63,12 @@ ReactNativeDeviceUtils.initEventListeners(); const { launchType, deepLink } = await ReactNativeDeviceUtils.getLaunchOptions(); const startupTime = await ReactNativeDeviceUtils.getStartupTime(); +const isFirstLaunch = ReactNativeDeviceUtils.isFirstLaunch(); +const isFirstAppVersionLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); +if (process.env.BUNDLE_VERSION) { + ReactNativeDeviceUtils.initFirstLaunchForBundle(process.env.BUNDLE_VERSION); +} +const isFirstBundleLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(); // Claim a startup stage exactly once across runtimes. const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent( @@ -74,6 +80,51 @@ const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent( Consumers own key namespaces and decide what to do with each result. Store values are native copies, not retained JS objects. +### First launch in shared code + +The following entry point works in React Native, Web, Electron renderers, +and extension pages. Call `initFirstLaunch` once at app startup, then read +the cached booleans synchronously anywhere: + +```ts +import { + initFirstLaunch, + isFirstLaunch, + isFirstLaunchForCurrentAppVersion, + isFirstLaunchForCurrentBundle, + resetFirstLaunch, +} from '@onekeyfe/react-native-device-utils/first-launch'; + +// Call once at app startup. On Web/Desktop/Extension, pass host-sampled +// `isLegacyInstall` / `legacyAppVersion` if upgrading from versions before this API. +initFirstLaunch({ + appVersion, + bundleVersion, + isLegacyInstall, +}); + +// Pure in-memory reads during the current launch. +const firstLaunch = isFirstLaunch(); +const firstAppVersionLaunch = isFirstLaunchForCurrentAppVersion(); +const firstBundleLaunch = isFirstLaunchForCurrentBundle(); + +// Optional: clear persisted files/keys AND in-memory cache (e.g. on Reset App before JS restart). +resetFirstLaunch(); +``` + +On iOS and Android, initialize the pure native singleton early in +`AppDelegate.didFinishLaunchingWithOptions` (`OneKeyDeviceUtilsFirstLaunch` via +`initializeWithOptions:` / `hasPersistedStateNumber`) or `Application.onCreate()` +(`DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... })`) so +host-specific legacy upgrade detection stays in the app and runs before React Native starts. + +Persisted state is stored as 3 independent plain-text entries (`launched`, +`app_ver`, `bundle_ver` under `1k_first_launch/` on native; `1k_fl_launched`, +`1k_fl_app_ver`, `1k_fl_bundle_ver` in `localStorage` on Web/Desktop/Extension), +so storage never grows and requires no cleanup. Rolling back to a version lower +than the recorded highest version returns `false`. Call from an extension-owned +UI page; an MV3 service worker returns `false`. + ## API | Method | Result | Platforms | Description | @@ -81,6 +132,11 @@ values are native copies, not retained JS objects. | `initEventListeners()` | `void` | iOS, Android | Registers native listeners; call once at startup. | | `getLaunchOptions()` / `clearLaunchOptions()` | `Promise` / `Promise` | iOS, Android | Read or consume the app's launch type and optional deep link. | | `getStartupTime()` | `Promise` | iOS, Android | Native startup timestamp. | +| `isFirstLaunch()` | `boolean` | iOS, Android | Synchronous first launch of the local installation, with a stable result for the native process. | +| `isFirstLaunchForCurrentAppVersion()` | `boolean` | iOS, Android | First launch of a native release version higher than any previously launched version. | +| `initFirstLaunchForBundle(bundleVersion)` | `void` | iOS, Android | Records the executing bundle at JS startup / OTA reload as the active bundle identity. | +| `isFirstLaunchForCurrentBundle(bundleVersion?)` | `boolean` | iOS, Android | First launch of a bundle version higher than any previously launched bundle. | +| `resetFirstLaunch()` | `boolean` | iOS, Android | Clears persisted `1k_first_launch/` files and in-memory launch state; returns `false` if deletion fails. | | `getDeviceToken()` / `saveDeviceToken(token)` / `registerDeviceToken()` | `Promise` / `Promise` / `Promise` | iOS, Android | Push-token plumbing; host setup still owns registration. | | `getInMemoryValue(key)` / `setInMemoryValue(key, value)` / `removeInMemoryValue(key)` / `setInMemoryValueIfAbsent(key, value)` | `InMemoryValue \| undefined` / `void` / `boolean` / `boolean` | iOS, Android | Synchronous bounded primitive store. | | `getAndClearColdStartLocalNotification()` | `Promise` | iOS, Android | Returns local-notification JSON once; Android returns `""`. | diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt new file mode 100644 index 000000000..94581d142 --- /dev/null +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt @@ -0,0 +1,140 @@ +package com.margelo.nitro.reactnativedeviceutils + +import android.content.Context +import android.content.pm.PackageManager +import java.io.File + +/** + * Pure native process-wide singleton for first-launch tracking. + * Has no Nitro/JSI dependencies, so host apps can initialize it early in + * `Application.onCreate()` before React Native starts. + */ +object DeviceUtilsFirstLaunch { + private val lock = Any() + + @Volatile + private var history: FirstLaunchHistory? = null + + private fun baseDirectory(context: Context): File? { + val appContext = context.applicationContext ?: context + return appContext.noBackupFilesDir + } + + /** + * Returns true if the persisted launched marker already exists on disk. + */ + @JvmStatic + fun hasPersistedState(context: Context): Boolean { + val base = baseDirectory(context) ?: return false + return File(File(base, FirstLaunchHistory.DIRECTORY_NAME), FirstLaunchHistory.LAUNCHED_FILE_NAME).exists() + } + + /** + * Initializes the process-wide first-launch state. Subsequent calls are no-ops. + */ + @JvmStatic + @JvmOverloads + fun initialize( + context: Context, + isLegacyInstall: Boolean = false, + legacyAppVersion: String? = null, + ) { + initialize( + context = context, + isLegacyInstall = { isLegacyInstall }, + legacyAppVersion = { legacyAppVersion }, + ) + } + + /** + * Kotlin-friendly initializer whose legacy-detection lambdas are only evaluated + * when no persisted launched marker exists yet. + */ + fun initialize( + context: Context, + isLegacyInstall: () -> Boolean, + legacyAppVersion: () -> String? = { null }, + ) { + if (history != null) return + synchronized(lock) { + if (history != null) return + val appContext = context.applicationContext ?: context + val base = baseDirectory(appContext) ?: return + val versionName = try { + @Suppress("DEPRECATION") + appContext.packageManager.getPackageInfo(appContext.packageName, 0).versionName + } catch (_: PackageManager.NameNotFoundException) { + null + } catch (_: SecurityException) { + null + } + val persistedExists = + File(File(base, FirstLaunchHistory.DIRECTORY_NAME), FirstLaunchHistory.LAUNCHED_FILE_NAME).exists() + val hasPreviousLaunch = if (persistedExists) false else runCatching(isLegacyInstall).getOrDefault(false) + val previousVersion = if (persistedExists) null else runCatching(legacyAppVersion).getOrNull() + history = FirstLaunchHistory( + baseDirectory = base, + appVersion = versionName, + previousAppVersion = previousVersion, + hasPreviousLaunch = hasPreviousLaunch, + ) + } + } + + /** + * Deletes persisted first-launch files and clears in-memory state so a subsequent + * JS restart within the same native process observes a fresh launch. + * Returns true if persisted files were removed (or already absent), false on failure. + */ + @JvmStatic + fun reset(context: Context): Boolean { + synchronized(lock) { + val base = baseDirectory(context) ?: return false + val storeDir = File(base, FirstLaunchHistory.DIRECTORY_NAME) + if (storeDir.exists()) { + val deleted = try { + storeDir.deleteRecursively() && !storeDir.exists() + } catch (_: SecurityException) { + false + } + if (!deleted) { + return false + } + } + history = null + return true + } + } + + internal fun isFirstLaunch(fallbackContext: Context? = null): Boolean = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.isFirstLaunch ?: false + } + + internal fun isFirstLaunchForCurrentAppVersion(fallbackContext: Context? = null): Boolean = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.isFirstLaunchForCurrentAppVersion ?: false + } + + internal fun initForBundle( + bundleVersion: String, + fallbackContext: Context? = null, + ) = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.initForBundle(bundleVersion) + } + + internal fun isFirstLaunchForBundle( + bundleVersion: String?, + fallbackContext: Context? = null, + ): Boolean = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.isFirstLaunchForBundle(bundleVersion) ?: false + } + + private fun ensureInitializedLocked(fallbackContext: Context?) { + if (history == null && fallbackContext != null) { + initialize(fallbackContext) + } + } +} diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt new file mode 100644 index 000000000..ffdaeffa0 --- /dev/null +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt @@ -0,0 +1,207 @@ +package com.margelo.nitro.reactnativedeviceutils + +import java.io.File +import java.io.FileOutputStream +import java.io.IOException + +internal class FirstLaunchHistory( + baseDirectory: File, + appVersion: String?, + previousAppVersion: String?, + hasPreviousLaunch: Boolean, +) { + val isFirstLaunch: Boolean + val isFirstLaunchForCurrentAppVersion: Boolean + private val storeDirectory = File(baseDirectory, DIRECTORY_NAME) + private val bundleResults = mutableMapOf() + private var currentBundleVersion: String? = null + + init { + val launchedFile = File(storeDirectory, LAUNCHED_FILE_NAME) + val launchedExists = launchedFile.exists() + val legacyBaseline = if (launchedExists) null else validatedVersion(previousAppVersion) + val validCurrent = validatedVersion(appVersion) + val appVerFile = File(storeDirectory, APP_VERSION_FILE_NAME) + + // Seed or evaluate app_ver BEFORE writing `launched` so an interrupted + // startup never loses the legacy app-version baseline. + isFirstLaunchForCurrentAppVersion = if (validCurrent != null) { + evaluateVersionFile( + file = appVerFile, + currentVersion = validCurrent, + legacyBaseline = legacyBaseline, + ) + } else { + if (legacyBaseline != null && !appVerFile.exists()) { + writeString(appVerFile, legacyBaseline) + } + false + } + + isFirstLaunch = if (launchedExists) { + false + } else { + val wrote = writeString(launchedFile, "1") + wrote && !hasPreviousLaunch + } + } + + @Synchronized + fun initForBundle(bundleVersion: String) { + val validBundle = validatedVersion(bundleVersion) + currentBundleVersion = validBundle + if (validBundle != null) { + resolveBundle(validBundle) + } + } + + @Synchronized + fun isFirstLaunchForBundle(bundleVersion: String?): Boolean { + if (bundleVersion == null) { + return currentBundleVersion?.let { bundleResults[it] } ?: false + } + val validBundle = validatedVersion(bundleVersion) ?: return false + return resolveBundle(validBundle) + } + + private fun resolveBundle(validBundle: String): Boolean { + bundleResults[validBundle]?.let { + return it + } + val result = evaluateVersionFile( + file = File(storeDirectory, BUNDLE_VERSION_FILE_NAME), + currentVersion = validBundle, + legacyBaseline = null, + ) + bundleResults[validBundle] = result + return result + } + + private fun evaluateVersionFile( + file: File, + currentVersion: String, + legacyBaseline: String?, + ): Boolean { + val existing: String? = if (file.exists()) { + val raw = try { + if (!file.isFile) return false + file.readText(Charsets.UTF_8) + } catch (_: IOException) { + return false + } catch (_: SecurityException) { + return false + } + validatedVersion(raw) ?: return false + } else { + null + } + + val baseline = existing ?: legacyBaseline + val isHigher = baseline == null || compareVersions(currentVersion, baseline) > 0 + if (isHigher) { + return writeString(file, currentVersion) + } + if (existing == null && legacyBaseline != null) { + writeString(file, legacyBaseline) + } + return false + } + + private fun writeString(target: File, value: String): Boolean { + var temp: File? = null + return try { + if (!storeDirectory.exists() && !storeDirectory.mkdirs() && !storeDirectory.isDirectory) { + false + } else if (!storeDirectory.isDirectory) { + false + } else { + temp = File.createTempFile("${target.name}.", ".tmp", storeDirectory) + FileOutputStream(temp).use { fos -> + fos.write(value.toByteArray(Charsets.UTF_8)) + fos.fd.sync() + } + if (temp.renameTo(target)) { + temp = null + true + } else { + false + } + } + } catch (_: IOException) { + false + } catch (_: SecurityException) { + false + } finally { + temp?.delete() + } + } + + companion object { + internal const val DIRECTORY_NAME = "1k_first_launch" + internal const val LAUNCHED_FILE_NAME = "launched" + internal const val APP_VERSION_FILE_NAME = "app_ver" + internal const val BUNDLE_VERSION_FILE_NAME = "bundle_ver" + + private val VERSION_REGEX = + Regex("""^[0-9]+(?:\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$""") + + internal fun validatedVersion(version: String?): String? { + if (version == null || version.length !in 1..120) return null + if (!VERSION_REGEX.matches(version)) return null + return version + } + + internal fun compareVersions(a: String, b: String): Int { + fun stripBuild(v: String): String { + val idx = v.indexOf('+') + return if (idx >= 0) v.substring(0, idx) else v + } + fun splitPre(v: String): Pair { + val idx = v.indexOf('-') + return if (idx >= 0) v.substring(0, idx) to v.substring(idx + 1) else v to null + } + fun isDigits(s: String): Boolean = s.isNotEmpty() && s.all { it in '0'..'9' } + fun compareUnsigned(lhs: String, rhs: String): Int { + val normA = lhs.trimStart('0').ifEmpty { "0" } + val normB = rhs.trimStart('0').ifEmpty { "0" } + if (normA.length != normB.length) return if (normA.length < normB.length) -1 else 1 + return normA.compareTo(normB) + } + fun compareIdent(lhs: String, rhs: String): Int { + val aNum = isDigits(lhs) + val bNum = isDigits(rhs) + if (aNum && bNum) return compareUnsigned(lhs, rhs) + if (aNum != bNum) return if (aNum) -1 else 1 + return lhs.compareTo(rhs) + } + + val (mainA, preA) = splitPre(stripBuild(a)) + val (mainB, preB) = splitPre(stripBuild(b)) + val segA = mainA.split('.') + val segB = mainB.split('.') + val maxLen = maxOf(segA.size, segB.size) + + for (i in 0 until maxLen) { + val partA = if (i < segA.size) segA[i] else "0" + val partB = if (i < segB.size) segB[i] else "0" + val cmp = compareIdent(partA, partB) + if (cmp != 0) return cmp + } + + if (preA == null && preB == null) return 0 + if (preA == null) return 1 + if (preB == null) return -1 + + val preSegA = preA.split('.') + val preSegB = preB.split('.') + val maxPre = maxOf(preSegA.size, preSegB.size) + for (i in 0 until maxPre) { + if (i >= preSegA.size) return -1 + if (i >= preSegB.size) return 1 + val cmp = compareIdent(preSegA[i], preSegB[i]) + if (cmp != 0) return cmp + } + return 0 + } + } +} diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt index 4bf72f214..3aa463960 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt @@ -46,6 +46,24 @@ private data class NavigationBarAppearance( @DoNotStrip class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEventListener { + override fun isFirstLaunch(): Boolean = + DeviceUtilsFirstLaunch.isFirstLaunch(NitroModules.applicationContext) + + override fun isFirstLaunchForCurrentAppVersion(): Boolean = + DeviceUtilsFirstLaunch.isFirstLaunchForCurrentAppVersion(NitroModules.applicationContext) + + override fun initFirstLaunchForBundle(bundleVersion: String) { + DeviceUtilsFirstLaunch.initForBundle(bundleVersion, NitroModules.applicationContext) + } + + override fun isFirstLaunchForCurrentBundle(bundleVersion: String?): Boolean = + DeviceUtilsFirstLaunch.isFirstLaunchForBundle(bundleVersion, NitroModules.applicationContext) + + override fun resetFirstLaunch(): Boolean { + val context = NitroModules.applicationContext ?: return false + return DeviceUtilsFirstLaunch.reset(context) + } + override fun getInMemoryValue(key: String): InMemoryValue? = InMemoryStore.get(key) override fun setInMemoryValue(key: String, value: InMemoryValue) = InMemoryStore.set(key, value) diff --git a/native-modules/react-native-device-utils/babel.config.js b/native-modules/react-native-device-utils/babel.config.js index 7d6b2cd2e..98655448c 100644 --- a/native-modules/react-native-device-utils/babel.config.js +++ b/native-modules/react-native-device-utils/babel.config.js @@ -1,13 +1,3 @@ module.exports = { presets: ['@react-native/babel-preset'], - plugins: [ - [ - 'module-resolver', - { - alias: { - 'react-native-device-utils': './src/index', - }, - }, - ], - ], }; diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index 87b95d9a7..b658c6b98 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -1,3 +1,55 @@ +# DeviceUtils: first launch + +## Status and scope + +The iOS and Android Nitro first-launch getters return synchronous booleans. Results are +shared by the main and background JavaScript runtimes and stay fixed for each +identity across JS reloads and foreground transitions within the same process. +Background process starts that run the normal native app bootstrap also count. + +| Method | First launch identity | +| --- | --- | +| `isFirstLaunch()` | The local app installation. | +| `isFirstLaunchForCurrentAppVersion()` | The native app's release version (`CFBundleShortVersionString` on iOS, `versionName` on Android). Build number changes alone keep the same identity. | +| `initFirstLaunchForBundle(bundleVersion: string)` | Activates and records the executing JS bundle version at JS startup and after an OTA reload. Passing an invalid version clears the active bundle identity without writing disk state. Assumes all live JS runtimes in the process are version-locked and restarted together on OTA bundle switches. | +| `isFirstLaunchForCurrentBundle(bundleVersion?: string)` | Returns whether the active bundle (when omitted) or explicitly supplied bundle version is higher than any previously launched bundle. Does not change the active bundle identity. | + +## Lifecycle, persistence, and platform behavior + +Persisted state is stored as **three independent plain-text entries** (no JSON container), so storage size is constant, no cleanup API is needed, and updating one dimension never clobbers or corrupts the others: + +| Dimension | Native file (inside `1k_first_launch/`) | Web `localStorage` key | Value | +| --- | --- | --- | --- | +| Installation launched | `launched` | `1k_fl_launched` | `"1"` | +| Highest app version | `app_ver` | `1k_fl_app_ver` | e.g. `"6.5.0"` | +| Highest bundle version | `bundle_ver` | `1k_fl_bundle_ver` | e.g. `"1000"` | + +On each launch, startup reads the persisted entries, computes and freezes the current-launch booleans in memory, and atomically writes any newly established or higher value. All getters during that launch return the frozen in-memory booleans and never re-evaluate against the updated disk values. + +| Platform | Initialization | Storage | Legacy-install evidence | +| --- | --- | --- | --- | +| iOS | Host calls `DeviceUtilsFirstLaunch.initialize(options:)` (or dynamically via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `initializeWithOptions:`) in `AppDelegate.didFinishLaunchingWithOptions` before initializing app storage. Lazy fallback initializes with `isLegacyInstall = false`. | `Library/Application Support/1k_first_launch/` (`isExcludedFromBackup = true`) | Owned by the host app. Use `hasPersistedState()` (or `hasPersistedStateNumber` returning `NSNumber` for `perform(_:)`) to skip legacy checks once `launched` exists. | +| Android | Host calls `DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... }, legacyAppVersion = { ... })` in `Application.onCreate()`. Lazy fallback initializes with `isLegacyInstall = false`. | `context.noBackupFilesDir/1k_first_launch/` (immune to Clear Cache and Auto Backup) | Owned by the host app (lambdas are only invoked when `launched` does not exist yet). | +| Web / Desktop / Extension | Host calls `initFirstLaunch({ appVersion, bundleVersion, isLegacyInstall, legacyAppVersion })` once at UI startup before reading getters. | `localStorage` keys `1k_fl_launched`, `1k_fl_app_ver`, `1k_fl_bundle_ver` | Owned by the host app (e.g. sampled in an HTML `` script or Electron preload before app JS writes to storage). | + +`resetFirstLaunch(): boolean` (and native `DeviceUtilsFirstLaunch.reset()` on iOS / `DeviceUtilsFirstLaunch.reset(context)` on Android) removes the `1k_first_launch/` directory (or the 3 `localStorage` keys) **and clears the in-memory launch cache**, returning `true` when deletion succeeds (including already-absent entries) and `false` on failure so callers can retry before soft-restarting JS. + +Version strings must have a numeric dot-separated core with optional SemVer pre-release (`-...`) and build metadata (`+...`) suffixes (1–120 ASCII chars, e.g. `6.5.0`, `6.5.0-beta.1`, `1000`). Non-numeric cores such as `v6.5.0` are rejected. Version comparison compares numeric dot-separated segments by integer value (e.g. `6.10.0 > 6.5.0`, `1000 > 999`) with SemVer pre-release ordering (`6.5.0 > 6.5.0-beta.1`). A version strictly higher than the persisted highest version returns `true` for the current launch and advances the persisted entry. Rolling back to or running any version lower than or equal to the persisted highest version returns `false` and keeps the higher value persisted. + +Missing startup initialization, unavailable or corrupted entries (empty or invalid stored version strings), invalid identifiers, and write failures fail closed for the affected entry and return `false` without overwriting the damaged entry. Zero-argument getters remain bound to the startup identities and are unaffected by later explicit version lookups. On Web/Desktop/Extension, getters called before `initFirstLaunch(...)` return `false` without touching storage. Because synchronous Web Storage has no cross-document lock, simultaneous first loads across two separate tabs may both observe an absent key. + +## Web, desktop renderer, and extension pages + +The `@onekeyfe/react-native-device-utils/first-launch` entry point exposes: + +- `initFirstLaunch(options?: { appVersion?: string; bundleVersion?: string; isLegacyInstall?: boolean; legacyAppVersion?: string }): void` +- `isFirstLaunch(): boolean` +- `isFirstLaunchForCurrentAppVersion(appVersion?: string): boolean` +- `isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean` +- `resetFirstLaunch(): boolean` + +React Native delegates to `ReactNativeDeviceUtils`. Web documents, Electron renderers, and extension-owned pages share `src/firstLaunch.web.ts` backed by `window.localStorage`. After `initFirstLaunch(...)` runs at startup, getters can be called with zero arguments to read the cached launch results. Server runtimes and MV3 service workers have no `window.localStorage` and return `false`. + # DeviceUtils: InMemoryStore contract ## Status and scope diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift new file mode 100644 index 000000000..244c0c80d --- /dev/null +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -0,0 +1,322 @@ +import Foundation + +@objc(OneKeyDeviceUtilsFirstLaunch) +public final class DeviceUtilsFirstLaunch: NSObject { + private static let lock = NSLock() + private static var history: FirstLaunchHistory? + + /// Returns true if the persisted launched marker already exists on disk. + public static func hasPersistedState() -> Bool { + guard let directory = defaultDirectory() else { return false } + let launchedURL = directory + .appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) + .appendingPathComponent(FirstLaunchHistory.launchedFileName) + return FileManager.default.fileExists(atPath: launchedURL.path) + } + + /// Object-returning variant of `hasPersistedState()` safe for dynamic invocation + /// via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `perform(_:)`. + @objc(hasPersistedStateNumber) + public static func hasPersistedStateNumber() -> NSNumber { + NSNumber(value: hasPersistedState()) + } + + /// Initializes the process-wide first-launch state from the host app (e.g. AppDelegate). + /// Accepts an Objective-C `NSDictionary` so Swift hosts can invoke it dynamically via + /// `NSClassFromString` + `perform(_:with:)` without importing Nitro C++ headers. + /// Supported keys: + /// - `"isLegacyInstall"`: `NSNumber` / `Bool` (default `false`) + /// - `"legacyAppVersion"`: `NSString` / `String` (optional) + @objc(initializeWithOptions:) + public static func initialize(options: NSDictionary?) { + let isLegacyInstall = (options?["isLegacyInstall"] as? NSNumber)?.boolValue ?? false + let legacyAppVersion = options?["legacyAppVersion"] as? String + initialize(isLegacyInstall: isLegacyInstall, legacyAppVersion: legacyAppVersion) + } + + /// Swift-friendly initializer for hosts that can import this module directly. + public static func initialize( + isLegacyInstall: Bool = false, + legacyAppVersion: String? = nil + ) { + lock.lock() + defer { lock.unlock() } + guard history == nil else { return } + guard let directory = defaultDirectory() else { return } + history = FirstLaunchHistory( + baseDirectory: directory, + appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, + previousAppVersion: legacyAppVersion, + hasPreviousLaunch: isLegacyInstall + ) + } + + /// Deletes persisted first-launch files and clears in-memory state so a subsequent + /// JS restart within the same native process observes a fresh launch. + /// Returns true if persisted files were removed (or already absent), false on failure. + @objc @discardableResult public static func reset() -> Bool { + lock.lock() + defer { lock.unlock() } + guard let directory = defaultDirectory() else { return false } + let storeDir = directory.appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) + if FileManager.default.fileExists(atPath: storeDir.path) { + do { + try FileManager.default.removeItem(at: storeDir) + } catch { + return false + } + } + history = nil + return true + } + + static var value: Bool { + withHistory(default: false) { $0.isFirstLaunch } + } + + static var forCurrentAppVersion: Bool { + withHistory(default: false) { $0.isFirstLaunchForCurrentAppVersion } + } + + static func initForBundle(_ bundleVersion: String) { + withHistory(default: ()) { $0.initForBundle(bundleVersion) } + } + + static func forBundle(_ bundleVersion: String?) -> Bool { + withHistory(default: false) { $0.isFirstLaunchForBundle(bundleVersion) } + } + + private static func defaultDirectory() -> URL? { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first + } + + private static func withHistory(default fallback: Result, _ read: (FirstLaunchHistory) -> Result) -> Result { + lock.lock() + defer { lock.unlock() } + if let existing = history { + return read(existing) + } + guard let directory = defaultDirectory() else { + return fallback + } + let created = FirstLaunchHistory( + baseDirectory: directory, + appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, + previousAppVersion: nil, + hasPreviousLaunch: false + ) + history = created + return read(created) + } +} + +final class FirstLaunchHistory { + static let directoryName = "1k_first_launch" + static let launchedFileName = "launched" + static let appVersionFileName = "app_ver" + static let bundleVersionFileName = "bundle_ver" + + let isFirstLaunch: Bool + let isFirstLaunchForCurrentAppVersion: Bool + private let storeDirectory: URL + private var bundleResults: [String: Bool] = [:] + private var currentBundleVersion: String? + + init(baseDirectory: URL, appVersion: String?, previousAppVersion: String?, hasPreviousLaunch: Bool) { + let dir = baseDirectory.appendingPathComponent(Self.directoryName, isDirectory: true) + storeDirectory = dir + + let launchedURL = dir.appendingPathComponent(Self.launchedFileName) + let launchedExists = FileManager.default.fileExists(atPath: launchedURL.path) + let legacyBaseline = launchedExists ? nil : Self.validatedVersion(previousAppVersion) + + // Seed or evaluate app_ver BEFORE writing `launched` so an interrupted + // startup never loses the legacy app-version baseline. + let appVerURL = dir.appendingPathComponent(Self.appVersionFileName) + if let validCurrent = Self.validatedVersion(appVersion) { + isFirstLaunchForCurrentAppVersion = Self.evaluateVersionFile( + at: appVerURL, + directory: dir, + currentVersion: validCurrent, + legacyBaseline: legacyBaseline + ) + } else { + if let legacyBaseline, !FileManager.default.fileExists(atPath: appVerURL.path) { + _ = Self.writeString(legacyBaseline, to: appVerURL, directory: dir) + } + isFirstLaunchForCurrentAppVersion = false + } + + if launchedExists { + isFirstLaunch = false + } else { + let wrote = Self.writeString("1", to: launchedURL, directory: dir) + isFirstLaunch = wrote && !hasPreviousLaunch + } + } + + func initForBundle(_ bundleVersion: String) { + let validBundle = Self.validatedVersion(bundleVersion) + currentBundleVersion = validBundle + guard let validBundle else { + return + } + _ = resolveBundle(validBundle) + } + + func isFirstLaunchForBundle(_ bundleVersion: String?) -> Bool { + guard let bundleVersion else { + return currentBundleVersion.flatMap { bundleResults[$0] } ?? false + } + guard let validBundle = Self.validatedVersion(bundleVersion) else { + return false + } + return resolveBundle(validBundle) + } + + private func resolveBundle(_ validBundle: String) -> Bool { + if let cached = bundleResults[validBundle] { + return cached + } + let result = Self.evaluateVersionFile( + at: storeDirectory.appendingPathComponent(Self.bundleVersionFileName), + directory: storeDirectory, + currentVersion: validBundle, + legacyBaseline: nil + ) + bundleResults[validBundle] = result + return result + } + + private static func evaluateVersionFile( + at fileURL: URL, + directory: URL, + currentVersion: String, + legacyBaseline: String? + ) -> Bool { + let exists = FileManager.default.fileExists(atPath: fileURL.path) + let existing: String? + if exists { + guard let raw = try? String(contentsOf: fileURL, encoding: .utf8), + let valid = validatedVersion(raw) else { + // Corrupted file: fail closed without overwriting. + return false + } + existing = valid + } else { + existing = nil + } + + let baseline = existing ?? legacyBaseline + let isHigher = baseline == nil || compareVersions(currentVersion, baseline!) > 0 + if isHigher { + return writeString(currentVersion, to: fileURL, directory: directory) + } + if existing == nil, let baseline { + _ = writeString(baseline, to: fileURL, directory: directory) + } + return false + } + + private static func writeString(_ value: String, to url: URL, directory: URL) -> Bool { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + var dirURL = directory + var values = URLResourceValues() + values.isExcludedFromBackup = true + try dirURL.setResourceValues(values) + try Data(value.utf8).write(to: url, options: .atomic) + return true + } catch { + return false + } + } + + static func compareVersions(_ a: String, _ b: String) -> Int { + func stripBuild(_ v: String) -> Substring { + if let plus = v.firstIndex(of: "+") { + return v[.. (Substring, Substring?) { + if let dash = v.firstIndex(of: "-") { + return (v[.. Bool { + !s.isEmpty && s.utf8.allSatisfy { $0 >= 48 && $0 <= 57 } + } + func compareUnsigned(_ lhs: Substring, _ rhs: Substring) -> Int { + let normA = lhs.drop { $0 == "0" } + let normB = rhs.drop { $0 == "0" } + if normA.count != normB.count { + return normA.count < normB.count ? -1 : 1 + } + if normA == normB { return 0 } + return normA < normB ? -1 : 1 + } + func compareIdent(_ lhs: Substring, _ rhs: Substring) -> Int { + let aNum = isDigits(lhs) + let bNum = isDigits(rhs) + if aNum && bNum { + return compareUnsigned(lhs, rhs) + } + if aNum != bNum { + return aNum ? -1 : 1 + } + if lhs == rhs { return 0 } + return lhs < rhs ? -1 : 1 + } + + let (mainA, preA) = splitPre(stripBuild(a)) + let (mainB, preB) = splitPre(stripBuild(b)) + let segA = mainA.split(separator: ".", omittingEmptySubsequences: false) + let segB = mainB.split(separator: ".", omittingEmptySubsequences: false) + let maxLen = max(segA.count, segB.count) + let zero: Substring = "0" + + for i in 0..= preSegA.count { return -1 } + if i >= preSegB.count { return 1 } + let cmp = compareIdent(preSegA[i], preSegB[i]) + if cmp != 0 { return cmp } + } + return 0 + } + } + + static func validatedVersion(_ version: String?) -> String? { + guard let version, (1...120).contains(version.utf8.count) else { return nil } + let fullRange = NSRange(version.startIndex.. Bool { + DeviceUtilsFirstLaunch.value + } + + func isFirstLaunchForCurrentAppVersion() throws -> Bool { + DeviceUtilsFirstLaunch.forCurrentAppVersion + } + + func initFirstLaunchForBundle(bundleVersion: String) throws { + DeviceUtilsFirstLaunch.initForBundle(bundleVersion) + } + + func isFirstLaunchForCurrentBundle(bundleVersion: String?) throws -> Bool { + DeviceUtilsFirstLaunch.forBundle(bundleVersion) + } + + func resetFirstLaunch() throws -> Bool { + DeviceUtilsFirstLaunch.reset() + } + override init() { injectedInterfaceOrientationObserver = nil super.init() diff --git a/native-modules/react-native-device-utils/package.json b/native-modules/react-native-device-utils/package.json index 92c1ec621..8d4f166f1 100644 --- a/native-modules/react-native-device-utils/package.json +++ b/native-modules/react-native-device-utils/package.json @@ -10,6 +10,21 @@ "types": "./lib/typescript/src/index.d.ts", "default": "./lib/module/index.js" }, + "./first-launch": { + "browser": { + "types": "./lib/typescript/src/firstLaunch.web.d.ts", + "source": "./src/firstLaunch.web.ts", + "default": "./lib/module/firstLaunch.web.js" + }, + "react-native": { + "types": "./lib/typescript/src/firstLaunch.native.d.ts", + "source": "./src/firstLaunch.native.ts", + "default": "./lib/module/firstLaunch.native.js" + }, + "types": "./lib/typescript/src/firstLaunch.web.d.ts", + "source": "./src/firstLaunch.web.ts", + "default": "./lib/module/firstLaunch.web.js" + }, "./package.json": "./package.json" }, "files": [ diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index 212e70934..08d39294e 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -152,6 +152,16 @@ export interface ReactNativeDeviceUtils saveDeviceToken(token: string): Promise; registerDeviceToken(): Promise; getStartupTime(): Promise; + /** Whether the current native process is the first launch of this local installation. */ + isFirstLaunch(): boolean; + /** First launch of a native release version higher than any previously launched version. */ + isFirstLaunchForCurrentAppVersion(): boolean; + /** Records the executing bundle version at JS startup / OTA reload as the active bundle identity. */ + initFirstLaunchForBundle(bundleVersion: string): void; + /** First launch of a bundle version higher than any previously launched bundle. */ + isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean; + /** Clears persisted first-launch files and in-memory state (e.g. on Reset App). Returns false if deletion fails. */ + resetFirstLaunch(): boolean; // Process-owned primitive Map, shared by all runtimes and never persisted. getInMemoryValue(key: string): InMemoryValue | undefined; setInMemoryValue(key: string, value: InMemoryValue): void; diff --git a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts new file mode 100644 index 000000000..73e9a58bc --- /dev/null +++ b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts @@ -0,0 +1,237 @@ +const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'); + +function openDocument( + localStorage?: Pick +) { + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: localStorage ? { localStorage } : undefined, + }); + return loadModule(); +} + +function loadModule() { + let result!: typeof import('../firstLaunch.web'); + jest.isolateModules(() => { + result = jest.requireActual( + '../firstLaunch.web' + ); + }); + return result; +} + +function createStorage(initialEntries?: Record) { + const values = new Map( + initialEntries ? Object.entries(initialEntries) : [] + ); + return { + get length() { + return values.size; + }, + getItem: jest.fn((key: string) => values.get(key) ?? null), + setItem: jest.fn((key: string, value: string) => { + values.set(key, value); + }), + removeItem: jest.fn((key: string) => { + values.delete(key); + }), + }; +} + +afterEach(() => { + if (originalWindow) { + Object.defineProperty(globalThis, 'window', originalWindow); + } else { + Reflect.deleteProperty(globalThis, 'window'); + } +}); + +it('records installation, highest app version, and highest bundle version as 3 independent keys', () => { + const storage = createStorage(); + const startup = openDocument(storage); + + startup.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(storage.setItem).toHaveBeenCalledWith('1k_fl_launched', '1'); + expect(storage.setItem).toHaveBeenCalledWith('1k_fl_app_ver', '6.5.0'); + expect(storage.setItem).toHaveBeenCalledWith('1k_fl_bundle_ver', '1000'); + expect(startup.isFirstLaunch()).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle()).toBe(true); + // Repeated calls during the same launch stay stable and read from memory. + expect(startup.isFirstLaunch()).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle('1000')).toBe(true); + + // Explicit lookup of another identity must not overwrite startup zero-arg results or evict startup cache. + expect(startup.isFirstLaunchForCurrentAppVersion('6.6.0')).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle('999')).toBe(false); + expect(startup.isFirstLaunchForCurrentBundle()).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle('1000')).toBe(true); + + const reload = openDocument(storage); + reload.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1000' }); + expect(reload.isFirstLaunch()).toBe(false); + expect(reload.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(reload.isFirstLaunchForCurrentBundle()).toBe(false); + + // Higher bundle only + const ota = openDocument(storage); + ota.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1001' }); + expect(ota.isFirstLaunch()).toBe(false); + expect(ota.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(ota.isFirstLaunchForCurrentBundle()).toBe(true); + + // Rollback to lower bundle returns false and preserves highest bundle version + const rollback = openDocument(storage); + rollback.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1000' }); + expect(rollback.isFirstLaunch()).toBe(false); + expect(rollback.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(rollback.isFirstLaunchForCurrentBundle()).toBe(false); + + // Upgrade app version (6.10.0 > 6.6.0 numerically) with same bundle + const upgrade = openDocument(storage); + upgrade.initFirstLaunch({ appVersion: '6.10.0', bundleVersion: '1001' }); + expect(upgrade.isFirstLaunch()).toBe(false); + expect(upgrade.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(upgrade.isFirstLaunchForCurrentBundle()).toBe(false); + + // Downgrade app version returns false + const downgrade = openDocument(storage); + downgrade.initFirstLaunch({ appVersion: '6.9.0', bundleVersion: '999' }); + expect(downgrade.isFirstLaunch()).toBe(false); + expect(downgrade.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(downgrade.isFirstLaunchForCurrentBundle()).toBe(false); +}); + +it('clears both persisted keys and in-memory state on resetFirstLaunch', () => { + const storage = createStorage(); + const doc = openDocument(storage); + + doc.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(doc.isFirstLaunch()).toBe(true); + + // Simulate normal restart -> false + const restarted = openDocument(storage); + restarted.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(restarted.isFirstLaunch()).toBe(false); + expect(restarted.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(restarted.isFirstLaunchForCurrentBundle()).toBe(false); + + // Reset in the same runtime (e.g. Reset App + JS soft restart) + expect(restarted.resetFirstLaunch()).toBe(true); + expect(restarted.isFirstLaunch()).toBe(false); + restarted.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(restarted.isFirstLaunch()).toBe(true); + expect(restarted.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(restarted.isFirstLaunchForCurrentBundle()).toBe(true); + + // Reset returns false when storage deletion fails and preserves in-memory state. + storage.removeItem.mockImplementationOnce(() => { + throw new Error('Remove failed'); + }); + expect(restarted.resetFirstLaunch()).toBe(false); + expect(restarted.isFirstLaunch()).toBe(true); +}); + +it('preserves legacyAppVersion even when appVersion is omitted during initFirstLaunch', () => { + const storage = createStorage(); + const doc = openDocument(storage); + doc.initFirstLaunch({ isLegacyInstall: true, legacyAppVersion: '6.5.0' }); + expect(doc.isFirstLaunch()).toBe(false); + expect(storage.getItem('1k_fl_app_ver')).toBe('6.5.0'); + + const next = openDocument(storage); + next.initFirstLaunch({ appVersion: '6.5.0' }); + expect(next.isFirstLaunch()).toBe(false); + expect(next.isFirstLaunchForCurrentAppVersion()).toBe(false); +}); + +it('does not touch storage before initFirstLaunch so legacy init is never consumed early', () => { + const storage = createStorage(); + const doc = openDocument(storage); + + expect(doc.isFirstLaunch()).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(false); + expect(doc.isFirstLaunchForCurrentBundle('1000')).toBe(false); + expect(storage.getItem).not.toHaveBeenCalled(); + expect(storage.setItem).not.toHaveBeenCalled(); + + doc.initFirstLaunch({ + appVersion: '6.5.0', + bundleVersion: '1000', + isLegacyInstall: true, + legacyAppVersion: '6.5.0', + }); + expect(doc.isFirstLaunch()).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(doc.isFirstLaunchForCurrentBundle()).toBe(true); +}); + +it('isolates corrupted keys without overwriting them or breaking healthy keys', () => { + const storage = createStorage({ + '1k_fl_launched': '1', + '1k_fl_app_ver': '6.6.0!', + '1k_fl_bundle_ver': '1000', + }); + const doc = openDocument(storage); + doc.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1001' }); + + expect(doc.isFirstLaunch()).toBe(false); + // Corrupted app_ver fails closed and is NOT overwritten + expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(storage.getItem('1k_fl_app_ver')).toBe('6.6.0!'); + // Healthy bundle_ver still works independently + expect(doc.isFirstLaunchForCurrentBundle()).toBe(true); + expect(storage.getItem('1k_fl_bundle_ver')).toBe('1001'); +}); + +it('validates numeric version core and handles prerelease comparisons accurately', () => { + const storage = createStorage(); + const doc = openDocument(storage); + doc.initFirstLaunch({ appVersion: 'v6.5.0', bundleVersion: '../1000' }); + expect(doc.isFirstLaunch()).toBe(true); + expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(doc.isFirstLaunchForCurrentBundle()).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion('v6.5.0')).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); + + expect(doc.compareVersions('6.10.0', '6.5.0')).toBeGreaterThan(0); + expect(doc.compareVersions('6.5.0', '6.5')).toBe(0); + expect(doc.compareVersions('6.5.0', '6.5.0-beta.1')).toBeGreaterThan(0); + expect(doc.compareVersions('6.5.0-beta.2', '6.5.0-beta.1')).toBeGreaterThan( + 0 + ); + expect(doc.compareVersions('1000', '999')).toBeGreaterThan(0); +}); + +it('returns false without browser storage and tolerates blocked writes', () => { + const server = openDocument(); + server.initFirstLaunch({ appVersion: '2.0', bundleVersion: '1000' }); + expect(server.isFirstLaunch()).toBe(false); + expect(server.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(server.isFirstLaunchForCurrentBundle()).toBe(false); + + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: { + get localStorage() { + throw new Error('Storage is blocked'); + }, + }, + }); + const blocked = loadModule(); + blocked.initFirstLaunch({ appVersion: '2.0', bundleVersion: '1000' }); + expect(blocked.isFirstLaunch()).toBe(false); + + const storage = createStorage(); + storage.setItem.mockImplementation(() => { + throw new Error('Storage is full'); + }); + const startup = openDocument(storage); + startup.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(startup.isFirstLaunch()).toBe(false); + expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(startup.isFirstLaunchForCurrentBundle()).toBe(false); +}); diff --git a/native-modules/react-native-device-utils/src/firstLaunch.native.ts b/native-modules/react-native-device-utils/src/firstLaunch.native.ts new file mode 100644 index 000000000..364d4d9d5 --- /dev/null +++ b/native-modules/react-native-device-utils/src/firstLaunch.native.ts @@ -0,0 +1,44 @@ +import { ReactNativeDeviceUtils } from './index'; + +export interface FirstLaunchInitOptions { + appVersion?: string; + bundleVersion?: string; + /** + * Used on Web/Desktop/Extension only; on iOS/Android pass legacy signals to + * the native `DeviceUtilsFirstLaunch.initialize(...)` singleton at app launch. + */ + isLegacyInstall?: boolean; + /** + * Used on Web/Desktop/Extension only; on iOS/Android pass legacy signals to + * the native `DeviceUtilsFirstLaunch.initialize(...)` singleton at app launch. + */ + legacyAppVersion?: string; +} + +export function initFirstLaunch(options?: FirstLaunchInitOptions): void { + ReactNativeDeviceUtils.isFirstLaunch(); + ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); + if (options?.bundleVersion !== undefined) { + ReactNativeDeviceUtils.initFirstLaunchForBundle(options.bundleVersion); + } +} + +export function isFirstLaunch(): boolean { + return ReactNativeDeviceUtils.isFirstLaunch(); +} + +export function isFirstLaunchForCurrentAppVersion( + _appVersion?: string +): boolean { + return ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); +} + +export function isFirstLaunchForCurrentBundle( + bundleVersion?: string +): boolean { + return ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(bundleVersion); +} + +export function resetFirstLaunch(): boolean { + return ReactNativeDeviceUtils.resetFirstLaunch(); +} diff --git a/native-modules/react-native-device-utils/src/firstLaunch.web.ts b/native-modules/react-native-device-utils/src/firstLaunch.web.ts new file mode 100644 index 000000000..3ce506871 --- /dev/null +++ b/native-modules/react-native-device-utils/src/firstLaunch.web.ts @@ -0,0 +1,332 @@ +export interface FirstLaunchInitOptions { + appVersion?: string; + bundleVersion?: string; + /** + * Host-provided signal indicating this storage area already existed + * in a legacy version before first-launch tracking was introduced. + * Ignored once persisted state already exists. + */ + isLegacyInstall?: boolean; + /** + * Optional previous app version known to the host from legacy state. + * Ignored once persisted state already exists. + */ + legacyAppVersion?: string; +} + +export const FIRST_LAUNCH_KEYS = { + launched: '1k_fl_launched', + appVersion: '1k_fl_app_ver', + bundleVersion: '1k_fl_bundle_ver', +} as const; + +const validVersionPattern = + /^[0-9]+(?:\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/; +const digitsOnly = /^[0-9]+$/; + +let initialized = false; +let cachedFirstLaunch = false; +let startupAppVersion: string | undefined; +let startupBundleVersion: string | undefined; +const cachedAppResults = new Map(); +const cachedBundleResults = new Map(); + +function isValidVersion(version?: unknown): version is string { + return ( + typeof version === 'string' && + version.length > 0 && + version.length <= 120 && + validVersionPattern.test(version) + ); +} + +function compareUnsignedIntStrings(a: string, b: string): number { + const normA = a.replace(/^0+/, '') || '0'; + const normB = b.replace(/^0+/, '') || '0'; + if (normA.length !== normB.length) { + return normA.length < normB.length ? -1 : 1; + } + if (normA === normB) { + return 0; + } + return normA < normB ? -1 : 1; +} + +function compareIdentifiers(a: string, b: string): number { + const aNum = digitsOnly.test(a); + const bNum = digitsOnly.test(b); + if (aNum && bNum) { + return compareUnsignedIntStrings(a, b); + } + if (aNum !== bNum) { + return aNum ? -1 : 1; + } + if (a === b) { + return 0; + } + return a < b ? -1 : 1; +} + +export function compareVersions(a: string, b: string): number { + const stripBuild = (v: string) => { + const plusIndex = v.indexOf('+'); + return plusIndex >= 0 ? v.slice(0, plusIndex) : v; + }; + const splitPre = (v: string): [string, string | null] => { + const dashIndex = v.indexOf('-'); + return dashIndex >= 0 + ? [v.slice(0, dashIndex), v.slice(dashIndex + 1)] + : [v, null]; + }; + + const [mainA, preA] = splitPre(stripBuild(a)); + const [mainB, preB] = splitPre(stripBuild(b)); + const segA = mainA.split('.'); + const segB = mainB.split('.'); + const maxLen = Math.max(segA.length, segB.length); + + for (let i = 0; i < maxLen; i += 1) { + const partA = segA[i] ?? '0'; + const partB = segB[i] ?? '0'; + const cmp = compareIdentifiers(partA, partB); + if (cmp !== 0) { + return cmp; + } + } + + if (preA === null && preB === null) { + return 0; + } + if (preA === null) { + return 1; + } + if (preB === null) { + return -1; + } + + const preSegA = preA.split('.'); + const preSegB = preB.split('.'); + const maxPreLen = Math.max(preSegA.length, preSegB.length); + for (let i = 0; i < maxPreLen; i += 1) { + if (i >= preSegA.length) { + return -1; + } + if (i >= preSegB.length) { + return 1; + } + const cmp = compareIdentifiers(preSegA[i]!, preSegB[i]!); + if (cmp !== 0) { + return cmp; + } + } + return 0; +} + +function getStorage(): Storage | null { + if (typeof window === 'undefined') { + return null; + } + try { + return window.localStorage ?? null; + } catch { + return null; + } +} + +function safeGet(storage: Storage, key: string): { ok: true; value: string | null } | { ok: false } { + try { + return { ok: true, value: storage.getItem(key) }; + } catch { + return { ok: false }; + } +} + +function safeSet(storage: Storage, key: string, value: string): boolean { + try { + storage.setItem(key, value); + return true; + } catch { + return false; + } +} + +function evaluateVersionKey( + storage: Storage, + key: string, + currentVersion: string, + legacyBaseline?: string +): boolean { + const existing = safeGet(storage, key); + if (!existing.ok) { + return false; + } + if (existing.value !== null && !isValidVersion(existing.value)) { + // Corrupted stored value: fail closed without overwriting. + return false; + } + const baseline = + existing.value ?? (isValidVersion(legacyBaseline) ? legacyBaseline : null); + const isHigher = + baseline === null || compareVersions(currentVersion, baseline) > 0; + if (isHigher) { + return safeSet(storage, key, currentVersion); + } + if (existing.value === null && baseline !== null) { + // Persist the legacy baseline so future launches don't need legacy input. + safeSet(storage, key, baseline); + } + return false; +} + +export function initFirstLaunch(options?: FirstLaunchInitOptions): void { + if (initialized) { + return; + } + initialized = true; + + const validAppVersion = isValidVersion(options?.appVersion) + ? options.appVersion + : undefined; + const validBundleVersion = isValidVersion(options?.bundleVersion) + ? options.bundleVersion + : undefined; + startupAppVersion = validAppVersion; + startupBundleVersion = validBundleVersion; + + const storage = getStorage(); + if (!storage) { + cachedFirstLaunch = false; + if (validAppVersion !== undefined) { + cachedAppResults.set(validAppVersion, false); + } + if (validBundleVersion !== undefined) { + cachedBundleResults.set(validBundleVersion, false); + } + return; + } + + const isLegacyInstall = options?.isLegacyInstall === true; + const launchedRead = safeGet(storage, FIRST_LAUNCH_KEYS.launched); + const isFreshStorage = launchedRead.ok && launchedRead.value === null; + const legacyBaseline = isFreshStorage ? options?.legacyAppVersion : undefined; + + // Seed or evaluate app_ver BEFORE writing `launched`, so a legacy baseline is + // never lost even when `appVersion` is omitted or startup is interrupted. + if (validAppVersion !== undefined) { + cachedAppResults.set( + validAppVersion, + evaluateVersionKey( + storage, + FIRST_LAUNCH_KEYS.appVersion, + validAppVersion, + legacyBaseline + ) + ); + } else if (isValidVersion(legacyBaseline)) { + const existingApp = safeGet(storage, FIRST_LAUNCH_KEYS.appVersion); + if (existingApp.ok && existingApp.value === null) { + safeSet(storage, FIRST_LAUNCH_KEYS.appVersion, legacyBaseline); + } + } + + if (validBundleVersion !== undefined) { + cachedBundleResults.set( + validBundleVersion, + evaluateVersionKey( + storage, + FIRST_LAUNCH_KEYS.bundleVersion, + validBundleVersion + ) + ); + } + + if (!launchedRead.ok) { + cachedFirstLaunch = false; + } else if (launchedRead.value === null) { + const wrote = safeSet(storage, FIRST_LAUNCH_KEYS.launched, '1'); + cachedFirstLaunch = wrote && !isLegacyInstall; + } else { + // Present ("1" or corrupted): not a first launch, do not overwrite. + cachedFirstLaunch = false; + } +} + +export function isFirstLaunch(): boolean { + if (!initialized) { + return false; + } + return cachedFirstLaunch; +} + +export function isFirstLaunchForCurrentAppVersion( + appVersion?: string +): boolean { + if (!initialized) { + return false; + } + if (appVersion === undefined) { + return startupAppVersion !== undefined + ? (cachedAppResults.get(startupAppVersion) ?? false) + : false; + } + if (!isValidVersion(appVersion)) { + return false; + } + const cached = cachedAppResults.get(appVersion); + if (cached !== undefined) { + return cached; + } + const storage = getStorage(); + const result = storage + ? evaluateVersionKey(storage, FIRST_LAUNCH_KEYS.appVersion, appVersion) + : false; + cachedAppResults.set(appVersion, result); + return result; +} + +export function isFirstLaunchForCurrentBundle( + bundleVersion?: string +): boolean { + if (!initialized) { + return false; + } + if (bundleVersion === undefined) { + return startupBundleVersion !== undefined + ? (cachedBundleResults.get(startupBundleVersion) ?? false) + : false; + } + if (!isValidVersion(bundleVersion)) { + return false; + } + const cached = cachedBundleResults.get(bundleVersion); + if (cached !== undefined) { + return cached; + } + const storage = getStorage(); + const result = storage + ? evaluateVersionKey(storage, FIRST_LAUNCH_KEYS.bundleVersion, bundleVersion) + : false; + cachedBundleResults.set(bundleVersion, result); + return result; +} + +export function resetFirstLaunch(): boolean { + const storage = getStorage(); + if (!storage) { + return false; + } + try { + storage.removeItem(FIRST_LAUNCH_KEYS.launched); + storage.removeItem(FIRST_LAUNCH_KEYS.appVersion); + storage.removeItem(FIRST_LAUNCH_KEYS.bundleVersion); + } catch { + return false; + } + initialized = false; + cachedFirstLaunch = false; + startupAppVersion = undefined; + startupBundleVersion = undefined; + cachedAppResults.clear(); + cachedBundleResults.clear(); + return true; +} diff --git a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt index 02efb49ce..4fa397de6 100644 --- a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt +++ b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt @@ -139,4 +139,77 @@ fun main() { } check(capacityWinners.get() == 128 && rejectedClaims.get() == 128) println("Kotlin in-memory store: passed") + + val directory = kotlin.io.path.createTempDirectory("device-utils-first-launch-").toFile() + try { + fun launch(version: String, previous: String? = null) = + FirstLaunchHistory(directory, version, previous, hasPreviousLaunch = previous != null) + + val fresh = launch("6.5.0") + check(fresh.isFirstLaunch && fresh.isFirstLaunchForCurrentAppVersion) + check(!fresh.isFirstLaunchForBundle(null)) + fresh.initForBundle("1000") + check(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle(null)) + // Explicit lookup of another bundle must not overwrite zero-arg active bundle result. + check(!fresh.isFirstLaunchForBundle("999")) + check(fresh.isFirstLaunchForBundle(null)) + // Reject non-numeric version core, trailing newlines, and traversal strings. + check(!fresh.isFirstLaunchForBundle("v1000")) + check(!fresh.isFirstLaunchForBundle("1000\n")) + check(!fresh.isFirstLaunchForBundle("../escape")) + + val restart = launch("6.5.0") + check(!restart.isFirstLaunch && !restart.isFirstLaunchForCurrentAppVersion) + restart.initForBundle("1000") + check(!restart.isFirstLaunchForBundle("1000") && !restart.isFirstLaunchForBundle(null)) + // Explicit lookup of a higher bundle must not overwrite active bundle. + check(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) + check(!restart.isFirstLaunchForBundle(null)) + // In-process OTA reload calls initForBundle with the new executing bundle and updates zero-arg getter. + restart.initForBundle("1001") + check(restart.isFirstLaunchForBundle(null)) + // Invalid startup bundle clears the active bundle identity so zero-arg getter returns false. + restart.initForBundle("v1002") + check(!restart.isFirstLaunchForBundle(null)) + + val rollback = launch("6.5.0") + check(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) + check(!rollback.isFirstLaunchForBundle("1000")) + check(!rollback.isFirstLaunchForBundle("999")) + + val upgrade = launch("6.10.0", previous = "6.5.0") + check(!upgrade.isFirstLaunch && upgrade.isFirstLaunchForCurrentAppVersion) + check(!upgrade.isFirstLaunchForBundle("1001")) + check(upgrade.isFirstLaunchForBundle("1002")) + + val downgrade = launch("6.9.0", previous = "6.10.0") + check(!downgrade.isFirstLaunch && !downgrade.isFirstLaunchForCurrentAppVersion) + check(!downgrade.isFirstLaunchForBundle("1001")) + + val legacySame = FirstLaunchHistory(directory.resolve("legacy-same"), "6.5.0", "6.5.0", hasPreviousLaunch = true) + check(!legacySame.isFirstLaunch && !legacySame.isFirstLaunchForCurrentAppVersion) + + val legacyUpgraded = FirstLaunchHistory(directory.resolve("legacy-upgraded"), "6.6.0", "6.5.0", hasPreviousLaunch = true) + check(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) + + // Corrupted individual files must fail closed without overwriting or breaking healthy files. + val corruptPayloads = listOf("", "6.6.0!", "v1000") + corruptPayloads.forEachIndexed { idx, bad -> + val corruptBase = directory.resolve("corrupt-$idx") + val corruptStore = corruptBase.resolve(FirstLaunchHistory.DIRECTORY_NAME).apply { mkdirs() } + corruptStore.resolve(FirstLaunchHistory.LAUNCHED_FILE_NAME).writeText("1") + val badAppFile = corruptStore.resolve(FirstLaunchHistory.APP_VERSION_FILE_NAME).apply { writeText(bad) } + val corrupted = FirstLaunchHistory(corruptBase, "6.5.0", null, hasPreviousLaunch = false) + check(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion) + check(badAppFile.readText() == bad) + check(corrupted.isFirstLaunchForBundle("1000")) + } + + val file = directory.resolve("file").apply { writeText("") } + val failed = FirstLaunchHistory(file, "6.5.0", null, hasPreviousLaunch = false) + check(!failed.isFirstLaunch && !failed.isFirstLaunchForCurrentAppVersion && !failed.isFirstLaunchForBundle("1000")) + } finally { + directory.deleteRecursively() + } + println("Kotlin first launch history: passed") } diff --git a/native-modules/react-native-device-utils/tests/in-memory-store.cjs b/native-modules/react-native-device-utils/tests/in-memory-store.cjs index 9e2d30b31..58da54971 100644 --- a/native-modules/react-native-device-utils/tests/in-memory-store.cjs +++ b/native-modules/react-native-device-utils/tests/in-memory-store.cjs @@ -20,6 +20,7 @@ if (mode !== '--kotlin') { run('swiftc', [ join(root, 'nitrogen/generated/ios/swift/InMemoryValue.swift'), join(root, 'ios/InMemoryStore.swift'), + join(root, 'ios/DeviceUtilsFirstLaunch.swift'), join(__dirname, 'main.swift'), '-module-cache-path', join(output, 'swift-module-cache'), @@ -42,6 +43,7 @@ if (mode !== '--swift') { annotation, join(root, 'nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/InMemoryValue.kt'), join(root, 'android/src/main/java/com/margelo/nitro/reactnativedeviceutils/InMemoryStore.kt'), + join(root, 'android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt'), join(__dirname, 'InMemoryStoreTest.kt'), '-include-runtime', '-d', diff --git a/native-modules/react-native-device-utils/tests/main.swift b/native-modules/react-native-device-utils/tests/main.swift index 9c689d4b8..368773353 100644 --- a/native-modules/react-native-device-utils/tests/main.swift +++ b/native-modules/react-native-device-utils/tests/main.swift @@ -129,3 +129,98 @@ DispatchQueue.concurrentPerform(iterations: 256) { index in } precondition(capacityWinners == 128 && rejectedClaims == 128) print("Swift in-memory store: passed") + +func testFirstLaunchHistory() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + + func launch(_ version: String, previous: String? = nil) -> FirstLaunchHistory { + FirstLaunchHistory( + baseDirectory: directory, + appVersion: version, + previousAppVersion: previous, + hasPreviousLaunch: previous != nil + ) + } + + let fresh = launch("6.5.0") + precondition(fresh.isFirstLaunch && fresh.isFirstLaunchForCurrentAppVersion) + precondition(!fresh.isFirstLaunchForBundle(nil)) + fresh.initForBundle("1000") + precondition(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle(nil)) + // Explicit lookup of another bundle must not overwrite zero-arg active bundle result. + precondition(!fresh.isFirstLaunchForBundle("999")) + precondition(fresh.isFirstLaunchForBundle(nil)) + // Reject non-numeric version core, trailing newlines, and traversal strings. + precondition(!fresh.isFirstLaunchForBundle("v1000")) + precondition(!fresh.isFirstLaunchForBundle("1000\n")) + precondition(!fresh.isFirstLaunchForBundle("../escape")) + + let restart = launch("6.5.0") + precondition(!restart.isFirstLaunch && !restart.isFirstLaunchForCurrentAppVersion) + restart.initForBundle("1000") + precondition(!restart.isFirstLaunchForBundle("1000") && !restart.isFirstLaunchForBundle(nil)) + // Explicit lookup of a higher bundle must not overwrite active bundle. + precondition(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) + precondition(!restart.isFirstLaunchForBundle(nil)) + // In-process OTA reload calls initForBundle with the new executing bundle and updates zero-arg getter. + restart.initForBundle("1001") + precondition(restart.isFirstLaunchForBundle(nil)) + // Invalid startup bundle clears the active bundle identity so zero-arg getter returns false. + restart.initForBundle("v1002") + precondition(!restart.isFirstLaunchForBundle(nil)) + + let rollback = launch("6.5.0") + precondition(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) + precondition(!rollback.isFirstLaunchForBundle("1000")) + precondition(!rollback.isFirstLaunchForBundle("999")) + + let upgrade = launch("6.10.0", previous: "6.5.0") + precondition(!upgrade.isFirstLaunch && upgrade.isFirstLaunchForCurrentAppVersion) + precondition(!upgrade.isFirstLaunchForBundle("1001")) + precondition(upgrade.isFirstLaunchForBundle("1002")) + + let downgrade = launch("6.9.0", previous: "6.10.0") + precondition(!downgrade.isFirstLaunch && !downgrade.isFirstLaunchForCurrentAppVersion) + precondition(!downgrade.isFirstLaunchForBundle("1001")) + + let legacySameVersion = FirstLaunchHistory( + baseDirectory: directory.appendingPathComponent("legacy-same"), + appVersion: "6.5.0", + previousAppVersion: "6.5.0", + hasPreviousLaunch: true + ) + precondition(!legacySameVersion.isFirstLaunch && !legacySameVersion.isFirstLaunchForCurrentAppVersion) + + let legacyUpgraded = FirstLaunchHistory( + baseDirectory: directory.appendingPathComponent("legacy-upgraded"), + appVersion: "6.6.0", + previousAppVersion: "6.5.0", + hasPreviousLaunch: true + ) + precondition(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) + + // Corrupted individual files must fail closed without overwriting or breaking healthy files. + for (idx, bad) in ["", "6.6.0!", "v1000"].enumerated() { + let corruptBase = directory.appendingPathComponent("corrupt-\(idx)") + let corruptStore = corruptBase.appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) + try FileManager.default.createDirectory(at: corruptStore, withIntermediateDirectories: true) + try Data("1".utf8).write(to: corruptStore.appendingPathComponent(FirstLaunchHistory.launchedFileName)) + let badAppFile = corruptStore.appendingPathComponent(FirstLaunchHistory.appVersionFileName) + try Data(bad.utf8).write(to: badAppFile) + let corrupted = FirstLaunchHistory(baseDirectory: corruptBase, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) + precondition(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion) + let remaining = try String(contentsOf: badAppFile, encoding: .utf8) + precondition(remaining == bad) + // Healthy bundle file still works independently. + precondition(corrupted.isFirstLaunchForBundle("1000")) + } + + let file = directory.appendingPathComponent("file") + try Data().write(to: file) + let failed = FirstLaunchHistory(baseDirectory: file, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) + precondition(!failed.isFirstLaunch && !failed.isFirstLaunchForCurrentAppVersion && !failed.isFirstLaunchForBundle("1000")) +} + +try testFirstLaunchHistory() +print("Swift first launch history: passed") diff --git a/native-modules/react-native-device-utils/tsconfig.json b/native-modules/react-native-device-utils/tsconfig.json index 604e2a148..0fd68c6e4 100644 --- a/native-modules/react-native-device-utils/tsconfig.json +++ b/native-modules/react-native-device-utils/tsconfig.json @@ -10,7 +10,7 @@ "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "jsx": "react-jsx", - "lib": ["ESNext"], + "lib": ["ESNext", "DOM"], "module": "ESNext", "moduleResolution": "bundler", "noEmit": true,