expo-app-updates-android-ios 0.0.0-stage → 0.1.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 (47) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +10 -2
  4. package/android/build.gradle +24 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/com/andwati/appupdatesandroid/ExpoAppUpdatesAndroidIosModule.kt +72 -0
  7. package/android/src/main/java/com/andwati/appupdatesandroid/PlayUpdateClient.kt +335 -0
  8. package/build/AppUpdateGate.d.ts +40 -0
  9. package/build/AppUpdateGate.js +115 -0
  10. package/build/ExpoAppUpdatesAndroidIos.types.d.ts +102 -0
  11. package/build/ExpoAppUpdatesAndroidIos.types.js +12 -0
  12. package/build/ExpoAppUpdatesAndroidIosModule.d.ts +35 -0
  13. package/build/ExpoAppUpdatesAndroidIosModule.js +5 -0
  14. package/build/ExpoAppUpdatesAndroidIosModule.web.d.ts +2 -0
  15. package/build/ExpoAppUpdatesAndroidIosModule.web.js +3 -0
  16. package/build/index.d.ts +6 -0
  17. package/build/index.js +52 -0
  18. package/build/iosLookup.d.ts +5 -0
  19. package/build/iosLookup.js +128 -0
  20. package/build/isoCountryCodes.d.ts +1 -0
  21. package/build/isoCountryCodes.js +256 -0
  22. package/build/updateErrors.d.ts +2 -0
  23. package/build/updateErrors.js +25 -0
  24. package/build/updateGatePolicy.d.ts +14 -0
  25. package/build/updateGatePolicy.js +28 -0
  26. package/build/updates.d.ts +8 -0
  27. package/build/updates.js +100 -0
  28. package/build/useAppUpdateGate.d.ts +26 -0
  29. package/build/useAppUpdateGate.js +298 -0
  30. package/docs/README.md +94 -0
  31. package/docs/releasing.md +30 -0
  32. package/expo-module.config.json +9 -0
  33. package/ios/ExpoAppUpdatesAndroidIos.podspec +29 -0
  34. package/ios/ExpoAppUpdatesAndroidIosModule.swift +89 -0
  35. package/ios/StorePresenter.swift +143 -0
  36. package/package.json +57 -3
  37. package/src/AppUpdateGate.tsx +347 -0
  38. package/src/ExpoAppUpdatesAndroidIos.types.ts +136 -0
  39. package/src/ExpoAppUpdatesAndroidIosModule.ts +49 -0
  40. package/src/ExpoAppUpdatesAndroidIosModule.web.ts +1 -0
  41. package/src/index.ts +23 -0
  42. package/src/iosLookup.ts +165 -0
  43. package/src/isoCountryCodes.ts +253 -0
  44. package/src/updateErrors.ts +25 -0
  45. package/src/updateGatePolicy.ts +58 -0
  46. package/src/updates.ts +111 -0
  47. package/src/useAppUpdateGate.ts +391 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ - Add Android emulator screenshots to the README and move the integration guide to `docs/`.
