@algocare/react-native-code-push 12.6.3 → 13.0.0-rc.0

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 (292) hide show
  1. package/CodePush.podspec +6 -8
  2. package/README.md +343 -586
  3. package/android/app/build.gradle +2 -1
  4. package/android/app/proguard-rules.pro +14 -0
  5. package/android/app/src/debug/AndroidManifest.xml +9 -0
  6. package/android/app/src/main/AndroidManifest.xml +1 -2
  7. package/android/app/src/main/java/com/microsoft/codepush/react/CodePush.java +14 -139
  8. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushConstants.java +0 -3
  9. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushNativeModule.java +108 -63
  10. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushUpdateManager.java +2 -33
  11. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushUpdateUtils.java +13 -109
  12. package/android/build.gradle +3 -0
  13. package/app.plugin.js +1 -0
  14. package/bin/code-push.js +6 -0
  15. package/cli/commands/bundleCommand/bundleCodePush.ts +118 -0
  16. package/cli/commands/bundleCommand/index.ts +34 -0
  17. package/cli/commands/createHistoryCommand/createReleaseHistory.ts +37 -0
  18. package/cli/commands/createHistoryCommand/createReleaseHistoryList.ts +40 -0
  19. package/cli/commands/createHistoryCommand/index.ts +44 -0
  20. package/cli/commands/createPullRequestHistoryCommand/createPullRequestHistory.ts +33 -0
  21. package/cli/commands/createPullRequestHistoryCommand/index.ts +31 -0
  22. package/cli/commands/createPullRequestReleaseCommand/addToPullRequestRelease.ts +71 -0
  23. package/cli/commands/createPullRequestReleaseCommand/createPullRequestRelease.ts +75 -0
  24. package/cli/commands/createPullRequestReleaseCommand/index.ts +74 -0
  25. package/cli/commands/getPackageHashCommand/index.ts +45 -0
  26. package/cli/commands/initCommand/index.ts +14 -0
  27. package/cli/commands/initCommand/initAndroid.ts +91 -0
  28. package/cli/commands/initCommand/initIos.ts +123 -0
  29. package/cli/commands/initCommand/test/initAndroid.test.ts +128 -0
  30. package/cli/commands/initCommand/test/initIos.test.ts +99 -0
  31. package/cli/commands/releaseCommand/addToReleaseHistory.ts +57 -0
  32. package/cli/commands/releaseCommand/index.ts +90 -0
  33. package/cli/commands/releaseCommand/release.ts +105 -0
  34. package/cli/commands/removePullRequestHistoryCommand/index.ts +37 -0
  35. package/cli/commands/removePullRequestHistoryCommand/removePullRequestHistory.ts +28 -0
  36. package/cli/commands/showHistoryCommand/index.ts +31 -0
  37. package/cli/commands/updateHistoryCommand/index.ts +55 -0
  38. package/cli/commands/updateHistoryCommand/updateReleaseHistory.ts +42 -0
  39. package/cli/constant.ts +4 -0
  40. package/cli/dist/commands/bundleCommand/bundleCodePush.js +65 -0
  41. package/cli/dist/commands/bundleCommand/index.js +15 -0
  42. package/cli/dist/commands/createHistoryCommand/createReleaseHistory.js +25 -0
  43. package/cli/dist/commands/createHistoryCommand/createReleaseHistoryList.js +27 -0
  44. package/cli/dist/commands/createHistoryCommand/index.js +20 -0
  45. package/cli/dist/commands/createPullRequestHistoryCommand/createPullRequestHistory.js +23 -0
  46. package/cli/dist/commands/createPullRequestHistoryCommand/index.js +15 -0
  47. package/cli/dist/commands/createPullRequestReleaseCommand/addToPullRequestRelease.js +51 -0
  48. package/cli/dist/commands/createPullRequestReleaseCommand/createPullRequestRelease.js +39 -0
  49. package/cli/dist/commands/createPullRequestReleaseCommand/index.js +35 -0
  50. package/cli/dist/commands/getPackageHashCommand/index.js +26 -0
  51. package/cli/dist/commands/initCommand/index.js +12 -0
  52. package/cli/dist/commands/initCommand/initAndroid.js +73 -0
  53. package/cli/dist/commands/initCommand/initIos.js +108 -0
  54. package/cli/dist/commands/initCommand/test/initAndroid.test.js +113 -0
  55. package/cli/dist/commands/initCommand/test/initIos.test.js +95 -0
  56. package/cli/dist/commands/releaseCommand/addToReleaseHistory.js +35 -0
  57. package/cli/dist/commands/releaseCommand/index.js +45 -0
  58. package/cli/dist/commands/releaseCommand/release.js +62 -0
  59. package/cli/dist/commands/removePullRequestHistoryCommand/index.js +19 -0
  60. package/cli/dist/commands/removePullRequestHistoryCommand/removePullRequestHistory.js +18 -0
  61. package/cli/dist/commands/showHistoryCommand/index.js +15 -0
  62. package/cli/dist/commands/updateHistoryCommand/index.js +31 -0
  63. package/cli/dist/commands/updateHistoryCommand/updateReleaseHistory.js +28 -0
  64. package/cli/dist/constant.js +4 -0
  65. package/cli/dist/functions/getReactTempDir.js +10 -0
  66. package/cli/{functions → dist/functions}/makeCodePushBundle.js +5 -11
  67. package/cli/{functions → dist/functions}/prepareToBundleJS.js +2 -5
  68. package/cli/dist/functions/runExpoBundleCommand.js +35 -0
  69. package/cli/{functions → dist/functions}/runHermesEmitBinaryCommand.js +36 -71
  70. package/cli/{functions → dist/functions}/runReactNativeBundleCommand.js +19 -24
  71. package/cli/dist/index.js +54 -0
  72. package/cli/dist/utils/datetime.js +17 -0
  73. package/cli/dist/utils/file-utils.js +19 -0
  74. package/cli/dist/utils/fsUtils.js +44 -0
  75. package/cli/{utils → dist/utils}/hash-utils.js +19 -130
  76. package/cli/{utils → dist/utils}/promisfied-fs.js +5 -16
  77. package/cli/dist/utils/showLogo.js +21 -0
  78. package/cli/dist/utils/unzip.js +41 -0
  79. package/cli/{utils → dist/utils}/zip.js +15 -51
  80. package/cli/functions/{getReactTempDir.js → getReactTempDir.ts} +2 -6
  81. package/cli/functions/makeCodePushBundle.ts +26 -0
  82. package/cli/functions/prepareToBundleJS.ts +10 -0
  83. package/cli/functions/runExpoBundleCommand.ts +45 -0
  84. package/cli/functions/runHermesEmitBinaryCommand.ts +203 -0
  85. package/cli/functions/runReactNativeBundleCommand.ts +67 -0
  86. package/cli/index.ts +68 -0
  87. package/cli/package.json +35 -0
  88. package/cli/utils/datetime.ts +19 -0
  89. package/cli/utils/{file-utils.js → file-utils.ts} +4 -21
  90. package/cli/utils/fsUtils.ts +50 -0
  91. package/cli/utils/hash-utils.ts +143 -0
  92. package/cli/utils/promisfied-fs.ts +19 -0
  93. package/cli/utils/{showLogo.js → showLogo.ts} +4 -6
  94. package/cli/utils/unzip.ts +46 -0
  95. package/cli/utils/zip.ts +65 -0
  96. package/expo/plugin/withCodePush.js +14 -0
  97. package/expo/plugin/withCodePushAndroid.js +92 -0
  98. package/expo/plugin/withCodePushIos.js +143 -0
  99. package/ios/CodePush/CodePush.h +0 -16
  100. package/ios/CodePush/CodePush.m +30 -20
  101. package/ios/CodePush/CodePushConfig.m +1 -11
  102. package/ios/CodePush/CodePushPackage.m +12 -69
  103. package/ios/CodePush/CodePushUpdateUtils.m +1 -91
  104. package/ios/CodePush/SSZipArchive/Info.plist +26 -0
  105. package/ios/CodePush/SSZipArchive/README.md +1 -1
  106. package/ios/CodePush/SSZipArchive/SSZipArchive.h +129 -27
  107. package/ios/CodePush/SSZipArchive/SSZipArchive.m +1119 -314
  108. package/ios/CodePush/SSZipArchive/SSZipCommon.h +71 -0
  109. package/ios/CodePush/SSZipArchive/Supporting Files/PrivacyInfo.xcprivacy +23 -0
  110. package/ios/CodePush/SSZipArchive/include/ZipArchive.h +25 -0
  111. package/ios/CodePush/SSZipArchive/minizip/LICENSE +17 -0
  112. package/ios/CodePush/SSZipArchive/minizip/mz.h +273 -0
  113. package/ios/CodePush/SSZipArchive/minizip/mz_compat.c +1306 -0
  114. package/ios/CodePush/SSZipArchive/minizip/mz_compat.h +346 -0
  115. package/ios/CodePush/SSZipArchive/minizip/mz_crypt.c +187 -0
  116. package/ios/CodePush/SSZipArchive/minizip/mz_crypt.h +65 -0
  117. package/ios/CodePush/SSZipArchive/minizip/mz_crypt_apple.c +526 -0
  118. package/ios/CodePush/SSZipArchive/minizip/mz_os.c +348 -0
  119. package/ios/CodePush/SSZipArchive/minizip/mz_os.h +176 -0
  120. package/ios/CodePush/SSZipArchive/minizip/mz_os_posix.c +350 -0
  121. package/ios/CodePush/SSZipArchive/minizip/mz_strm.c +556 -0
  122. package/ios/CodePush/SSZipArchive/minizip/mz_strm.h +132 -0
  123. package/ios/CodePush/SSZipArchive/minizip/mz_strm_buf.c +383 -0
  124. package/ios/CodePush/SSZipArchive/minizip/mz_strm_buf.h +42 -0
  125. package/ios/CodePush/SSZipArchive/minizip/mz_strm_mem.c +269 -0
  126. package/ios/CodePush/SSZipArchive/minizip/mz_strm_mem.h +48 -0
  127. package/ios/CodePush/SSZipArchive/minizip/mz_strm_os.h +40 -0
  128. package/ios/CodePush/SSZipArchive/minizip/mz_strm_os_posix.c +203 -0
  129. package/ios/CodePush/SSZipArchive/minizip/mz_strm_pkcrypt.c +334 -0
  130. package/ios/CodePush/SSZipArchive/minizip/mz_strm_pkcrypt.h +46 -0
  131. package/ios/CodePush/SSZipArchive/minizip/mz_strm_split.c +429 -0
  132. package/ios/CodePush/SSZipArchive/minizip/mz_strm_split.h +43 -0
  133. package/ios/CodePush/SSZipArchive/minizip/mz_strm_wzaes.c +360 -0
  134. package/ios/CodePush/SSZipArchive/minizip/mz_strm_wzaes.h +46 -0
  135. package/ios/CodePush/SSZipArchive/minizip/mz_strm_zlib.c +389 -0
  136. package/ios/CodePush/SSZipArchive/minizip/mz_strm_zlib.h +43 -0
  137. package/ios/CodePush/SSZipArchive/minizip/mz_zip.c +2782 -0
  138. package/ios/CodePush/SSZipArchive/minizip/mz_zip.h +262 -0
  139. package/ios/CodePush/SSZipArchive/minizip/mz_zip_rw.c +1942 -0
  140. package/ios/CodePush/SSZipArchive/minizip/mz_zip_rw.h +285 -0
  141. package/ios/CodePush.xcodeproj/project.pbxproj +244 -453
  142. package/ios/PrivacyInfo.xcprivacy +31 -0
  143. package/package.json +67 -41
  144. package/react-native.config.js +1 -1
  145. package/{AlertAdapter.js → src/AlertAdapter.js} +5 -5
  146. package/src/CodePush.js +947 -0
  147. package/{package-mixins.js → src/package-mixins.js} +1 -1
  148. package/{versioning → src/versioning}/BaseVersioning.js +12 -1
  149. package/{versioning → src/versioning}/SemverVersioning.test.js +78 -0
  150. package/typings/react-native-code-push.d.ts +559 -495
  151. package/CONTRIBUTING.md +0 -134
  152. package/CodePush.js +0 -972
  153. package/SECURITY.md +0 -41
  154. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushBuilder.java +0 -37
  155. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushInvalidPublicKeyException.java +0 -12
  156. package/android/app/src/main/java/com/microsoft/codepush/react/ReactInstanceHolder.java +0 -17
  157. package/android/codepush.gradle +0 -162
  158. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  159. package/android/gradle/wrapper/gradle-wrapper.properties +0 -5
  160. package/android/gradlew +0 -164
  161. package/android/gradlew.bat +0 -90
  162. package/babel.config.js +0 -3
  163. package/cli/commands/bundleCommand/bundleCodePush.js +0 -57
  164. package/cli/commands/bundleCommand/index.js +0 -55
  165. package/cli/commands/common.js +0 -245
  166. package/cli/commands/createHistoryCommand/createReleaseHistory.js +0 -42
  167. package/cli/commands/createHistoryCommand/createReleaseHistoryList.js +0 -52
  168. package/cli/commands/createHistoryCommand/index.js +0 -95
  169. package/cli/commands/createPullRequestHistoryCommand/createPullRequestHistory.js +0 -34
  170. package/cli/commands/createPullRequestHistoryCommand/index.js +0 -29
  171. package/cli/commands/createPullRequestReleaseCommand/addToPullRequestRelease.js +0 -74
  172. package/cli/commands/createPullRequestReleaseCommand/createPullRequestRelease.js +0 -91
  173. package/cli/commands/createPullRequestReleaseCommand/index.js +0 -68
  174. package/cli/commands/getPackageHashCommand/index.js +0 -42
  175. package/cli/commands/releaseCommand/addToReleaseHistory.js +0 -85
  176. package/cli/commands/releaseCommand/index.js +0 -151
  177. package/cli/commands/releaseCommand/release.js +0 -121
  178. package/cli/commands/removePullRequestHistoryCommand/index.js +0 -28
  179. package/cli/commands/removePullRequestHistoryCommand/removePullRequestHistory.js +0 -23
  180. package/cli/commands/showHistoryCommand/index.js +0 -88
  181. package/cli/commands/updateHistoryCommand/index.js +0 -123
  182. package/cli/commands/updateHistoryCommand/updateReleaseHistory.js +0 -69
  183. package/cli/constant.js +0 -8
  184. package/cli/index.js +0 -63
  185. package/cli/utils/datetime.js +0 -22
  186. package/cli/utils/fsUtils.js +0 -64
  187. package/cli/utils/version.js +0 -26
  188. package/code-push.config.example.supabase.ts +0 -114
  189. package/code-push.config.js +0 -229
  190. package/code-push.config.ts +0 -175
  191. package/docs/api-android.md +0 -83
  192. package/docs/api-ios.md +0 -31
  193. package/docs/api-js.md +0 -592
  194. package/docs/multi-deployment-testing-android.md +0 -148
  195. package/docs/multi-deployment-testing-ios.md +0 -59
  196. package/docs/setup-android.md +0 -482
  197. package/docs/setup-ios.md +0 -280
  198. package/eslint.config.mjs +0 -32
  199. package/ios/CodePush/Base64/Base64/MF_Base64Additions.h +0 -34
  200. package/ios/CodePush/Base64/Base64/MF_Base64Additions.m +0 -252
  201. package/ios/CodePush/Base64/README.md +0 -47
  202. package/ios/CodePush/JWT/Core/Algorithms/Base/JWTAlgorithm.h +0 -69
  203. package/ios/CodePush/JWT/Core/Algorithms/Base/JWTAlgorithmFactory.h +0 -16
  204. package/ios/CodePush/JWT/Core/Algorithms/Base/JWTAlgorithmFactory.m +0 -51
  205. package/ios/CodePush/JWT/Core/Algorithms/Base/JWTAlgorithmNone.h +0 -15
  206. package/ios/CodePush/JWT/Core/Algorithms/Base/JWTAlgorithmNone.m +0 -55
  207. package/ios/CodePush/JWT/Core/Algorithms/ESFamily/JWTAlgorithmESBase.h +0 -24
  208. package/ios/CodePush/JWT/Core/Algorithms/ESFamily/JWTAlgorithmESBase.m +0 -41
  209. package/ios/CodePush/JWT/Core/Algorithms/HSFamily/JWTAlgorithmHSBase.h +0 -28
  210. package/ios/CodePush/JWT/Core/Algorithms/HSFamily/JWTAlgorithmHSBase.m +0 -205
  211. package/ios/CodePush/JWT/Core/Algorithms/Holders/JWTAlgorithmDataHolder.h +0 -103
  212. package/ios/CodePush/JWT/Core/Algorithms/Holders/JWTAlgorithmDataHolder.m +0 -322
  213. package/ios/CodePush/JWT/Core/Algorithms/Holders/JWTAlgorithmDataHolderChain.h +0 -37
  214. package/ios/CodePush/JWT/Core/Algorithms/Holders/JWTAlgorithmDataHolderChain.m +0 -145
  215. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/JWTAlgorithmRSBase.h +0 -35
  216. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/JWTAlgorithmRSBase.m +0 -551
  217. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/JWTRSAlgorithm.h +0 -23
  218. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/RSKeys/JWTCryptoKey.h +0 -43
  219. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/RSKeys/JWTCryptoKey.m +0 -230
  220. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/RSKeys/JWTCryptoKeyExtractor.h +0 -31
  221. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/RSKeys/JWTCryptoKeyExtractor.m +0 -113
  222. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/RSKeys/JWTCryptoSecurity.h +0 -38
  223. package/ios/CodePush/JWT/Core/Algorithms/RSFamily/RSKeys/JWTCryptoSecurity.m +0 -500
  224. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaim.h +0 -18
  225. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaim.m +0 -214
  226. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaimsSet.h +0 -23
  227. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaimsSet.m +0 -29
  228. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaimsSetSerializer.h +0 -19
  229. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaimsSetSerializer.m +0 -68
  230. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaimsSetVerifier.h +0 -18
  231. package/ios/CodePush/JWT/Core/ClaimSet/JWTClaimsSetVerifier.m +0 -72
  232. package/ios/CodePush/JWT/Core/Coding/JWTCoding+ResultTypes.h +0 -67
  233. package/ios/CodePush/JWT/Core/Coding/JWTCoding+ResultTypes.m +0 -111
  234. package/ios/CodePush/JWT/Core/Coding/JWTCoding+VersionOne.h +0 -119
  235. package/ios/CodePush/JWT/Core/Coding/JWTCoding+VersionOne.m +0 -307
  236. package/ios/CodePush/JWT/Core/Coding/JWTCoding+VersionThree.h +0 -94
  237. package/ios/CodePush/JWT/Core/Coding/JWTCoding+VersionThree.m +0 -619
  238. package/ios/CodePush/JWT/Core/Coding/JWTCoding+VersionTwo.h +0 -164
  239. package/ios/CodePush/JWT/Core/Coding/JWTCoding+VersionTwo.m +0 -514
  240. package/ios/CodePush/JWT/Core/Coding/JWTCoding.h +0 -24
  241. package/ios/CodePush/JWT/Core/Coding/JWTCoding.m +0 -11
  242. package/ios/CodePush/JWT/Core/FrameworkSupplement/JWT.h +0 -52
  243. package/ios/CodePush/JWT/Core/FrameworkSupplement/Map.modulemap +0 -5
  244. package/ios/CodePush/JWT/Core/Supplement/JWTBase64Coder.h +0 -28
  245. package/ios/CodePush/JWT/Core/Supplement/JWTBase64Coder.m +0 -70
  246. package/ios/CodePush/JWT/Core/Supplement/JWTDeprecations.h +0 -22
  247. package/ios/CodePush/JWT/Core/Supplement/JWTErrorDescription.h +0 -34
  248. package/ios/CodePush/JWT/Core/Supplement/JWTErrorDescription.m +0 -73
  249. package/ios/CodePush/JWT/LICENSE +0 -19
  250. package/ios/CodePush/JWT/README.md +0 -489
  251. package/ios/CodePush/SSZipArchive/Common.h +0 -81
  252. package/ios/CodePush/SSZipArchive/aes/aes.h +0 -198
  253. package/ios/CodePush/SSZipArchive/aes/aes_via_ace.h +0 -541
  254. package/ios/CodePush/SSZipArchive/aes/aescrypt.c +0 -294
  255. package/ios/CodePush/SSZipArchive/aes/aeskey.c +0 -548
  256. package/ios/CodePush/SSZipArchive/aes/aesopt.h +0 -739
  257. package/ios/CodePush/SSZipArchive/aes/aestab.c +0 -391
  258. package/ios/CodePush/SSZipArchive/aes/aestab.h +0 -173
  259. package/ios/CodePush/SSZipArchive/aes/brg_endian.h +0 -126
  260. package/ios/CodePush/SSZipArchive/aes/brg_types.h +0 -219
  261. package/ios/CodePush/SSZipArchive/aes/entropy.c +0 -54
  262. package/ios/CodePush/SSZipArchive/aes/entropy.h +0 -16
  263. package/ios/CodePush/SSZipArchive/aes/fileenc.c +0 -144
  264. package/ios/CodePush/SSZipArchive/aes/fileenc.h +0 -121
  265. package/ios/CodePush/SSZipArchive/aes/hmac.c +0 -145
  266. package/ios/CodePush/SSZipArchive/aes/hmac.h +0 -103
  267. package/ios/CodePush/SSZipArchive/aes/prng.c +0 -155
  268. package/ios/CodePush/SSZipArchive/aes/prng.h +0 -82
  269. package/ios/CodePush/SSZipArchive/aes/pwd2key.c +0 -103
  270. package/ios/CodePush/SSZipArchive/aes/pwd2key.h +0 -57
  271. package/ios/CodePush/SSZipArchive/aes/sha1.c +0 -258
  272. package/ios/CodePush/SSZipArchive/aes/sha1.h +0 -73
  273. package/ios/CodePush/SSZipArchive/minizip/crypt.h +0 -130
  274. package/ios/CodePush/SSZipArchive/minizip/ioapi.c +0 -369
  275. package/ios/CodePush/SSZipArchive/minizip/ioapi.h +0 -175
  276. package/ios/CodePush/SSZipArchive/minizip/mztools.c +0 -284
  277. package/ios/CodePush/SSZipArchive/minizip/mztools.h +0 -31
  278. package/ios/CodePush/SSZipArchive/minizip/unzip.c +0 -1839
  279. package/ios/CodePush/SSZipArchive/minizip/unzip.h +0 -248
  280. package/ios/CodePush/SSZipArchive/minizip/zip.c +0 -1910
  281. package/ios/CodePush/SSZipArchive/minizip/zip.h +0 -202
  282. package/scripts/generateBundledResourcesHash.js +0 -125
  283. package/scripts/getFilesInFolder.js +0 -19
  284. package/scripts/recordFilesBeforeBundleCommand.js +0 -41
  285. package/tsconfig.json +0 -20
  286. package/tslint.json +0 -32
  287. /package/{logging.js → src/logging.js} +0 -0
  288. /package/{versioning → src/versioning}/BaseVersioning.test.js +0 -0
  289. /package/{versioning → src/versioning}/IncrementalVersioning.js +0 -0
  290. /package/{versioning → src/versioning}/IncrementalVersioning.test.js +0 -0
  291. /package/{versioning → src/versioning}/SemverVersioning.js +0 -0
  292. /package/{versioning → src/versioning}/index.js +0 -0
