native-update-react-native 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +82 -2
  3. package/android/build.gradle +41 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/com/aoneahsan/nativeupdate/android/Errors.kt +20 -0
  6. package/android/src/main/java/com/aoneahsan/nativeupdate/android/NativeUpdate.kt +309 -0
  7. package/android/src/main/java/com/aoneahsan/nativeupdate/android/NativeUpdateConfig.kt +92 -0
  8. package/android/src/main/java/com/aoneahsan/nativeupdate/android/PlayAppUpdate.kt +153 -0
  9. package/android/src/main/java/com/aoneahsan/nativeupdate/android/PlayReview.kt +68 -0
  10. package/android/src/main/java/com/aoneahsan/nativeupdate/android/UpdateTypes.kt +50 -0
  11. package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/AppInfo.kt +56 -0
  12. package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/BundleStore.kt +210 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/BundleVerifier.kt +66 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/UpdateClient.kt +184 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/Versions.kt +34 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/ZipExtractor.kt +55 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/reactnative/NativeUpdateModule.kt +155 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/reactnative/NativeUpdatePackage.kt +30 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/reactnative/NativeUpdateReactNative.kt +41 -0
  20. package/lib/NativeNativeUpdate.d.ts +16 -0
  21. package/lib/NativeNativeUpdate.js +4 -0
  22. package/lib/index.d.ts +72 -0
  23. package/lib/index.js +76 -0
  24. package/package.json +56 -4
  25. package/react-native.config.js +11 -0
  26. package/src/NativeNativeUpdate.ts +18 -0
  27. package/src/index.ts +111 -0