6
+ - Verify tagged builds and publish GitHub releases automatically.
7
+ - Add weekly Dependabot updates for pnpm, Android Gradle dependencies, and GitHub Actions.
8
+
9
+ ## 0.1.0
10
+
11
+ - Add immediate and flexible Google Play updates with progress and recovery.
12
+ - Add iOS App Store lookup, direct handoff, and StoreKit product sheets.
13
+ - Expose a typed Expo API and configurable `AppUpdateGate` UI.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # expo-app-updates-android-ios
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Store updates for Expo SDK 58 on Android and iOS. [Documentation](docs/)
4
+
5
+ <p>
6
+ <img src="docs/screenshots/update-available.png" alt="Update available prompt" width="220">
7
+ <img src="docs/screenshots/download-progress.png" alt="Flexible update downloading at 62 percent" width="220">
8
+ <img src="docs/screenshots/ready-to-install.png" alt="Restart and install prompt" width="220">
9
+ </p>
10
+
11
+ Android emulator previews with simulated Google Play responses.
@@ -0,0 +1,24 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'com.andwati.appupdatesandroid'
7
+ version = '0.1.1'
8
+
9
+ android {
10
+ namespace "com.andwati.appupdatesandroid"
11
+ defaultConfig {
12
+ versionCode 2
13
+ versionName "0.1.1"
14
+ }
15
+ lint {
16
+ abortOnError = true
17
+ warningsAsErrors = true
18
+ }
19
+ }
20
+
21
+ dependencies {
22
+ implementation 'com.google.android.play:app-update:2.1.0'
23
+ implementation 'androidx.activity:activity:1.13.0'
24
+ }
@@ -0,0 +1,2 @@
1
+ <manifest>
2
+ </manifest>
@@ -0,0 +1,72 @@
1
+ package com.andwati.appupdatesandroid
2
+
3
+ import expo.modules.kotlin.Promise
4
+ import expo.modules.kotlin.functions.Queues
5
+ import expo.modules.kotlin.modules.Module
6
+ import expo.modules.kotlin.modules.ModuleDefinition
7
+ import expo.modules.kotlin.records.Field
8
+ import expo.modules.kotlin.records.Record
9
+ import expo.modules.kotlin.types.Enumerable
10
+
11
+ private const val INSTALL_EVENT = "onInstallStateChanged"
12
+ private const val FLOW_EVENT = "onUpdateFlowResult"
13
+
14
+ internal enum class AndroidUpdateMode(val value: String, val playMode: PlayUpdateMode) : Enumerable {
15
+ FLEXIBLE(PlayUpdateMode.FLEXIBLE.value, PlayUpdateMode.FLEXIBLE),
16
+ IMMEDIATE(PlayUpdateMode.IMMEDIATE.value, PlayUpdateMode.IMMEDIATE)
17
+ }
18
+
19
+ internal class AndroidStartOptions(
20
+ @Field val mode: AndroidUpdateMode,
21
+ @Field val allowAssetPackDeletion: Boolean = false
22
+ ) : Record
23
+
24
+ class ExpoAppUpdatesAndroidIosModule : Module() {
25
+ private val play by lazy {
26
+ PlayUpdateClient(
27
+ applicationContext = { appContext.reactContext?.applicationContext },
28
+ currentActivity = { appContext.currentActivity },
29
+ onInstallState = { sendEvent(INSTALL_EVENT, it) },
30
+ onFlowResult = { sendEvent(FLOW_EVENT, it) }
31
+ )
32
+ }
33
+
34
+ override fun definition() = ModuleDefinition {
35
+ Name("ExpoAppUpdatesAndroidIos")
36
+ Events(INSTALL_EVENT, FLOW_EVENT)
37
+
38
+ OnStartObserving(INSTALL_EVENT) { play.observeInstallState(true) }
39
+ OnStopObserving(INSTALL_EVENT) { play.observeInstallState(false) }
40
+ OnActivityDestroys { play.onActivityDestroyed() }
41
+ OnDestroy { play.dispose() }
42
+
43
+ AsyncFunction("checkAndroidAsync") { allowAssetPackDeletion: Boolean, promise: Promise ->
44
+ play.check(allowAssetPackDeletion, promise.playCompletion())
45
+ }.runOnQueue(Queues.MAIN)
46
+
47
+ AsyncFunction("startAndroidAsync") { options: AndroidStartOptions, promise: Promise ->
48
+ play.start(options.mode.playMode, options.allowAssetPackDeletion, promise.playCompletion())
49
+ }.runOnQueue(Queues.MAIN)
50
+
51
+ AsyncFunction("resumeAndroidAsync") { allowAssetPackDeletion: Boolean, promise: Promise ->
52
+ play.resume(allowAssetPackDeletion, promise.playCompletion())
53
+ }.runOnQueue(Queues.MAIN)
54
+
55
+ AsyncFunction("completeAndroidAsync") { promise: Promise ->
56
+ play.complete(promise.playCompletion())
57
+ }.runOnQueue(Queues.MAIN)
58
+ }
59
+
60
+ private fun Promise.playCompletion(): PlayCompletion = { result ->
61
+ result.fold(
62
+ onSuccess = { resolve(it) },
63
+ onFailure = { error ->
64
+ if (error is PlayUpdateException) {
65
+ reject(error.code, error.message, error.cause)
66
+ } else {
67
+ reject("ERR_UPDATE_FAILED", error.message, error)
68
+ }
69
+ }
70
+ )
71
+ }
72
+ }
@@ -0,0 +1,335 @@
1
+ package com.andwati.appupdatesandroid
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.os.Handler
6
+ import android.os.Looper
7
+ import androidx.activity.ComponentActivity
8
+ import androidx.activity.result.ActivityResultLauncher
9
+ import androidx.activity.result.IntentSenderRequest
10
+ import androidx.activity.result.contract.ActivityResultContracts
11
+ import androidx.core.content.pm.PackageInfoCompat
12
+ import com.google.android.play.core.appupdate.AppUpdateInfo
13
+ import com.google.android.play.core.appupdate.AppUpdateManager
14
+ import com.google.android.play.core.appupdate.AppUpdateManagerFactory
15
+ import com.google.android.play.core.appupdate.AppUpdateOptions
16
+ import com.google.android.play.core.install.InstallException
17
+ import com.google.android.play.core.install.InstallStateUpdatedListener
18
+ import com.google.android.play.core.install.model.ActivityResult
19
+ import com.google.android.play.core.install.model.AppUpdateType
20
+ import com.google.android.play.core.install.model.InstallErrorCode
21
+ import com.google.android.play.core.install.model.InstallStatus
22
+ import com.google.android.play.core.install.model.UpdateAvailability
23
+ import java.util.UUID
24
+
25
+ internal typealias PlayCompletion = (Result<Map<String, Any>>) -> Unit
26
+
27
+ internal class PlayUpdateException(val code: String, message: String, cause: Throwable?) : Exception(message, cause)
28
+
29
+ internal enum class PlayUpdateMode(val value: String, val type: Int) {
30
+ FLEXIBLE("flexible", AppUpdateType.FLEXIBLE),
31
+ IMMEDIATE("immediate", AppUpdateType.IMMEDIATE)
32
+ }
33
+
34
+ internal class PlayUpdateClient(
35
+ private val applicationContext: () -> Context?,
36
+ private val currentActivity: () -> Activity?,
37
+ private val onInstallState: (Map<String, Any>) -> Unit,
38
+ private val onFlowResult: (Map<String, Any>) -> Unit
39
+ ) {
40
+ private val mainHandler = Handler(Looper.getMainLooper())
41
+ private var manager: AppUpdateManager? = null
42
+ private var observingInstallState = false
43
+ private var listenerRegistered = false
44
+ private var pendingFlow: PendingFlow? = null
45
+ private var completing = false
46
+
47
+ private val installListener = InstallStateUpdatedListener { state ->
48
+ val payload = mutableMapOf<String, Any>("status" to statusName(state.installStatus()))
49
+ if (state.installStatus() == InstallStatus.DOWNLOADING) {
50
+ payload["bytesDownloaded"] = state.bytesDownloaded().toDouble()
51
+ payload["totalBytesToDownload"] = state.totalBytesToDownload().toDouble()
52
+ }
53
+ if (state.installStatus() == InstallStatus.FAILED) {
54
+ payload["errorCode"] = state.installErrorCode()
55
+ }
56
+ onInstallState(payload)
57
+ }
58
+
59
+ fun observeInstallState(observing: Boolean) {
60
+ mainHandler.post {
61
+ observingInstallState = observing
62
+ updateInstallListener()
63
+ }
64
+ }
65
+
66
+ fun onActivityDestroyed() {
67
+ val flow = pendingFlow
68
+ clearPendingFlow()
69
+ if (flow?.launcher != null) {
70
+ onFlowResult(mapOf("mode" to flow.mode.value, "status" to "interrupted"))
71
+ }
72
+ }
73
+
74
+ fun dispose() {
75
+ mainHandler.post {
76
+ observingInstallState = false
77
+ updateInstallListener()
78
+ manager = null
79
+ clearPendingFlow()
80
+ }
81
+ }
82
+
83
+ fun check(allowDeletion: Boolean, callback: PlayCompletion) {
84
+ val context = applicationContext()
85
+ if (context == null) {
86
+ callback.reject("ERR_UPDATE_CHECK", "Android application context is unavailable.", null)
87
+ } else {
88
+ withUpdateInfo(callback, "ERR_UPDATE_CHECK", unsupportedCheck = true) { _, info ->
89
+ callback.resolve(snapshot(context, info, allowDeletion))
90
+ }
91
+ }
92
+ }
93
+
94
+ fun start(mode: PlayUpdateMode, allowDeletion: Boolean, callback: PlayCompletion) {
95
+ startFlow(mode, allowDeletion, resume = false, callback)
96
+ }
97
+
98
+ fun resume(allowDeletion: Boolean, callback: PlayCompletion) {
99
+ startFlow(PlayUpdateMode.IMMEDIATE, allowDeletion, resume = true, callback)
100
+ }
101
+
102
+ private fun withUpdateInfo(
103
+ callback: PlayCompletion,
104
+ errorCode: String,
105
+ unsupportedCheck: Boolean = false,
106
+ onFailure: () -> Unit = {},
107
+ onSuccess: (AppUpdateManager, AppUpdateInfo) -> Unit
108
+ ) {
109
+ fun reject(error: Exception) {
110
+ onFailure()
111
+ if (isUnsupported(error)) {
112
+ val result = if (unsupportedCheck) {
113
+ mapOf("status" to "unsupported", "platform" to "android")
114
+ } else {
115
+ outcome("unsupported")
116
+ }
117
+ callback.resolve(result)
118
+ } else {
119
+ callback.reject(errorCode, error.message ?: "Google Play could not check the update.", error)
120
+ }
121
+ }
122
+
123
+ try {
124
+ val play = manager ?: AppUpdateManagerFactory.create(
125
+ checkNotNull(applicationContext())
126
+ ).also { manager = it }
127
+ updateInstallListener()
128
+ play.appUpdateInfo
129
+ .addOnSuccessListener { info ->
130
+ try {
131
+ onSuccess(play, info)
132
+ } catch (error: Exception) {
133
+ reject(error)
134
+ }
135
+ }
136
+ .addOnFailureListener { reject(it) }
137
+ .addOnCanceledListener { reject(IllegalStateException("Google Play canceled the update request.")) }
138
+ } catch (error: Exception) {
139
+ reject(error)
140
+ }
141
+ }
142
+
143
+ private fun startFlow(
144
+ mode: PlayUpdateMode,
145
+ allowDeletion: Boolean,
146
+ resume: Boolean,
147
+ callback: PlayCompletion
148
+ ) {
149
+ if (pendingFlow != null || completing) {
150
+ callback.resolve(outcome("busy"))
151
+ return
152
+ }
153
+ val activity = activeActivity()
154
+ if (activity == null) {
155
+ callback.reject("ERR_UPDATE_ACTIVITY", "An active Android activity is needed to show Google Play.", null)
156
+ return
157
+ }
158
+
159
+ val flow = PendingFlow(activity, mode)
160
+ pendingFlow = flow
161
+ fun clearFlow() {
162
+ if (pendingFlow === flow) clearPendingFlow()
163
+ }
164
+
165
+ withUpdateInfo(callback, "ERR_UPDATE_LAUNCH", onFailure = ::clearFlow) { play, info ->
166
+ val expectedAvailability = if (resume) {
167
+ UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
168
+ } else {
169
+ UpdateAvailability.UPDATE_AVAILABLE
170
+ }
171
+ val options = allowedOptions(info, mode.type, allowDeletion)
172
+ if (pendingFlow !== flow || activeActivity() !== flow.activity) {
173
+ clearFlow()
174
+ callback.reject("ERR_UPDATE_ACTIVITY", "The Android activity changed before the update could start.", null)
175
+ } else if (info.updateAvailability() != expectedAvailability || options == null ||
176
+ (!resume && info.installStatus() in activeInstallStatuses)
177
+ ) {
178
+ clearFlow()
179
+ callback.resolve(outcome("unavailable"))
180
+ } else {
181
+ val launcher = activity.activityResultRegistry.register(
182
+ "expo-app-updates:play-update:${UUID.randomUUID()}",
183
+ ActivityResultContracts.StartIntentSenderForResult()
184
+ ) { result ->
185
+ if (pendingFlow === flow && flow.launcher != null) {
186
+ clearPendingFlow()
187
+ val status = when (result.resultCode) {
188
+ Activity.RESULT_OK -> "accepted"
189
+ Activity.RESULT_CANCELED -> "canceled"
190
+ ActivityResult.RESULT_IN_APP_UPDATE_FAILED -> "failed"
191
+ else -> "failed"
192
+ }
193
+ onFlowResult(mapOf("mode" to flow.mode.value, "status" to status, "resultCode" to result.resultCode))
194
+ }
195
+ }
196
+ flow.launcher = launcher
197
+
198
+ if (play.startUpdateFlowForResult(info, launcher, options)) {
199
+ callback.resolve(outcome("started"))
200
+ } else {
201
+ clearFlow()
202
+ callback.reject("ERR_UPDATE_LAUNCH", "Google Play did not start the update flow.", null)
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ fun complete(callback: PlayCompletion) {
209
+ if (completing || pendingFlow != null) {
210
+ callback.resolve(outcome("busy"))
211
+ return
212
+ }
213
+ completing = true
214
+ withUpdateInfo(callback, "ERR_UPDATE_INSTALL", onFailure = { completing = false }) { play, info ->
215
+ if (info.installStatus() != InstallStatus.DOWNLOADED) {
216
+ completing = false
217
+ callback.resolve(outcome("unavailable"))
218
+ } else {
219
+ play.completeUpdate()
220
+ .addOnSuccessListener {
221
+ completing = false
222
+ callback.resolve(outcome("requested"))
223
+ }
224
+ .addOnFailureListener {
225
+ completing = false
226
+ callback.reject("ERR_UPDATE_INSTALL", it.message, it)
227
+ }
228
+ .addOnCanceledListener {
229
+ completing = false
230
+ callback.reject("ERR_UPDATE_INSTALL", "Google Play canceled the installation request.", null)
231
+ }
232
+ }
233
+ }
234
+ }
235
+
236
+ private fun updateInstallListener() {
237
+ val play = manager ?: return
238
+ if (observingInstallState == listenerRegistered) return
239
+ if (observingInstallState) play.registerListener(installListener)
240
+ else play.unregisterListener(installListener)
241
+ listenerRegistered = observingInstallState
242
+ }
243
+
244
+ private fun activeActivity(): ComponentActivity? =
245
+ (currentActivity() as? ComponentActivity)?.takeUnless { it.isFinishing || it.isDestroyed }
246
+
247
+ private fun clearPendingFlow() {
248
+ val flow = pendingFlow
249
+ pendingFlow = null
250
+ flow?.launcher?.unregister()
251
+ }
252
+
253
+ @Suppress("DEPRECATION")
254
+ private fun snapshot(context: Context, info: AppUpdateInfo, allowDeletion: Boolean): Map<String, Any> {
255
+ val installed = context.packageManager.getPackageInfo(context.packageName, 0)
256
+ val availability = info.updateAvailability()
257
+ val installStatus = info.installStatus()
258
+ val inProgress = availability == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
259
+ val available = availability == UpdateAvailability.UPDATE_AVAILABLE || inProgress
260
+ val allowedModes = buildList {
261
+ for (mode in PlayUpdateMode.entries) {
262
+ if (allowedOptions(info, mode.type, allowDeletion) != null) add(mode.value)
263
+ }
264
+ }
265
+ val installState = mutableMapOf<String, Any>("status" to statusName(installStatus))
266
+ if (installStatus == InstallStatus.DOWNLOADING) {
267
+ installState["bytesDownloaded"] = info.bytesDownloaded().toDouble()
268
+ installState["totalBytesToDownload"] = info.totalBytesToDownload().toDouble()
269
+ }
270
+
271
+ return buildMap {
272
+ put("platform", "android")
273
+ put("installedVersion", installed.versionName.orEmpty())
274
+ put("installedVersionCode", PackageInfoCompat.getLongVersionCode(installed).toDouble())
275
+ put("allowedModes", allowedModes)
276
+ put("immediateUpdateInProgress", inProgress)
277
+ put("installState", installState)
278
+ put("status", when (availability) {
279
+ UpdateAvailability.UPDATE_AVAILABLE -> "available"
280
+ UpdateAvailability.UPDATE_NOT_AVAILABLE -> "upToDate"
281
+ UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS -> "inProgress"
282
+ else -> "unknown"
283
+ })
284
+ if (available) {
285
+ put("availableVersionCode", info.availableVersionCode())
286
+ put("priority", info.updatePriority())
287
+ info.clientVersionStalenessDays()?.let { put("stalenessDays", it) }
288
+ }
289
+ }
290
+ }
291
+
292
+ private fun allowedOptions(info: AppUpdateInfo, type: Int, allowDeletion: Boolean): AppUpdateOptions? {
293
+ val defaults = AppUpdateOptions.defaultOptions(type)
294
+ if (info.isUpdateTypeAllowed(defaults)) return defaults
295
+ if (!allowDeletion) return null
296
+ val withDeletion = AppUpdateOptions.newBuilder(type).setAllowAssetPackDeletion(true).build()
297
+ return withDeletion.takeIf { info.isUpdateTypeAllowed(it) }
298
+ }
299
+
300
+ private fun isUnsupported(error: Exception): Boolean =
301
+ error is InstallException && error.errorCode in setOf(
302
+ InstallErrorCode.ERROR_API_NOT_AVAILABLE,
303
+ InstallErrorCode.ERROR_PLAY_STORE_NOT_FOUND,
304
+ InstallErrorCode.ERROR_APP_NOT_OWNED
305
+ )
306
+
307
+ private fun statusName(status: Int): String = when (status) {
308
+ InstallStatus.PENDING -> "pending"
309
+ InstallStatus.DOWNLOADING -> "downloading"
310
+ InstallStatus.DOWNLOADED -> "downloaded"
311
+ InstallStatus.INSTALLING -> "installing"
312
+ InstallStatus.INSTALLED -> "installed"
313
+ InstallStatus.FAILED -> "failed"
314
+ InstallStatus.CANCELED -> "canceled"
315
+ else -> "unknown"
316
+ }
317
+
318
+ private fun outcome(status: String) = mapOf("status" to status)
319
+
320
+ private class PendingFlow(val activity: ComponentActivity, val mode: PlayUpdateMode) {
321
+ var launcher: ActivityResultLauncher<IntentSenderRequest>? = null
322
+ }
323
+
324
+ private companion object {
325
+ val activeInstallStatuses = setOf(
326
+ InstallStatus.PENDING, InstallStatus.DOWNLOADING, InstallStatus.DOWNLOADED, InstallStatus.INSTALLING
327
+ )
328
+ }
329
+ }
330
+
331
+ private fun PlayCompletion.resolve(value: Map<String, Any>) = invoke(Result.success(value))
332
+
333
+ private fun PlayCompletion.reject(code: String, message: String?, cause: Throwable?) {
334
+ invoke(Result.failure(PlayUpdateException(code, message ?: "Google Play update failed.", cause)))
335
+ }
@@ -0,0 +1,40 @@
1
+ import { type JSX, type ReactNode, type Ref } from 'react';
2
+ import type { UpdateInfo } from './ExpoAppUpdatesAndroidIos.types';
3
+ import { type UpdateGateOptions } from './useAppUpdateGate';
4
+ export interface AppUpdateGateRef {
5
+ /** Checks immediately and returns the result, or undefined if the check fails. */
6
+ checkAsync(): Promise<UpdateInfo | undefined>;
7
+ }
8
+ export interface AppUpdateCopy {
9
+ offerTitle: string;
10
+ offerMessage: string;
11
+ requiredTitle: string;
12
+ requiredMessage: string;
13
+ update: string;
14
+ later: string;
15
+ openAppStore: string;
16
+ releaseNotes: string;
17
+ downloadTitle: string;
18
+ installingTitle: string;
19
+ readyTitle: string;
20
+ readyMessage: string;
21
+ restart: string;
22
+ recheck: string;
23
+ error: string;
24
+ }
25
+ export interface AppUpdateTheme {
26
+ background: string;
27
+ text: string;
28
+ secondaryText: string;
29
+ accent: string;
30
+ accentText: string;
31
+ backdrop: string;
32
+ }
33
+ export interface AppUpdateGateProps extends UpdateGateOptions {
34
+ children: ReactNode;
35
+ ref?: Ref<AppUpdateGateRef>;
36
+ copy?: Partial<AppUpdateCopy>;
37
+ theme?: Partial<AppUpdateTheme>;
38
+ showReleaseNotes?: boolean;
39
+ }
40
+ export declare function AppUpdateGate(props: AppUpdateGateProps): JSX.Element;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppUpdateGate = AppUpdateGate;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_1 = require("react");
6
+ const react_native_1 = require("react-native");
7
+ const useAppUpdateGate_1 = require("./useAppUpdateGate");
8
+ const defaultCopy = {
9
+ offerTitle: 'Update available',
10
+ offerMessage: 'A newer version of this app is available.',
11
+ requiredTitle: 'Update required',
12
+ requiredMessage: 'Update this app to continue.',
13
+ update: 'Update',
14
+ later: 'Later',
15
+ openAppStore: 'Open App Store',
16
+ releaseNotes: 'Release notes',
17
+ downloadTitle: 'Downloading update',
18
+ installingTitle: 'Installing update',
19
+ readyTitle: 'Update ready to install',
20
+ readyMessage: 'Restart the app to install the downloaded update.',
21
+ restart: 'Restart and install',
22
+ recheck: 'Check again',
23
+ error: 'The update could not continue. Try again.',
24
+ };
25
+ const light = {
26
+ background: '#ffffff',
27
+ text: '#18181b',
28
+ secondaryText: '#52525b',
29
+ accent: '#234cc7',
30
+ accentText: '#ffffff',
31
+ backdrop: 'rgba(0, 0, 0, 0.55)',
32
+ };
33
+ const dark = {
34
+ background: '#242427',
35
+ text: '#fafafa',
36
+ secondaryText: '#d4d4d8',
37
+ accent: '#aac1ff',
38
+ accentText: '#151d32',
39
+ backdrop: 'rgba(0, 0, 0, 0.72)',
40
+ };
41
+ function AppUpdateGate(props) {
42
+ const { children, ref, showReleaseNotes = true } = props;
43
+ const { offer, install, error, busy, check, update, complete, defer, restartDeferred, setRestartDeferred, } = (0, useAppUpdateGate_1.useAppUpdateGate)(props);
44
+ const copy = { ...defaultCopy, ...props.copy };
45
+ const theme = { ...((0, react_native_1.useColorScheme)() === 'dark' ? dark : light), ...props.theme };
46
+ const ready = install.status === 'downloaded';
47
+ const waiting = install.status === 'pending' ||
48
+ install.status === 'downloading' ||
49
+ install.status === 'installing';
50
+ const required = offer?.required ?? false;
51
+ const showDialog = ready
52
+ ? required || !restartDeferred
53
+ : offer !== null && (required || !waiting);
54
+ const notes = showReleaseNotes && offer?.info.platform === 'ios' ? offer.info.releaseNotes : undefined;
55
+ const progress = downloadPercent(install.bytesDownloaded, install.totalBytesToDownload);
56
+ const progressTitle = install.status === 'installing' ? copy.installingTitle : copy.downloadTitle;
57
+ (0, react_1.useImperativeHandle)(ref, () => ({ checkAsync: () => check() }), [check]);
58
+ (0, react_1.useEffect)(() => {
59
+ if (!showDialog || react_native_1.Platform.OS !== 'android') {
60
+ return;
61
+ }
62
+ const subscription = react_native_1.BackHandler.addEventListener('hardwareBackPress', () => true);
63
+ return () => subscription.remove();
64
+ }, [showDialog]);
65
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.root, children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { accessibilityElementsHidden: showDialog, importantForAccessibility: showDialog ? 'no-hide-descendants' : 'auto', pointerEvents: showDialog ? 'none' : 'auto', style: styles.root, children: children }), waiting && !showDialog && ((0, jsx_runtime_1.jsx)(react_native_1.View, { pointerEvents: "none", style: styles.bannerContainer, children: (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.banner, { backgroundColor: theme.background }], children: (0, jsx_runtime_1.jsx)(Progress, { theme: theme, title: progressTitle, percent: progress }) }) })), ready && !showDialog && ((0, jsx_runtime_1.jsx)(react_native_1.View, { pointerEvents: "box-none", style: styles.bannerContainer, children: (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.banner, { backgroundColor: theme.background }], children: (0, jsx_runtime_1.jsx)(Action, { label: copy.readyTitle, onPress: () => setRestartDeferred(false), theme: theme, disabled: busy }) }) })), showDialog && ((0, jsx_runtime_1.jsx)(react_native_1.View, { accessibilityViewIsModal: true, style: [styles.backdrop, { backgroundColor: theme.backdrop }], children: (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.dialog, { backgroundColor: theme.background }], children: (0, jsx_runtime_1.jsxs)(react_native_1.ScrollView, { keyboardShouldPersistTaps: "handled", contentContainerStyle: styles.dialogContent, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { accessibilityRole: "header", style: [styles.title, { color: theme.text }], children: ready ? copy.readyTitle : required ? copy.requiredTitle : copy.offerTitle }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: theme.secondaryText }, children: ready ? copy.readyMessage : required ? copy.requiredMessage : copy.offerMessage }), notes && !ready && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.notes, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { accessibilityRole: "header", style: [styles.notesTitle, { color: theme.text }], children: copy.releaseNotes }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: theme.secondaryText }, children: notes })] })), error && ((0, jsx_runtime_1.jsx)(react_native_1.Text, { accessibilityRole: "alert", accessibilityLiveRegion: "polite", style: { color: theme.text }, children: copy.error })), waiting && (0, jsx_runtime_1.jsx)(Progress, { theme: theme, title: progressTitle, percent: progress }), busy && !waiting && (0, jsx_runtime_1.jsx)(react_native_1.ActivityIndicator, { color: theme.accent }), ready ? ((0, jsx_runtime_1.jsx)(Action, { label: copy.restart, onPress: complete, theme: theme, disabled: busy, primary: true })) : (!waiting && ((0, jsx_runtime_1.jsx)(Action, { label: copy.update, onPress: () => update(), theme: theme, disabled: busy, primary: true }))), !ready &&
66
+ !waiting &&
67
+ offer?.info.platform === 'ios' &&
68
+ props.iosMode === 'storeKit' && ((0, jsx_runtime_1.jsx)(Action, { label: copy.openAppStore, onPress: () => update('appStore'), theme: theme, disabled: busy })), !required && ((0, jsx_runtime_1.jsx)(Action, { label: copy.later, onPress: ready ? () => setRestartDeferred(true) : defer, theme: theme, disabled: busy })), (required || error) && ((0, jsx_runtime_1.jsx)(Action, { label: copy.recheck, onPress: () => {
69
+ void check();
70
+ }, theme: theme, disabled: busy }))] }) }) }))] }));
71
+ }
72
+ function downloadPercent(downloaded, total) {
73
+ if (downloaded === undefined || total === undefined || total <= 0) {
74
+ return undefined;
75
+ }
76
+ return Math.max(0, Math.min(100, Math.round((downloaded / total) * 100)));
77
+ }
78
+ function Progress({ theme, title, percent, }) {
79
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { accessible: true, accessibilityRole: "progressbar", accessibilityLabel: title, accessibilityValue: percent === undefined ? undefined : { min: 0, max: 100, now: percent }, style: styles.progress, children: [percent === undefined && (0, jsx_runtime_1.jsx)(react_native_1.ActivityIndicator, { color: theme.accent }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: theme.text }, children: percent === undefined ? title : `${title} (${percent}%)` }), percent !== undefined && ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.track, { backgroundColor: theme.secondaryText }], children: (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.fill, { width: `${percent}%`, backgroundColor: theme.accent }] }) }))] }));
80
+ }
81
+ function Action({ label, onPress, theme, disabled, primary = false }) {
82
+ return ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", accessibilityState: { disabled }, disabled: disabled, onPress: onPress, style: ({ pressed }) => [
83
+ styles.action,
84
+ primary && { backgroundColor: theme.accent },
85
+ (pressed || disabled) && styles.dim,
86
+ ], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.actionLabel, { color: primary ? theme.accentText : theme.accent }], children: label }) }));
87
+ }
88
+ const styles = react_native_1.StyleSheet.create({
89
+ root: { flex: 1 },
90
+ bannerContainer: { ...react_native_1.StyleSheet.absoluteFill, justifyContent: 'flex-end', padding: 20 },
91
+ banner: { alignSelf: 'center', width: '100%', maxWidth: 440, padding: 18, borderRadius: 16 },
92
+ backdrop: {
93
+ ...react_native_1.StyleSheet.absoluteFill,
94
+ alignItems: 'center',
95
+ justifyContent: 'center',
96
+ padding: 20,
97
+ },
98
+ dialog: { width: '100%', maxWidth: 440, maxHeight: '85%', borderRadius: 20, overflow: 'hidden' },
99
+ dialogContent: { padding: 22, gap: 12 },
100
+ title: { fontSize: 22, fontWeight: '700' },
101
+ notes: { gap: 4 },
102
+ notesTitle: { fontWeight: '600' },
103
+ progress: { gap: 8, alignItems: 'center' },
104
+ track: { width: '100%', height: 6, borderRadius: 3, overflow: 'hidden' },
105
+ fill: { height: '100%' },
106
+ action: {
107
+ minHeight: 48,
108
+ padding: 10,
109
+ borderRadius: 10,
110
+ justifyContent: 'center',
111
+ alignItems: 'center',
112
+ },
113
+ actionLabel: { fontWeight: '600', textAlign: 'center' },
114
+ dim: { opacity: 0.6 },
115
+ });