@@ -0,0 +1,947 @@
1
+ import { Alert } from "./AlertAdapter";
2
+ import { AppState, Platform } from "react-native";
3
+ import log from "./logging";
4
+ import hoistStatics from 'hoist-non-react-statics';
5
+ import { SemverVersioning } from './versioning/SemverVersioning'
6
+
7
+ let NativeCodePush = require("react-native").NativeModules.CodePush;
8
+ const PackageMixins = require("./package-mixins")(NativeCodePush);
9
+
10
+ const DEPLOYMENT_KEY = 'deprecated_deployment_key';
11
+
12
+ /**
13
+ * @param deviceId {string}
14
+ * @returns {number}
15
+ */
16
+ function hashDeviceId(deviceId) {
17
+ let hash = 0;
18
+ for (let i = 0; i < deviceId.length; i++) {
19
+ hash = ((hash << 5) - hash) + deviceId.charCodeAt(i);
20
+ hash |= 0; // Convert to 32bit int
21
+ }
22
+ return Math.abs(hash);
23
+ }
24
+
25
+ /**
26
+ * @param clientId {string}
27
+ * @param packageHash {string}
28
+ * @returns {number}
29
+ */
30
+ function getBucket(clientId, packageHash) {
31
+ const hash = hashDeviceId(`${clientId ?? ''}_${packageHash ?? ''}`);
32
+ return (Math.abs(hash) % 100);
33
+ }
34
+
35
+ /**
36
+ * Note that the `clientUniqueId` value may not guarantee the same value if the app is deleted and re-installed.
37
+ * In other words, if a user re-installs the app, the result of this function may change.
38
+ * @returns {Promise<boolean>}
39
+ */
40
+ async function decideLatestReleaseIsInRollout(versioning, clientId, onRolloutSkipped) {
41
+ const [latestVersion, latestReleaseInfo] = versioning.findLatestRelease();
42
+
43
+ if (latestReleaseInfo.rollout === undefined || latestReleaseInfo.rollout >= 100) {
44
+ return true;
45
+ }
46
+
47
+ const bucket = getBucket(clientId, latestReleaseInfo.packageHash);
48
+ const inRollout = bucket < latestReleaseInfo.rollout;
49
+
50
+ log(`Bucket: ${bucket}, rollout: ${latestReleaseInfo.rollout} → ${inRollout ? 'IN' : 'OUT'}`);
51
+
52
+ if (!inRollout) {
53
+ log(`Skipping update due to rollout. Bucket ${bucket} is not smaller than rollout range ${latestReleaseInfo.rollout}.`);
54
+ onRolloutSkipped?.(latestVersion);
55
+ }
56
+
57
+ return inRollout;
58
+ }
59
+
60
+ /**
61
+ * @param handleBinaryVersionMismatchCallback {function|null}
62
+ * @param prNumber {string|null} When given, only PR preview releases (`{prNumber}-{semver}` keys in
63
+ * the release history) are considered. Normal releases are ignored.
64
+ * (algocare PR preview release extension)
65
+ */
66
+ async function checkForUpdate(handleBinaryVersionMismatchCallback = null, prNumber = null) {
67
+ /*
68
+ * Before we ask the server if an update exists, we
69
+ * need to retrieve three pieces of information from the
70
+ * native side: deployment key, app version (e.g. 1.0.1)
71
+ * and the hash of the currently running update (if there is one).
72
+ * This allows the client to only receive updates which are targetted
73
+ * for their specific deployment and version and which are actually
74
+ * different from the CodePush update they have already installed.
75
+ */
76
+ const nativeConfig = await getConfiguration();
77
+
78
+ // Use dynamically overridden getCurrentPackage() during tests.
79
+ const localPackage = await module.exports.getCurrentPackage();
80
+
81
+ /*
82
+ * If the app has a previously installed update, and that update
83
+ * was targetted at the same app version that is currently running,
84
+ * then we want to use its package hash to determine whether a new
85
+ * release has been made on the server. Otherwise, we only need
86
+ * to send the app version to the server, since we are interested
87
+ * in any updates for current binary version, regardless of hash.
88
+ */
89
+ let queryPackage;
90
+ if (localPackage) {
91
+ queryPackage = localPackage;
92
+ } else {
93
+ queryPackage = { appVersion: nativeConfig.appVersion };
94
+ if (Platform.OS === "ios" && nativeConfig.packageHash) {
95
+ queryPackage.packageHash = nativeConfig.packageHash;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * @type {RemotePackage|null|undefined}
101
+ */
102
+ const update = await (async () => {
103
+ try {
104
+ const updateRequest = {
105
+ app_version: queryPackage.appVersion,
106
+ package_hash: queryPackage.packageHash,
107
+ is_companion: nativeConfig.ignoreAppVersion,
108
+ label: queryPackage.label,
109
+ client_unique_id: nativeConfig.clientUniqueId,
110
+ };
111
+
112
+ /**
113
+ * @type {updateChecker|undefined}
114
+ * @deprecated
115
+ */
116
+ const updateChecker = sharedCodePushOptions.updateChecker;
117
+ if (updateChecker) {
118
+ // We do not provide rollout functionality. This could be implemented in the `updateChecker`.
119
+ const { update_info } = await updateChecker(updateRequest);
120
+ return mapToRemotePackageMetadata(update_info);
121
+ } else {
122
+ /**
123
+ * `releaseHistory`
124
+ * @type {ReleaseHistoryInterface}
125
+ */
126
+ const releaseHistory = await sharedCodePushOptions.releaseHistoryFetcher(updateRequest);
127
+
128
+ /**
129
+ * (algocare PR preview) If the app is currently running a PR preview release
130
+ * (label contains `-`) and no prNumber is requested, skip the update check.
131
+ * This prevents the app from replacing a PR preview bundle with a normal release
132
+ * right after restarting during PR QA.
133
+ */
134
+ if (
135
+ !prNumber &&
136
+ updateRequest.label &&
137
+ updateRequest.label.includes("-") &&
138
+ Object.keys(releaseHistory).includes(updateRequest.label)
139
+ ) {
140
+ log("Currently running a PR preview release. Skipping update check.");
141
+ return undefined;
142
+ }
143
+
144
+ /**
145
+ * (algocare PR preview) Filter the release history.
146
+ * - PR preview mode: only `{prNumber}-{semver}` keys, with the PR prefix stripped.
147
+ * - Normal mode: only plain semver keys. (PR preview keys contain `-` and are excluded)
148
+ * @type {ReleaseHistoryInterface}
149
+ */
150
+ const filteredReleaseHistory = prNumber
151
+ ? Object.entries(releaseHistory)
152
+ .filter(([key]) => key.startsWith(`${prNumber}-`))
153
+ .reduce((acc, [key, value]) => {
154
+ const version = key.split("-")[1];
155
+ acc[version] = value;
156
+ return acc;
157
+ }, {})
158
+ : Object.entries(releaseHistory)
159
+ .filter(([key]) => !key.includes("-"))
160
+ .reduce((acc, [key, value]) => {
161
+ acc[key] = value;
162
+ return acc;
163
+ }, {});
164
+
165
+ /**
166
+ * `runtimeVersion`
167
+ * The version of currently running CodePush update. (It can be undefined if the app is running without CodePush update.)
168
+ * PR preview labels (`{prNumber}-{semver}`) are stripped down to their semver part.
169
+ * @type {string|undefined}
170
+ */
171
+ const runtimeVersion =
172
+ updateRequest.label && updateRequest.label.includes("-")
173
+ ? updateRequest.label.split("-")[1]
174
+ : updateRequest.label;
175
+
176
+ const versioning = new SemverVersioning(filteredReleaseHistory);
177
+
178
+ const isInRollout = await decideLatestReleaseIsInRollout(versioning, nativeConfig.clientUniqueId, sharedCodePushOptions?.onRolloutSkipped);
179
+ versioning.setIsLatestReleaseInRollout(isInRollout);
180
+
181
+ const shouldRollbackToBinary = versioning.shouldRollbackToBinary(runtimeVersion)
182
+ if (shouldRollbackToBinary) {
183
+ // Reset to latest major version and restart
184
+ CodePush.clearUpdates();
185
+ CodePush.allowRestart();
186
+ CodePush.restartApp();
187
+ }
188
+
189
+ const [latestVersion, latestReleaseInfo] = versioning.findLatestRelease();
190
+ const isMandatory = versioning.checkIsMandatory(runtimeVersion);
191
+
192
+ /**
193
+ * Convert the update information decided from `ReleaseHistoryInterface` to be passed to the library core (original CodePush library).
194
+ *
195
+ * @type {UpdateCheckResponse} the interface required by the original CodePush library.
196
+ */
197
+ const updateInfo = {
198
+ download_url: latestReleaseInfo.downloadUrl,
199
+ // (`enabled` will always be true in the release information obtained from the previous process.)
200
+ is_available: latestReleaseInfo.enabled,
201
+ package_hash: latestReleaseInfo.packageHash,
202
+ is_mandatory: isMandatory,
203
+ /**
204
+ * The `ReleaseHistoryInterface` data returned by the `releaseHistoryFetcher` function is
205
+ * based on the assumption that it is compatible with the current runtime binary.
206
+ * (because it is querying the update history deployed for the current binary version)
207
+ * Therefore, the current runtime binary version should be passed as it is.
208
+ */
209
+ target_binary_range: updateRequest.app_version,
210
+ /**
211
+ * Retrieve the update version from the ReleaseHistory and store it in the label.
212
+ * This information can be accessed at runtime through the CodePush bundle metadata.
213
+ * (PR preview releases are labeled `{prNumber}-{semver}` to distinguish them at runtime.)
214
+ */
215
+ label: prNumber ? `${prNumber}-${latestVersion}` : latestVersion,
216
+ // `false` should be passed to work properly
217
+ update_app_version: false,
218
+ // currently not used.
219
+ description: "",
220
+ // not used at runtime.
221
+ is_disabled: false,
222
+ // not used at runtime.
223
+ package_size: 0,
224
+ // not used at runtime.
225
+ should_run_binary_version: false,
226
+ };
227
+
228
+ return mapToRemotePackageMetadata(updateInfo);
229
+ }
230
+ } catch (error) {
231
+ log(`An error has occurred at update checker :`);
232
+ console.error(error)
233
+ // update will not happen
234
+ return undefined;
235
+ }
236
+ })();
237
+
238
+ /*
239
+ * There are four cases where checkForUpdate will resolve to null:
240
+ * ----------------------------------------------------------------
241
+ * 1) The server said there isn't an update. This is the most common case.
242
+ * 2) The server said there is an update but it requires a newer binary version.
243
+ * This would occur when end-users are running an older binary version than
244
+ * is available, and CodePush is making sure they don't get an update that
245
+ * potentially wouldn't be compatible with what they are running.
246
+ * 3) The server said there is an update, but the update's hash is the same as
247
+ * the currently running update. This should _never_ happen, unless there is a
248
+ * bug in the server, but we're adding this check just to double-check that the
249
+ * client app is resilient to a potential issue with the update check.
250
+ * 4) The server said there is an update, but the update's hash is the same as that
251
+ * of the binary's currently running version. This should only happen in Android -
252
+ * unlike iOS, we don't attach the binary's hash to the updateCheck request
253
+ * because we want to avoid having to install diff updates against the binary's
254
+ * version, which we can't do yet on Android.
255
+ */
256
+ if (!update || update.updateAppVersion ||
257
+ localPackage && (update.packageHash === localPackage.packageHash) ||
258
+ (!localPackage || localPackage._isDebugOnly) && nativeConfig.packageHash === update.packageHash) {
259
+ if (update && update.updateAppVersion) {
260
+ log("An update is available but it is not targeting the binary version of your app.");
261
+ if (handleBinaryVersionMismatchCallback && typeof handleBinaryVersionMismatchCallback === "function") {
262
+ handleBinaryVersionMismatchCallback(update)
263
+ }
264
+ }
265
+
266
+ return null;
267
+ } else {
268
+ const remotePackage = { ...update, ...PackageMixins.remote() };
269
+ remotePackage.failedInstall = await NativeCodePush.isFailedUpdate(remotePackage.packageHash);
270
+ return remotePackage;
271
+ }
272
+ }
273
+
274
+ /**
275
+ * @param updateInfo {UpdateCheckResponse}
276
+ * @return {RemotePackage | null}
277
+ */
278
+ function mapToRemotePackageMetadata(updateInfo) {
279
+ if (!updateInfo) {
280
+ return null;
281
+ } else if (!updateInfo.download_url) {
282
+ log("download_url is missed in the release history.");
283
+ return null;
284
+ } else if (!updateInfo.is_available) {
285
+ return null;
286
+ }
287
+
288
+ // refer to `RemotePackage` type inside code-push SDK
289
+ return {
290
+ deploymentKey: DEPLOYMENT_KEY,
291
+ description: updateInfo.description ?? '',
292
+ label: updateInfo.label ?? '',
293
+ appVersion: updateInfo.target_binary_range ?? '',
294
+ isMandatory: updateInfo.is_mandatory ?? false,
295
+ packageHash: updateInfo.package_hash ?? '',
296
+ packageSize: updateInfo.package_size ?? 0,
297
+ downloadUrl: updateInfo.download_url ?? '',
298
+ };
299
+ }
300
+
301
+ const getConfiguration = (() => {
302
+ let config;
303
+ return async function getConfiguration() {
304
+ if (config) {
305
+ return config;
306
+ } else if (testConfig) {
307
+ return testConfig;
308
+ } else {
309
+ config = await NativeCodePush.getConfiguration();
310
+ return config;
311
+ }
312
+ }
313
+ })();
314
+
315
+ async function getCurrentPackage() {
316
+ return await getUpdateMetadata(CodePush.UpdateState.LATEST);
317
+ }
318
+
319
+ async function getUpdateMetadata(updateState) {
320
+ let updateMetadata = await NativeCodePush.getUpdateMetadata(updateState || CodePush.UpdateState.RUNNING);
321
+ if (updateMetadata) {
322
+ updateMetadata = { ...PackageMixins.local, ...updateMetadata };
323
+ updateMetadata.failedInstall = await NativeCodePush.isFailedUpdate(updateMetadata.packageHash);
324
+ updateMetadata.isFirstRun = await NativeCodePush.isFirstRun(updateMetadata.packageHash);
325
+ }
326
+ return updateMetadata;
327
+ }
328
+
329
+ // This ensures that notifyApplicationReadyInternal is only called once
330
+ // in the lifetime of this module instance.
331
+ const notifyApplicationReady = (() => {
332
+ let notifyApplicationReadyPromise;
333
+ return () => {
334
+ if (!notifyApplicationReadyPromise) {
335
+ notifyApplicationReadyPromise = notifyApplicationReadyInternal();
336
+ }
337
+
338
+ return notifyApplicationReadyPromise;
339
+ };
340
+ })();
341
+
342
+ async function notifyApplicationReadyInternal() {
343
+ await NativeCodePush.notifyApplicationReady();
344
+ const statusReport = await NativeCodePush.getNewStatusReport();
345
+ statusReport && tryReportStatus(statusReport); // Don't wait for this to complete.
346
+
347
+ return statusReport;
348
+ }
349
+
350
+ async function tryReportStatus(statusReport, retryOnAppResume) {
351
+ try {
352
+ if (statusReport.appVersion) {
353
+ log(`Reporting binary update (${statusReport.appVersion})`);
354
+ } else {
355
+ const label = statusReport.package.label;
356
+ if (statusReport.status === "DeploymentSucceeded") {
357
+ log(`Reporting CodePush update success (${label})`);
358
+ sharedCodePushOptions?.onUpdateSuccess?.(label);
359
+ } else {
360
+ log(`Reporting CodePush update rollback (${label})`);
361
+ await NativeCodePush.setLatestRollbackInfo(statusReport.package.packageHash);
362
+ sharedCodePushOptions?.onUpdateRollback?.(label);
363
+ }
364
+ }
365
+
366
+ NativeCodePush.recordStatusReported(statusReport);
367
+ retryOnAppResume && retryOnAppResume.remove();
368
+ } catch (e) {
369
+ log(`${e}`)
370
+ log(`Report status failed: ${JSON.stringify(statusReport)}`);
371
+ NativeCodePush.saveStatusReportForRetry(statusReport);
372
+ // Try again when the app resumes
373
+ if (!retryOnAppResume) {
374
+ const resumeListener = AppState.addEventListener("change", async (newState) => {
375
+ if (newState !== "active") return;
376
+ const refreshedStatusReport = await NativeCodePush.getNewStatusReport();
377
+ if (refreshedStatusReport) {
378
+ tryReportStatus(refreshedStatusReport, resumeListener);
379
+ } else {
380
+ resumeListener && resumeListener.remove();
381
+ }
382
+ });
383
+ }
384
+ }
385
+ }
386
+
387
+ async function shouldUpdateBeIgnored(remotePackage, syncOptions) {
388
+ let { rollbackRetryOptions } = syncOptions;
389
+
390
+ const isFailedPackage = remotePackage && remotePackage.failedInstall;
391
+ if (!isFailedPackage || !syncOptions.ignoreFailedUpdates) {
392
+ return false;
393
+ }
394
+
395
+ if (!rollbackRetryOptions) {
396
+ return true;
397
+ }
398
+
399
+ if (typeof rollbackRetryOptions !== "object") {
400
+ rollbackRetryOptions = CodePush.DEFAULT_ROLLBACK_RETRY_OPTIONS;
401
+ } else {
402
+ rollbackRetryOptions = { ...CodePush.DEFAULT_ROLLBACK_RETRY_OPTIONS, ...rollbackRetryOptions };
403
+ }
404
+
405
+ if (!validateRollbackRetryOptions(rollbackRetryOptions)) {
406
+ return true;
407
+ }
408
+
409
+ const latestRollbackInfo = await NativeCodePush.getLatestRollbackInfo();
410
+ if (!validateLatestRollbackInfo(latestRollbackInfo, remotePackage.packageHash)) {
411
+ log("The latest rollback info is not valid.");
412
+ return true;
413
+ }
414
+
415
+ const { delayInHours, maxRetryAttempts } = rollbackRetryOptions;
416
+ const hoursSinceLatestRollback = (Date.now() - latestRollbackInfo.time) / (1000 * 60 * 60);
417
+ if (hoursSinceLatestRollback >= delayInHours && maxRetryAttempts >= latestRollbackInfo.count) {
418
+ log("Previous rollback should be ignored due to rollback retry options.");
419
+ return false;
420
+ }
421
+
422
+ return true;
423
+ }
424
+
425
+ function validateLatestRollbackInfo(latestRollbackInfo, packageHash) {
426
+ return latestRollbackInfo &&
427
+ latestRollbackInfo.time &&
428
+ latestRollbackInfo.count &&
429
+ latestRollbackInfo.packageHash &&
430
+ latestRollbackInfo.packageHash === packageHash;
431
+ }
432
+
433
+ function validateRollbackRetryOptions(rollbackRetryOptions) {
434
+ if (typeof rollbackRetryOptions.delayInHours !== "number") {
435
+ log("The 'delayInHours' rollback retry parameter must be a number.");
436
+ return false;
437
+ }
438
+
439
+ if (typeof rollbackRetryOptions.maxRetryAttempts !== "number") {
440
+ log("The 'maxRetryAttempts' rollback retry parameter must be a number.");
441
+ return false;
442
+ }
443
+
444
+ if (rollbackRetryOptions.maxRetryAttempts < 1) {
445
+ log("The 'maxRetryAttempts' rollback retry parameter cannot be less then 1.");
446
+ return false;
447
+ }
448
+
449
+ return true;
450
+ }
451
+
452
+ let testConfig;
453
+
454
+ // This function is only used for tests. Replaces the default SDK, configuration and native bridge
455
+ function setUpTestDependencies(testSdk, providedTestConfig, testNativeBridge) {
456
+ if (testSdk) module.exports.AcquisitionSdk = testSdk;
457
+ if (providedTestConfig) testConfig = providedTestConfig;
458
+ if (testNativeBridge) NativeCodePush = testNativeBridge;
459
+ }
460
+
461
+ async function restartApp(onlyIfUpdateIsPending = false) {
462
+ NativeCodePush.restartApp(onlyIfUpdateIsPending);
463
+ }
464
+
465
+ // This function allows only one syncInternal operation to proceed at any given time.
466
+ // Parallel calls to sync() while one is ongoing yields CodePush.SyncStatus.SYNC_IN_PROGRESS.
467
+ const sync = (() => {
468
+ let syncInProgress = false;
469
+ const setSyncCompleted = () => { syncInProgress = false; };
470
+
471
+ return (options = {}, syncStatusChangeCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback) => {
472
+ let syncStatusCallbackWithTryCatch, downloadProgressCallbackWithTryCatch;
473
+ if (typeof syncStatusChangeCallback === "function") {
474
+ syncStatusCallbackWithTryCatch = (...args) => {
475
+ try {
476
+ syncStatusChangeCallback(...args);
477
+ } catch (error) {
478
+ log(`An error has occurred : ${error.stack}`);
479
+ }
480
+ }
481
+ }
482
+
483
+ if (typeof downloadProgressCallback === "function") {
484
+ downloadProgressCallbackWithTryCatch = (...args) => {
485
+ try {
486
+ downloadProgressCallback(...args);
487
+ } catch (error) {
488
+ log(`An error has occurred: ${error.stack}`);
489
+ }
490
+ }
491
+ }
492
+
493
+ if (syncInProgress) {
494
+ typeof syncStatusCallbackWithTryCatch === "function"
495
+ ? syncStatusCallbackWithTryCatch(CodePush.SyncStatus.SYNC_IN_PROGRESS)
496
+ : log("Sync already in progress.");
497
+ return Promise.resolve(CodePush.SyncStatus.SYNC_IN_PROGRESS);
498
+ }
499
+
500
+ syncInProgress = true;
501
+ const syncPromise = syncInternal(options, syncStatusCallbackWithTryCatch, downloadProgressCallbackWithTryCatch, handleBinaryVersionMismatchCallback);
502
+ syncPromise
503
+ .then(setSyncCompleted)
504
+ .catch(setSyncCompleted);
505
+
506
+ return syncPromise;
507
+ };
508
+ })();
509
+
510
+ /*
511
+ * The syncInternal method provides a simple, one-line experience for
512
+ * incorporating the check, download and installation of an update.
513
+ *
514
+ * It simply composes the existing API methods together and adds additional
515
+ * support for respecting mandatory updates, ignoring previously failed
516
+ * releases, and displaying a standard confirmation UI to the end-user
517
+ * when an update is available.
518
+ */
519
+ async function syncInternal(options = {}, syncStatusChangeCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback) {
520
+ let resolvedInstallMode;
521
+ const syncOptions = {
522
+ deploymentKey: null,
523
+ ignoreFailedUpdates: true,
524
+ rollbackRetryOptions: null,
525
+ installMode: CodePush.InstallMode.ON_NEXT_RESTART,
526
+ mandatoryInstallMode: CodePush.InstallMode.IMMEDIATE,
527
+ minimumBackgroundDuration: 0,
528
+ updateDialog: null,
529
+ ...options,
530
+ };
531
+
532
+ syncStatusChangeCallback = typeof syncStatusChangeCallback === "function"
533
+ ? syncStatusChangeCallback
534
+ : (syncStatus) => {
535
+ switch (syncStatus) {
536
+ case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
537
+ log("Checking for update.");
538
+ break;
539
+ case CodePush.SyncStatus.AWAITING_USER_ACTION:
540
+ log("Awaiting user action.");
541
+ break;
542
+ case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
543
+ log("Downloading package.");
544
+ break;
545
+ case CodePush.SyncStatus.INSTALLING_UPDATE:
546
+ log("Installing update.");
547
+ break;
548
+ case CodePush.SyncStatus.UP_TO_DATE:
549
+ log("App is up to date.");
550
+ break;
551
+ case CodePush.SyncStatus.UPDATE_IGNORED:
552
+ log("User cancelled the update.");
553
+ break;
554
+ case CodePush.SyncStatus.UPDATE_INSTALLED:
555
+ if (resolvedInstallMode == CodePush.InstallMode.ON_NEXT_RESTART) {
556
+ log("Update is installed and will be run on the next app restart.");
557
+ } else if (resolvedInstallMode == CodePush.InstallMode.ON_NEXT_RESUME) {
558
+ if (syncOptions.minimumBackgroundDuration > 0) {
559
+ log(`Update is installed and will be run after the app has been in the background for at least ${syncOptions.minimumBackgroundDuration} seconds.`);
560
+ } else {
561
+ log("Update is installed and will be run when the app next resumes.");
562
+ }
563
+ }
564
+ break;
565
+ case CodePush.SyncStatus.PREPARING_UPDATE:
566
+ log("Download complete. Preparing update (unzip/file-copy).");
567
+ break;
568
+ case CodePush.SyncStatus.UNKNOWN_ERROR:
569
+ log("An unknown error occurred.");
570
+ break;
571
+ }
572
+ };
573
+
574
+ let remotePackageLabel;
575
+ try {
576
+ await CodePush.notifyApplicationReady();
577
+
578
+ syncStatusChangeCallback(CodePush.SyncStatus.CHECKING_FOR_UPDATE);
579
+ const remotePackage = await checkForUpdate(handleBinaryVersionMismatchCallback, syncOptions.prNumber ?? null);
580
+ remotePackageLabel = remotePackage?.label;
581
+
582
+ const doDownloadAndInstall = async () => {
583
+ syncStatusChangeCallback(CodePush.SyncStatus.DOWNLOADING_PACKAGE);
584
+ sharedCodePushOptions.onDownloadStart?.(remotePackageLabel);
585
+
586
+ const localPackage = await remotePackage.download(downloadProgressCallback, () => {
587
+ // HTTP download complete, post-processing (unzip/file-copy) starts
588
+ syncStatusChangeCallback(CodePush.SyncStatus.PREPARING_UPDATE);
589
+ });
590
+
591
+ sharedCodePushOptions.onDownloadSuccess?.(remotePackageLabel);
592
+
593
+ // Determine the correct install mode based on whether the update is mandatory or not.
594
+ resolvedInstallMode = localPackage.isMandatory ? syncOptions.mandatoryInstallMode : syncOptions.installMode;
595
+
596
+ syncStatusChangeCallback(CodePush.SyncStatus.INSTALLING_UPDATE);
597
+ await localPackage.install(resolvedInstallMode, syncOptions.minimumBackgroundDuration, () => {
598
+ syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_INSTALLED);
599
+ });
600
+
601
+ return CodePush.SyncStatus.UPDATE_INSTALLED;
602
+ };
603
+
604
+ const updateShouldBeIgnored = await shouldUpdateBeIgnored(remotePackage, syncOptions);
605
+
606
+ if (!remotePackage || updateShouldBeIgnored) {
607
+ if (updateShouldBeIgnored) {
608
+ log("An update is available, but it is being ignored due to having been previously rolled back.");
609
+ }
610
+
611
+ const currentPackage = await CodePush.getCurrentPackage();
612
+ if (currentPackage && currentPackage.isPending) {
613
+ syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_INSTALLED);
614
+ return CodePush.SyncStatus.UPDATE_INSTALLED;
615
+ } else {
616
+ syncStatusChangeCallback(CodePush.SyncStatus.UP_TO_DATE);
617
+ return CodePush.SyncStatus.UP_TO_DATE;
618
+ }
619
+ } else if (syncOptions.updateDialog) {
620
+ // updateDialog supports any truthy value (e.g. true, "goo", 12),
621
+ // but we should treat a non-object value as just the default dialog
622
+ if (typeof syncOptions.updateDialog !== "object") {
623
+ syncOptions.updateDialog = CodePush.DEFAULT_UPDATE_DIALOG;
624
+ } else {
625
+ syncOptions.updateDialog = { ...CodePush.DEFAULT_UPDATE_DIALOG, ...syncOptions.updateDialog };
626
+ }
627
+
628
+ return await new Promise((resolve, reject) => {
629
+ let message = null;
630
+ let installButtonText = null;
631
+
632
+ const dialogButtons = [];
633
+
634
+ if (remotePackage.isMandatory) {
635
+ message = syncOptions.updateDialog.mandatoryUpdateMessage;
636
+ installButtonText = syncOptions.updateDialog.mandatoryContinueButtonLabel;
637
+ } else {
638
+ message = syncOptions.updateDialog.optionalUpdateMessage;
639
+ installButtonText = syncOptions.updateDialog.optionalInstallButtonLabel;
640
+ // Since this is an optional update, add a button
641
+ // to allow the end-user to ignore it
642
+ dialogButtons.push({
643
+ text: syncOptions.updateDialog.optionalIgnoreButtonLabel,
644
+ onPress: () => {
645
+ syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_IGNORED);
646
+ resolve(CodePush.SyncStatus.UPDATE_IGNORED);
647
+ },
648
+ });
649
+ }
650
+
651
+ // Since the install button should be placed to the
652
+ // right of any other button, add it last
653
+ dialogButtons.push({
654
+ text: installButtonText,
655
+ onPress: () => {
656
+ doDownloadAndInstall()
657
+ .then(resolve, reject);
658
+ },
659
+ })
660
+
661
+ // If the update has a description, and the developer
662
+ // explicitly chose to display it, then set that as the message
663
+ if (syncOptions.updateDialog.appendReleaseDescription && remotePackage.description) {
664
+ message += `${syncOptions.updateDialog.descriptionPrefix} ${remotePackage.description}`;
665
+ }
666
+
667
+ syncStatusChangeCallback(CodePush.SyncStatus.AWAITING_USER_ACTION);
668
+ Alert.alert(syncOptions.updateDialog.title, message, dialogButtons);
669
+ });
670
+ } else {
671
+ return await doDownloadAndInstall();
672
+ }
673
+ } catch (error) {
674
+ syncStatusChangeCallback(CodePush.SyncStatus.UNKNOWN_ERROR);
675
+ sharedCodePushOptions?.onSyncError?.(remotePackageLabel ?? 'unknown', error);
676
+ log(error.message);
677
+ throw error;
678
+ }
679
+ };
680
+
681
+ let CodePush;
682
+
683
+ /**
684
+ * @callback releaseHistoryFetcher
685
+ * @param {UpdateCheckRequest} updateRequest Current package information to check for updates.
686
+ * @returns {Promise<ReleaseHistoryInterface>} The release history of the updates deployed for a specific binary version.
687
+ */
688
+
689
+ /**
690
+ * @callback updateChecker
691
+ * @param {UpdateCheckRequest} updateRequest Current package information to check for updates.
692
+ * @returns {Promise<{update_info: UpdateCheckResponse}>} The result of the update check. Follows the AppCenter API response interface.
693
+ *
694
+ * @deprecated It will be removed in the next major version.
695
+ */
696
+
697
+ /**
698
+ * If you pass options once when calling `codePushify`, they will be shared with related functions.
699
+ * @type {{
700
+ * releaseHistoryFetcher: releaseHistoryFetcher | undefined,
701
+ * setReleaseHistoryFetcher(releaseHistoryFetcherFunction: releaseHistoryFetcher | undefined): void,
702
+ *
703
+ * updateChecker: updateChecker | undefined,
704
+ * setUpdateChecker(updateCheckerFunction: updateChecker | undefined): void,
705
+ *
706
+ * onUpdateSuccess: (label: string) => void | undefined,
707
+ * setOnUpdateSuccess(onUpdateSuccessFunction: (label: string) => void | undefined): void,
708
+ *
709
+ * onUpdateRollback: (label: string) => void | undefined,
710
+ * setOnUpdateRollback(onUpdateRollbackFunction: (label: string) => void | undefined): void,
711
+ *
712
+ * onDownloadStart: (label: string) => void | undefined,
713
+ * setOnDownloadStart(onDownloadStartFunction: (label: string) => void | undefined): void,
714
+ *
715
+ * onDownloadSuccess: (label: string) => void | undefined,
716
+ * setOnDownloadSuccess(onDownloadSuccessFunction: (label: string) => void | undefined): void,
717
+ *
718
+ * onSyncError: (label: string, error: Error) => void | undefined,
719
+ * setOnSyncError(onSyncErrorFunction: (label: string, error: Error) => void | undefined): void,
720
+ *
721
+ * onRolloutSkipped: (label: string, error: Error) => void | undefined,
722
+ * setOnRolloutSkipped(onRolloutSkippedFunction: (label: string, error: Error) => void | undefined): void,
723
+ * }}
724
+ */
725
+ const sharedCodePushOptions = {
726
+ releaseHistoryFetcher: undefined,
727
+ setReleaseHistoryFetcher(releaseHistoryFetcherFunction) {
728
+ if (!releaseHistoryFetcherFunction || typeof releaseHistoryFetcherFunction !== 'function') throw new Error('Please implement the releaseHistoryFetcher function');
729
+ this.releaseHistoryFetcher = releaseHistoryFetcherFunction;
730
+ },
731
+ updateChecker: undefined,
732
+ setUpdateChecker(updateCheckerFunction) {
733
+ if (!updateCheckerFunction) return;
734
+ if (typeof updateCheckerFunction !== 'function') throw new Error('Please pass a function to updateChecker');
735
+ this.updateChecker = updateCheckerFunction;
736
+ },
737
+ onUpdateSuccess: undefined,
738
+ setOnUpdateSuccess(onUpdateSuccessFunction) {
739
+ if (!onUpdateSuccessFunction) return;
740
+ if (typeof onUpdateSuccessFunction !== 'function') throw new Error('Please pass a function to onUpdateSuccess');
741
+ this.onUpdateSuccess = onUpdateSuccessFunction;
742
+ },
743
+ onUpdateRollback: undefined,
744
+ setOnUpdateRollback(onUpdateRollbackFunction) {
745
+ if (!onUpdateRollbackFunction) return;
746
+ if (typeof onUpdateRollbackFunction !== 'function') throw new Error('Please pass a function to onUpdateRollback');
747
+ this.onUpdateRollback = onUpdateRollbackFunction;
748
+ },
749
+ onDownloadStart: undefined,
750
+ setOnDownloadStart(onDownloadStartFunction) {
751
+ if (!onDownloadStartFunction) return;
752
+ if (typeof onDownloadStartFunction !== 'function') throw new Error('Please pass a function to onDownloadStart');
753
+ this.onDownloadStart = onDownloadStartFunction;
754
+ },
755
+ onDownloadSuccess: undefined,
756
+ setOnDownloadSuccess(onDownloadSuccessFunction) {
757
+ if (!onDownloadSuccessFunction) return;
758
+ if (typeof onDownloadSuccessFunction !== 'function') throw new Error('Please pass a function to onDownloadSuccess');
759
+ this.onDownloadSuccess = onDownloadSuccessFunction;
760
+ },
761
+ onSyncError: undefined,
762
+ setOnSyncError(onSyncErrorFunction) {
763
+ if (!onSyncErrorFunction) return;
764
+ if (typeof onSyncErrorFunction !== 'function') throw new Error('Please pass a function to onSyncError');
765
+ this.onSyncError = onSyncErrorFunction;
766
+ },
767
+ onRolloutSkipped: undefined,
768
+ setOnRolloutSkipped(onRolloutSkippedFunction) {
769
+ if (!onRolloutSkippedFunction) return;
770
+ if (typeof onRolloutSkippedFunction !== 'function') throw new Error('Please pass a function to onRolloutSkipped');
771
+ this.onRolloutSkipped = onRolloutSkippedFunction;
772
+ },
773
+ }
774
+
775
+ function codePushify(options = {}) {
776
+ let React;
777
+ let ReactNative = require("react-native");
778
+
779
+ try { React = require("react"); } catch (e) { }
780
+ if (!React) {
781
+ try { React = ReactNative.React; } catch (e) { }
782
+ if (!React) {
783
+ throw new Error("Unable to find the 'React' module.");
784
+ }
785
+ }
786
+
787
+ if (!React.Component) {
788
+ throw new Error(
789
+ `Unable to find the "Component" class, please either:
790
+ 1. Upgrade to a newer version of React Native that supports it, or
791
+ 2. Call the codePush.sync API in your component instead of using the @codePush decorator`,
792
+ );
793
+ }
794
+
795
+ if (options.updateChecker && !options.releaseHistoryFetcher) {
796
+ throw new Error('If you want to use `updateChecker`, pass a no-op function to releaseHistoryFetcher option. (e.g. `releaseHistoryFetcher: async () => ({})`)');
797
+ }
798
+
799
+ sharedCodePushOptions.setReleaseHistoryFetcher(options.releaseHistoryFetcher);
800
+ sharedCodePushOptions.setUpdateChecker(options.updateChecker);
801
+
802
+ // set telemetry callbacks
803
+ sharedCodePushOptions.setOnUpdateSuccess(options.onUpdateSuccess);
804
+ sharedCodePushOptions.setOnUpdateRollback(options.onUpdateRollback);
805
+ sharedCodePushOptions.setOnDownloadStart(options.onDownloadStart);
806
+ sharedCodePushOptions.setOnDownloadSuccess(options.onDownloadSuccess);
807
+ sharedCodePushOptions.setOnSyncError(options.onSyncError);
808
+ sharedCodePushOptions.setOnRolloutSkipped(options.onRolloutSkipped);
809
+
810
+ const decorator = (RootComponent) => {
811
+ class CodePushComponent extends React.Component {
812
+ constructor(props) {
813
+ super(props);
814
+ this.rootComponentRef = React.createRef();
815
+ }
816
+
817
+ componentDidMount() {
818
+ if (options.checkFrequency === CodePush.CheckFrequency.MANUAL) {
819
+ CodePush.notifyAppReady();
820
+ } else {
821
+ const rootComponentInstance = this.rootComponentRef.current;
822
+
823
+ let syncStatusCallback;
824
+ if (rootComponentInstance && rootComponentInstance.codePushStatusDidChange) {
825
+ syncStatusCallback = rootComponentInstance.codePushStatusDidChange.bind(rootComponentInstance);
826
+ }
827
+
828
+ let downloadProgressCallback;
829
+ if (rootComponentInstance && rootComponentInstance.codePushDownloadDidProgress) {
830
+ downloadProgressCallback = rootComponentInstance.codePushDownloadDidProgress.bind(rootComponentInstance);
831
+ }
832
+
833
+ let handleBinaryVersionMismatchCallback;
834
+ if (rootComponentInstance && rootComponentInstance.codePushOnBinaryVersionMismatch) {
835
+ handleBinaryVersionMismatchCallback = rootComponentInstance.codePushOnBinaryVersionMismatch.bind(rootComponentInstance);
836
+ }
837
+
838
+ CodePush.sync(options, syncStatusCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback);
839
+
840
+ if (options.checkFrequency === CodePush.CheckFrequency.ON_APP_RESUME) {
841
+ ReactNative.AppState.addEventListener("change", (newState) => {
842
+ if (newState === "active") {
843
+ CodePush.sync(options, syncStatusCallback, downloadProgressCallback);
844
+ }
845
+ });
846
+ }
847
+ }
848
+ }
849
+
850
+ render() {
851
+ const props = { ...this.props };
852
+
853
+ // We can set ref property on class components only (not stateless)
854
+ // Check it by render method
855
+ if (RootComponent.prototype && RootComponent.prototype.render) {
856
+ props.ref = this.rootComponentRef;
857
+ }
858
+
859
+ return <RootComponent {...props} />
860
+ }
861
+ }
862
+
863
+ return hoistStatics(CodePushComponent, RootComponent);
864
+ }
865
+
866
+ if (typeof options === "function") {
867
+ // Infer that the root component was directly passed to us.
868
+ return decorator(options);
869
+ } else {
870
+ return decorator;
871
+ }
872
+ }
873
+
874
+ // If the "NativeCodePush" variable isn't defined, then
875
+ // the app didn't properly install the native module,
876
+ // and therefore, it doesn't make sense initializing
877
+ // the JS interface when it wouldn't work anyways.
878
+ if (NativeCodePush) {
879
+ CodePush = codePushify;
880
+ Object.assign(CodePush, {
881
+ checkForUpdate,
882
+ getConfiguration,
883
+ getCurrentPackage,
884
+ getUpdateMetadata,
885
+ log,
886
+ notifyAppReady: notifyApplicationReady,
887
+ notifyApplicationReady,
888
+ restartApp,
889
+ setUpTestDependencies,
890
+ sync,
891
+ disallowRestart: NativeCodePush.disallow,
892
+ allowRestart: NativeCodePush.allow,
893
+ clearUpdates: NativeCodePush.clearUpdates,
894
+ InstallMode: {
895
+ IMMEDIATE: NativeCodePush.codePushInstallModeImmediate, // Restart the app immediately
896
+ ON_NEXT_RESTART: NativeCodePush.codePushInstallModeOnNextRestart, // Don't artificially restart the app. Allow the update to be "picked up" on the next app restart
897
+ ON_NEXT_RESUME: NativeCodePush.codePushInstallModeOnNextResume, // Restart the app the next time it is resumed from the background
898
+ ON_NEXT_SUSPEND: NativeCodePush.codePushInstallModeOnNextSuspend, // Restart the app _while_ it is in the background,
899
+ // but only after it has been in the background for "minimumBackgroundDuration" seconds (0 by default),
900
+ // so that user context isn't lost unless the app suspension is long enough to not matter
901
+ },
902
+ SyncStatus: {
903
+ UP_TO_DATE: 0, // The running app is up-to-date
904
+ UPDATE_INSTALLED: 1, // The app had an optional/mandatory update that was successfully downloaded and is about to be installed.
905
+ UPDATE_IGNORED: 2, // The app had an optional update and the end-user chose to ignore it
906
+ UNKNOWN_ERROR: 3,
907
+ SYNC_IN_PROGRESS: 4, // There is an ongoing "sync" operation in progress.
908
+ CHECKING_FOR_UPDATE: 5,
909
+ AWAITING_USER_ACTION: 6,
910
+ DOWNLOADING_PACKAGE: 7,
911
+ INSTALLING_UPDATE: 8,
912
+ PREPARING_UPDATE: 9, // HTTP download complete, post-processing (unzip/file-copy) in progress
913
+ },
914
+ CheckFrequency: {
915
+ ON_APP_START: 0,
916
+ ON_APP_RESUME: 1,
917
+ MANUAL: 2,
918
+ },
919
+ UpdateState: {
920
+ RUNNING: NativeCodePush.codePushUpdateStateRunning,
921
+ PENDING: NativeCodePush.codePushUpdateStatePending,
922
+ LATEST: NativeCodePush.codePushUpdateStateLatest,
923
+ },
924
+ DeploymentStatus: {
925
+ FAILED: "DeploymentFailed",
926
+ SUCCEEDED: "DeploymentSucceeded",
927
+ },
928
+ DEFAULT_UPDATE_DIALOG: {
929
+ appendReleaseDescription: false,
930
+ descriptionPrefix: " Description: ",
931
+ mandatoryContinueButtonLabel: "Continue",
932
+ mandatoryUpdateMessage: "An update is available that must be installed.",
933
+ optionalIgnoreButtonLabel: "Ignore",
934
+ optionalInstallButtonLabel: "Install",
935
+ optionalUpdateMessage: "An update is available. Would you like to install it?",
936
+ title: "Update available",
937
+ },
938
+ DEFAULT_ROLLBACK_RETRY_OPTIONS: {
939
+ delayInHours: 24,
940
+ maxRetryAttempts: 1,
941
+ },
942
+ });
943
+ } else {
944
+ log("The CodePush module doesn't appear to be properly installed. Please double-check that everything is setup correctly.");
945
+ }
946
+
947
+ module.exports = CodePush;