@@ -0,0 +1,184 @@
1
+ package com.aoneahsan.nativeupdate.android.internal
2
+
3
+ import com.aoneahsan.nativeupdate.android.ErrorCodes
4
+ import com.aoneahsan.nativeupdate.android.NativeUpdateConfig
5
+ import com.aoneahsan.nativeupdate.android.NativeUpdateException
6
+ import com.aoneahsan.nativeupdate.android.UpdateCheckResult
7
+ import com.aoneahsan.nativeupdate.android.UpdateInfo
8
+ import org.json.JSONObject
9
+ import java.io.File
10
+ import java.io.IOException
11
+ import java.net.HttpURLConnection
12
+ import java.net.URL
13
+ import java.net.URLEncoder
14
+ import javax.net.ssl.HttpsURLConnection
15
+
16
+ /** The headers that identify one device and app on every check (docs/protocol/CLIENT-PROTOCOL.md §1). */
17
+ internal data class ClientIdentity(
18
+ val apiKey: String,
19
+ val deviceId: String,
20
+ val currentVersion: String,
21
+ val appVersion: String?,
22
+ val packageName: String,
23
+ val certSha256: String?,
24
+ val clientSdk: String,
25
+ val sdkVersion: String,
26
+ )
27
+
28
+ /**
29
+ * HTTP for the update check and the bundle download, on the platform's own HttpsURLConnection so a host app gets no
30
+ * extra HTTP library (and no compileSdk floor from one). Blocking calls; the caller picks the thread.
31
+ */
32
+ internal class UpdateClient(
33
+ private val allowLoopbackHttp: Boolean = false,
34
+ ) {
35
+ fun check(
36
+ serverUrl: String,
37
+ channel: String,
38
+ identity: ClientIdentity,
39
+ ): UpdateCheckResult {
40
+ val url = "$serverUrl/v1/updates/check?channel=${URLEncoder.encode(channel, "UTF-8")}"
41
+ val headers =
42
+ buildMap {
43
+ put("Accept", "application/json")
44
+ put("X-API-Key", identity.apiKey)
45
+ put("X-Device-ID", identity.deviceId)
46
+ put("X-Current-Version", identity.currentVersion)
47
+ put("X-Platform", "android")
48
+ put("X-Client-Sdk", identity.clientSdk)
49
+ put("X-Sdk-Version", identity.sdkVersion)
50
+ put("X-Android-Package", identity.packageName)
51
+ identity.appVersion?.let { put("X-App-Version", it) }
52
+ identity.certSha256?.let { put("X-Android-Cert-Sha256", it) }
53
+ }
54
+ val body =
55
+ try {
56
+ val connection = open(url, headers, READ_TIMEOUT_CHECK_MS)
57
+ try {
58
+ val status = connection.responseCode
59
+ if (status !in 200..299) {
60
+ throw NativeUpdateException(ErrorCodes.NETWORK_ERROR, "Update check answered HTTP $status")
61
+ }
62
+ connection.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }
63
+ } finally {
64
+ connection.disconnect()
65
+ }
66
+ } catch (failure: IOException) {
67
+ throw NativeUpdateException(ErrorCodes.NETWORK_ERROR, "Update check failed: ${failure.javaClass.simpleName}", failure)
68
+ } catch (failure: SecurityException) {
69
+ throw NativeUpdateException(ErrorCodes.NETWORK_ERROR, "Update check blocked: the app lacks the INTERNET permission", failure)
70
+ }
71
+ return parseCheck(body)
72
+ }
73
+
74
+ fun download(
75
+ url: String,
76
+ destination: File,
77
+ maxBytes: Long,
78
+ ) {
79
+ try {
80
+ val connection = open(url, emptyMap(), READ_TIMEOUT_DOWNLOAD_MS)
81
+ try {
82
+ val status = connection.responseCode
83
+ if (status !in 200..299) {
84
+ throw NativeUpdateException(ErrorCodes.DOWNLOAD_ERROR, "Download answered HTTP $status")
85
+ }
86
+ if (connection.contentLengthLong > maxBytes) {
87
+ throw NativeUpdateException(ErrorCodes.DOWNLOAD_ERROR, "Bundle exceeds the size limit")
88
+ }
89
+ var total = 0L
90
+ connection.inputStream.use { input ->
91
+ destination.outputStream().use { output ->
92
+ val buffer = ByteArray(BUFFER)
93
+ while (true) {
94
+ val read = input.read(buffer)
95
+ if (read < 0) break
96
+ total += read
97
+ if (total > maxBytes) {
98
+ throw NativeUpdateException(ErrorCodes.DOWNLOAD_ERROR, "Bundle exceeds the size limit")
99
+ }
100
+ output.write(buffer, 0, read)
101
+ }
102
+ }
103
+ }
104
+ } finally {
105
+ connection.disconnect()
106
+ }
107
+ } catch (failure: IOException) {
108
+ destination.delete()
109
+ throw NativeUpdateException(ErrorCodes.DOWNLOAD_ERROR, "Download stopped: ${failure.javaClass.simpleName}", failure)
110
+ } catch (failure: SecurityException) {
111
+ destination.delete()
112
+ throw NativeUpdateException(ErrorCodes.DOWNLOAD_ERROR, "Download blocked: the app lacks the INTERNET permission", failure)
113
+ } catch (failure: NativeUpdateException) {
114
+ destination.delete()
115
+ throw failure
116
+ }
117
+ }
118
+
119
+ /**
120
+ * HTTPS only, except a loopback test server in a debuggable build. Redirects are followed only within the same
121
+ * protocol (HttpURLConnection never crosses http and https).
122
+ */
123
+ private fun open(
124
+ url: String,
125
+ headers: Map<String, String>,
126
+ readTimeoutMs: Int,
127
+ ): HttpURLConnection {
128
+ val secure = url.startsWith("https://")
129
+ if (!secure && !(allowLoopbackHttp && NativeUpdateConfig.isLoopbackHttp(url))) {
130
+ throw NativeUpdateException(ErrorCodes.INSECURE_URL, "Only https URLs are allowed")
131
+ }
132
+ val connection = URL(url).openConnection() as HttpURLConnection
133
+ if (secure && connection !is HttpsURLConnection) {
134
+ throw NativeUpdateException(ErrorCodes.INSECURE_URL, "Only https URLs are allowed")
135
+ }
136
+ connection.connectTimeout = CONNECT_TIMEOUT_MS
137
+ connection.readTimeout = readTimeoutMs
138
+ connection.instanceFollowRedirects = true
139
+ connection.useCaches = false
140
+ headers.forEach { (name, value) -> connection.setRequestProperty(name, value) }
141
+ return connection
142
+ }
143
+
144
+ internal companion object {
145
+ private const val BUFFER = 64 * 1024
146
+ private const val CONNECT_TIMEOUT_MS = 15_000
147
+ private const val READ_TIMEOUT_CHECK_MS = 20_000
148
+ private const val READ_TIMEOUT_DOWNLOAD_MS = 60_000
149
+
150
+ /** Maps the server's JSON to a result. Pure, so it is unit-tested against the documented shapes. */
151
+ fun parseCheck(body: String): UpdateCheckResult {
152
+ val json =
153
+ try {
154
+ JSONObject(body)
155
+ } catch (failure: Exception) {
156
+ throw NativeUpdateException(ErrorCodes.NETWORK_ERROR, "Update check returned malformed JSON", failure)
157
+ }
158
+ fun text(name: String): String? = json.optString(name, "").takeIf { it.isNotEmpty() && !json.isNull(name) }
159
+ if (!json.optBoolean("available", false)) {
160
+ if (json.optBoolean("held", false)) return UpdateCheckResult.Held(text("version"), text("message"))
161
+ text("minNativeVersion")?.let { return UpdateCheckResult.NativeUpdateRequired(it) }
162
+ return UpdateCheckResult.UpToDate(text("message"), text("code"))
163
+ }
164
+ val info =
165
+ UpdateInfo(
166
+ version = text("version") ?: missing("version"),
167
+ bundleId = text("bundleId") ?: missing("bundleId"),
168
+ downloadUrl = text("downloadUrl") ?: missing("downloadUrl"),
169
+ checksum = text("checksum") ?: missing("checksum"),
170
+ signature = text("signature"),
171
+ signatureAlgorithm = text("signatureAlgorithm"),
172
+ payloadType = text("payloadType") ?: "web_bundle",
173
+ size = json.optLong("size", 0L),
174
+ mandatory = json.optBoolean("mandatory", false),
175
+ releaseNotes = text("releaseNotes"),
176
+ minNativeVersion = text("minNativeVersion"),
177
+ )
178
+ return UpdateCheckResult.Available(info)
179
+ }
180
+
181
+ private fun missing(field: String): Nothing =
182
+ throw NativeUpdateException(ErrorCodes.NETWORK_ERROR, "Update check response has no $field")
183
+ }
184
+ }
@@ -0,0 +1,34 @@
1
+ package com.aoneahsan.nativeupdate.android.internal
2
+
3
+ /** Numeric `major.minor.patch` comparison (1.10.0 > 1.9.0). A pre-release or build suffix is ignored. */
4
+ internal object Versions {
5
+ /** Negative, zero or positive like [Comparable.compareTo]; null when either side is not a version. */
6
+ fun compare(
7
+ left: String,
8
+ right: String,
9
+ ): Int? {
10
+ val a = parse(left) ?: return null
11
+ val b = parse(right) ?: return null
12
+ for (index in 0 until PARTS) {
13
+ val difference = a[index].compareTo(b[index])
14
+ if (difference != 0) return difference
15
+ }
16
+ return 0
17
+ }
18
+
19
+ /** True only when [candidate] is a version strictly newer than [current]. */
20
+ fun isNewer(
21
+ candidate: String,
22
+ current: String,
23
+ ): Boolean = (compare(candidate, current) ?: 0) > 0
24
+
25
+ private fun parse(version: String): IntArray? {
26
+ val core = version.trim().substringBefore('-').substringBefore('+')
27
+ val parts = core.split('.')
28
+ if (core.isEmpty() || parts.size > PARTS) return null
29
+ val numbers = parts.map { part -> part.toIntOrNull()?.takeIf { it >= 0 } ?: return null }
30
+ return IntArray(PARTS) { numbers.getOrElse(it) { 0 } }
31
+ }
32
+
33
+ private const val PARTS = 3
34
+ }
@@ -0,0 +1,55 @@
1
+ package com.aoneahsan.nativeupdate.android.internal
2
+
3
+ import com.aoneahsan.nativeupdate.android.ErrorCodes
4
+ import com.aoneahsan.nativeupdate.android.NativeUpdateException
5
+ import java.io.File
6
+ import java.util.zip.ZipInputStream
7
+
8
+ /** Unpacks a verified bundle ZIP, refusing any entry that escapes the target (Zip-Slip) and any oversize content. */
9
+ internal object ZipExtractor {
10
+ fun extract(
11
+ zip: File,
12
+ destination: File,
13
+ maxUncompressedBytes: Long,
14
+ ) {
15
+ destination.deleteRecursively()
16
+ if (!destination.mkdirs()) fail("cannot create the bundle directory")
17
+ val root = destination.canonicalFile
18
+ var total = 0L
19
+ var entries = 0
20
+ ZipInputStream(zip.inputStream().buffered()).use { input ->
21
+ while (true) {
22
+ val entry = input.nextEntry ?: break
23
+ entries += 1
24
+ if (entries > MAX_ENTRIES) fail("too many entries")
25
+ val target = File(root, entry.name).canonicalFile
26
+ if (target.path != root.path && !target.path.startsWith(root.path + File.separator)) {
27
+ fail("an entry escapes the bundle directory")
28
+ }
29
+ if (entry.isDirectory) {
30
+ target.mkdirs()
31
+ continue
32
+ }
33
+ target.parentFile?.mkdirs()
34
+ target.outputStream().use { output ->
35
+ val buffer = ByteArray(BUFFER)
36
+ while (true) {
37
+ val read = input.read(buffer)
38
+ if (read < 0) break
39
+ total += read
40
+ if (total > maxUncompressedBytes) fail("unpacked size exceeds the limit")
41
+ output.write(buffer, 0, read)
42
+ }
43
+ }
44
+ }
45
+ }
46
+ if (entries == 0) fail("the bundle is empty")
47
+ }
48
+
49
+ private fun fail(reason: String): Nothing {
50
+ throw NativeUpdateException(ErrorCodes.EXTRACTION_ERROR, "Bundle could not be unpacked: $reason")
51
+ }
52
+
53
+ private const val BUFFER = 64 * 1024
54
+ private const val MAX_ENTRIES = 20_000
55
+ }
@@ -0,0 +1,155 @@
1
+ package com.aoneahsan.nativeupdate.reactnative
2
+
3
+ import android.content.Intent
4
+ import com.aoneahsan.nativeupdate.android.Activation
5
+ import com.aoneahsan.nativeupdate.android.ErrorCodes
6
+ import com.aoneahsan.nativeupdate.android.NativeUpdate
7
+ import com.aoneahsan.nativeupdate.android.NativeUpdateException
8
+ import com.aoneahsan.nativeupdate.android.PlayAppUpdate
9
+ import com.aoneahsan.nativeupdate.android.PlayReview
10
+ import com.aoneahsan.nativeupdate.android.UpdateCheckResult
11
+ import com.aoneahsan.nativeupdate.android.UpdateInfo
12
+ import com.facebook.react.bridge.Arguments
13
+ import com.facebook.react.bridge.Promise
14
+ import com.facebook.react.bridge.ReactApplicationContext
15
+ import com.facebook.react.bridge.ReadableMap
16
+ import com.facebook.react.bridge.WritableMap
17
+ import kotlinx.coroutines.CoroutineScope
18
+ import kotlinx.coroutines.Dispatchers
19
+ import kotlinx.coroutines.SupervisorJob
20
+ import kotlinx.coroutines.cancel
21
+ import kotlinx.coroutines.launch
22
+
23
+ /** The `NativeUpdate` TurboModule, over the shared Kotlin core. */
24
+ class NativeUpdateModule(
25
+ private val context: ReactApplicationContext,
26
+ ) : NativeNativeUpdateSpec(context) {
27
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
28
+
29
+ override fun getName(): String = NAME
30
+
31
+ override fun invalidate() {
32
+ scope.cancel()
33
+ super.invalidate()
34
+ }
35
+
36
+ override fun checkForUpdate(promise: Promise) = run(promise) { checkResult(NativeUpdate.checkForUpdate()) }
37
+
38
+ override fun download(
39
+ info: ReadableMap,
40
+ activation: String,
41
+ promise: Promise,
42
+ ) = run(promise) {
43
+ NativeUpdate.download(updateInfo(info), if (activation == "now") Activation.NOW else Activation.NEXT_START)
44
+ }
45
+
46
+ override fun notifyAppReady(promise: Promise) =
47
+ run(promise) {
48
+ NativeUpdate.notifyAppReady()
49
+ null
50
+ }
51
+
52
+ override fun currentVersion(promise: Promise) = run(promise) { NativeUpdate.currentVersion() }
53
+
54
+ override fun lastDroppedReason(promise: Promise) = run(promise) { NativeUpdate.lastDroppedReason() }
55
+
56
+ /** Relaunches the app's launcher activity in a fresh process, so the next start loads the new bundle. */
57
+ override fun restart() {
58
+ val launch = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return
59
+ launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
60
+ context.startActivity(launch)
61
+ android.os.Process.killProcess(android.os.Process.myPid())
62
+ }
63
+
64
+ override fun isPlayInstall(promise: Promise) = run(promise) { PlayAppUpdate.isPlayInstall(context) }
65
+
66
+ override fun startPlayImmediateUpdate(promise: Promise) =
67
+ run(promise) { PlayAppUpdate.startImmediate(activity(), PLAY_UPDATE_REQUEST).name }
68
+
69
+ override fun resumePlayUpdate(promise: Promise) =
70
+ run(promise) { PlayAppUpdate.resumeIfInProgress(activity(), PLAY_UPDATE_REQUEST) }
71
+
72
+ override fun requestPlayReview(promise: Promise) = run(promise) { PlayReview.request(activity()).name }
73
+
74
+ private fun activity() =
75
+ context.currentActivity ?: throw NativeUpdateException(ErrorCodes.VALIDATION_ERROR, "No activity is in the foreground")
76
+
77
+ private fun run(
78
+ promise: Promise,
79
+ block: suspend () -> Any?,
80
+ ) {
81
+ scope.launch {
82
+ try {
83
+ promise.resolve(block())
84
+ } catch (error: NativeUpdateException) {
85
+ promise.reject(error.code, error.message, error)
86
+ } catch (error: Exception) {
87
+ promise.reject(ErrorCodes.VALIDATION_ERROR, error.message ?: "Unexpected failure", error)
88
+ }
89
+ }
90
+ }
91
+
92
+ private fun checkResult(result: UpdateCheckResult): WritableMap =
93
+ Arguments.createMap().apply {
94
+ when (result) {
95
+ is UpdateCheckResult.UpToDate -> {
96
+ putString("type", "upToDate")
97
+ putString("message", result.message)
98
+ putString("code", result.code)
99
+ }
100
+ is UpdateCheckResult.Available -> {
101
+ putString("type", "available")
102
+ putMap("info", infoMap(result.info))
103
+ }
104
+ is UpdateCheckResult.NativeUpdateRequired -> {
105
+ putString("type", "nativeUpdateRequired")
106
+ putString("minNativeVersion", result.minNativeVersion)
107
+ }
108
+ is UpdateCheckResult.Held -> {
109
+ putString("type", "held")
110
+ putString("version", result.version)
111
+ putString("message", result.message)
112
+ }
113
+ }
114
+ }
115
+
116
+ private fun infoMap(info: UpdateInfo): WritableMap =
117
+ Arguments.createMap().apply {
118
+ putString("version", info.version)
119
+ putString("bundleId", info.bundleId)
120
+ putString("downloadUrl", info.downloadUrl)
121
+ putString("checksum", info.checksum)
122
+ putString("signature", info.signature)
123
+ putString("signatureAlgorithm", info.signatureAlgorithm)
124
+ putString("payloadType", info.payloadType)
125
+ putDouble("size", info.size.toDouble())
126
+ putBoolean("mandatory", info.mandatory)
127
+ putString("releaseNotes", info.releaseNotes)
128
+ putString("minNativeVersion", info.minNativeVersion)
129
+ }
130
+
131
+ private fun updateInfo(map: ReadableMap): UpdateInfo {
132
+ fun text(name: String): String =
133
+ map.takeIf { it.hasKey(name) && !it.isNull(name) }?.getString(name)
134
+ ?: throw NativeUpdateException(ErrorCodes.VALIDATION_ERROR, "info.$name is missing")
135
+ fun optional(name: String): String? = if (map.hasKey(name) && !map.isNull(name)) map.getString(name) else null
136
+ return UpdateInfo(
137
+ version = text("version"),
138
+ bundleId = text("bundleId"),
139
+ downloadUrl = text("downloadUrl"),
140
+ checksum = text("checksum"),
141
+ signature = optional("signature"),
142
+ signatureAlgorithm = optional("signatureAlgorithm"),
143
+ payloadType = optional("payloadType") ?: "web_bundle",
144
+ size = if (map.hasKey("size") && !map.isNull("size")) map.getDouble("size").toLong() else 0L,
145
+ mandatory = map.hasKey("mandatory") && !map.isNull("mandatory") && map.getBoolean("mandatory"),
146
+ releaseNotes = optional("releaseNotes"),
147
+ minNativeVersion = optional("minNativeVersion"),
148
+ )
149
+ }
150
+
151
+ companion object {
152
+ const val NAME = "NativeUpdate"
153
+ private const val PLAY_UPDATE_REQUEST = 0x4e55
154
+ }
155
+ }
@@ -0,0 +1,30 @@
1
+ package com.aoneahsan.nativeupdate.reactnative
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+
9
+ /** Registers the `NativeUpdate` TurboModule; picked up by autolinking. */
10
+ class NativeUpdatePackage : BaseReactPackage() {
11
+ override fun getModule(
12
+ name: String,
13
+ reactContext: ReactApplicationContext,
14
+ ): NativeModule? = if (name == NativeUpdateModule.NAME) NativeUpdateModule(reactContext) else null
15
+
16
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider =
17
+ ReactModuleInfoProvider {
18
+ mapOf(
19
+ NativeUpdateModule.NAME to
20
+ ReactModuleInfo(
21
+ NativeUpdateModule.NAME,
22
+ NativeUpdateModule::class.java.name,
23
+ false,
24
+ false,
25
+ false,
26
+ true,
27
+ ),
28
+ )
29
+ }
30
+ }
@@ -0,0 +1,41 @@
1
+ package com.aoneahsan.nativeupdate.reactnative
2
+
3
+ import android.content.Context
4
+ import com.aoneahsan.nativeupdate.android.NativeUpdate
5
+ import com.aoneahsan.nativeupdate.android.NativeUpdateConfig
6
+
7
+ /**
8
+ * Native start-up for React Native apps. Call [init] in `MainApplication.onCreate` before the React host is built,
9
+ * then pass [bundleFile] as `jsBundleFilePath`:
10
+ *
11
+ * ```kotlin
12
+ * override val reactHost by lazy {
13
+ * getDefaultReactHost(applicationContext, PackageList(this).packages, jsBundleFilePath = NativeUpdateReactNative.bundleFile())
14
+ * }
15
+ * override fun onCreate() {
16
+ * NativeUpdateReactNative.init(this, NativeUpdateConfig.Builder(SERVER_URL, API_KEY, PUBLIC_KEY).build())
17
+ * super.onCreate()
18
+ * loadReactNative(this)
19
+ * }
20
+ * ```
21
+ */
22
+ object NativeUpdateReactNative {
23
+ /** This package's version, sent as X-Sdk-Version. Kept equal to package.json by the package's version check. */
24
+ const val VERSION: String = "1.0.1"
25
+
26
+ /** File name of the JavaScript bundle inside an update ZIP (Metro's default for Android). */
27
+ const val BUNDLE_FILE: String = "index.android.bundle"
28
+
29
+ /** Starts the SDK and runs the cold-start checks (rollback, integrity, new binary). */
30
+ @JvmStatic
31
+ fun init(
32
+ context: Context,
33
+ config: NativeUpdateConfig,
34
+ ) {
35
+ NativeUpdate.init(context, config, clientSdk = "react-native", sdkVersion = VERSION)
36
+ }
37
+
38
+ /** Absolute path of the active OTA bundle, or null to run the bundle built into the APK. */
39
+ @JvmStatic
40
+ fun bundleFile(): String? = NativeUpdate.file(BUNDLE_FILE)?.absolutePath
41
+ }
@@ -0,0 +1,16 @@
1
+ import type { TurboModule } from 'react-native';
2
+ /** Codegen spec for the native module. App code uses the wrappers in `index.ts`. */
3
+ export interface Spec extends TurboModule {
4
+ checkForUpdate(): Promise<Object>;
5
+ download(info: Object, activation: string): Promise<string>;
6
+ notifyAppReady(): Promise<void>;
7
+ currentVersion(): Promise<string>;
8
+ lastDroppedReason(): Promise<string | null>;
9
+ restart(): void;
10
+ isPlayInstall(): Promise<boolean>;
11
+ startPlayImmediateUpdate(): Promise<string>;
12
+ resumePlayUpdate(): Promise<boolean>;
13
+ requestPlayReview(): Promise<string>;
14
+ }
15
+ declare const _default: Spec;
16
+ export default _default;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const react_native_1 = require("react-native");
4
+ exports.default = react_native_1.TurboModuleRegistry.getEnforcing('NativeUpdate');
package/lib/index.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ /** One available bundle, as the server described it. */
2
+ export interface UpdateInfo {
3
+ version: string;
4
+ bundleId: string;
5
+ downloadUrl: string;
6
+ checksum: string;
7
+ signature?: string | null;
8
+ signatureAlgorithm?: string | null;
9
+ payloadType: string;
10
+ size: number;
11
+ mandatory: boolean;
12
+ releaseNotes?: string | null;
13
+ minNativeVersion?: string | null;
14
+ }
15
+ /** The answer to {@link checkForUpdate}. */
16
+ export type UpdateCheckResult = {
17
+ type: 'upToDate';
18
+ message?: string | null;
19
+ code?: string | null;
20
+ } | {
21
+ type: 'available';
22
+ info: UpdateInfo;
23
+ } | {
24
+ type: 'nativeUpdateRequired';
25
+ minNativeVersion: string;
26
+ } | {
27
+ type: 'held';
28
+ version?: string | null;
29
+ message?: string | null;
30
+ };
31
+ /** When a downloaded bundle runs: at the next cold start (default), or after {@link restart}. */
32
+ export type Activation = 'nextStart' | 'now';
33
+ export type PlayUpdateOutcome = 'STARTED' | 'NOT_AVAILABLE' | 'NOT_ALLOWED' | 'NOT_PLAY_INSTALL' | 'FAILED';
34
+ export type PlayReviewOutcome = 'REQUESTED' | 'NOT_PLAY_INSTALL' | 'FAILED';
35
+ /** A failure from the native side carries one of the protocol's error codes in `code`. */
36
+ export interface NativeUpdateError extends Error {
37
+ code: string;
38
+ }
39
+ /** Asks the server whether a newer JavaScript bundle exists for this device. */
40
+ export declare function checkForUpdate(): Promise<UpdateCheckResult>;
41
+ /**
42
+ * Downloads, verifies (SHA-256 + RSA-SHA256) and unpacks a bundle; returns the version that will run. With
43
+ * `activation: 'now'` it runs after {@link restart}; otherwise at the next cold start.
44
+ */
45
+ export declare function download(info: UpdateInfo, activation?: Activation): Promise<string>;
46
+ /**
47
+ * Call once the app has rendered and works, on every start. A new bundle that never gets here within two cold
48
+ * starts is rolled back and never offered to this device again.
49
+ */
50
+ export declare function notifyAppReady(): Promise<void>;
51
+ /** Version of the JavaScript running now: the active bundle's, or the one built into the app. */
52
+ export declare function currentVersion(): Promise<string>;
53
+ /** Why the last cold start set a bundle aside (rollback, failed check, new binary), or null. */
54
+ export declare function lastDroppedReason(): Promise<string | null>;
55
+ /** Relaunches the app so a downloaded bundle runs now. Only call it when the person expects a restart. */
56
+ export declare function restart(): void;
57
+ /** True when Google Play installed the running build. */
58
+ export declare function isPlayInstall(): Promise<boolean>;
59
+ /** Play's immediate in-app update. A sideloaded build answers `NOT_PLAY_INSTALL`. */
60
+ export declare function startPlayImmediateUpdate(): Promise<PlayUpdateOutcome>;
61
+ /** Brings back an immediate update the person left; call it when the app returns to the foreground. */
62
+ export declare function resumePlayUpdate(): Promise<boolean>;
63
+ /** Play's in-app review sheet. Play never says whether it showed; pair it with {@link shouldAskForReview}. */
64
+ export declare function requestPlayReview(): Promise<PlayReviewOutcome>;
65
+ /** True after at least `minSuccesses` good moments, and never twice within `minDaysBetween` days. */
66
+ export declare function shouldAskForReview(options: {
67
+ successes: number;
68
+ lastAskedMs: number | null;
69
+ nowMs: number;
70
+ minSuccesses?: number;
71
+ minDaysBetween?: number;
72
+ }): boolean;
package/lib/index.js ADDED
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.checkForUpdate = checkForUpdate;
7
+ exports.download = download;
8
+ exports.notifyAppReady = notifyAppReady;
9
+ exports.currentVersion = currentVersion;
10
+ exports.lastDroppedReason = lastDroppedReason;
11
+ exports.restart = restart;
12
+ exports.isPlayInstall = isPlayInstall;
13
+ exports.startPlayImmediateUpdate = startPlayImmediateUpdate;
14
+ exports.resumePlayUpdate = resumePlayUpdate;
15
+ exports.requestPlayReview = requestPlayReview;
16
+ exports.shouldAskForReview = shouldAskForReview;
17
+ /**
18
+ * Signed over-the-air JavaScript bundle updates, Google Play in-app update and in-app review for React Native,
19
+ * on the Native Update service.
20
+ *
21
+ * The SDK starts natively, in `MainApplication.onCreate`, before React loads (see the README), so a bundle that
22
+ * breaks the app can still be rolled back. JavaScript only checks, downloads and confirms.
23
+ */
24
+ const NativeNativeUpdate_1 = __importDefault(require("./NativeNativeUpdate"));
25
+ /** Asks the server whether a newer JavaScript bundle exists for this device. */
26
+ function checkForUpdate() {
27
+ return NativeNativeUpdate_1.default.checkForUpdate();
28
+ }
29
+ /**
30
+ * Downloads, verifies (SHA-256 + RSA-SHA256) and unpacks a bundle; returns the version that will run. With
31
+ * `activation: 'now'` it runs after {@link restart}; otherwise at the next cold start.
32
+ */
33
+ function download(info, activation = 'nextStart') {
34
+ return NativeNativeUpdate_1.default.download(info, activation);
35
+ }
36
+ /**
37
+ * Call once the app has rendered and works, on every start. A new bundle that never gets here within two cold
38
+ * starts is rolled back and never offered to this device again.
39
+ */
40
+ function notifyAppReady() {
41
+ return NativeNativeUpdate_1.default.notifyAppReady();
42
+ }
43
+ /** Version of the JavaScript running now: the active bundle's, or the one built into the app. */
44
+ function currentVersion() {
45
+ return NativeNativeUpdate_1.default.currentVersion();
46
+ }
47
+ /** Why the last cold start set a bundle aside (rollback, failed check, new binary), or null. */
48
+ function lastDroppedReason() {
49
+ return NativeNativeUpdate_1.default.lastDroppedReason();
50
+ }
51
+ /** Relaunches the app so a downloaded bundle runs now. Only call it when the person expects a restart. */
52
+ function restart() {
53
+ NativeNativeUpdate_1.default.restart();
54
+ }
55
+ /** True when Google Play installed the running build. */
56
+ function isPlayInstall() {
57
+ return NativeNativeUpdate_1.default.isPlayInstall();
58
+ }
59
+ /** Play's immediate in-app update. A sideloaded build answers `NOT_PLAY_INSTALL`. */
60
+ function startPlayImmediateUpdate() {
61
+ return NativeNativeUpdate_1.default.startPlayImmediateUpdate();
62
+ }
63
+ /** Brings back an immediate update the person left; call it when the app returns to the foreground. */
64
+ function resumePlayUpdate() {
65
+ return NativeNativeUpdate_1.default.resumePlayUpdate();
66
+ }
67
+ /** Play's in-app review sheet. Play never says whether it showed; pair it with {@link shouldAskForReview}. */
68
+ function requestPlayReview() {
69
+ return NativeNativeUpdate_1.default.requestPlayReview();
70
+ }
71
+ const DAY_MS = 86_400_000;
72
+ /** True after at least `minSuccesses` good moments, and never twice within `minDaysBetween` days. */
73
+ function shouldAskForReview(options) {
74
+ const { successes, lastAskedMs, nowMs, minSuccesses = 3, minDaysBetween = 90 } = options;
75
+ return successes >= minSuccesses && (lastAskedMs === null || nowMs - lastAskedMs >= minDaysBetween * DAY_MS);
76
+ }