@hot-updater/native-core 0.0.0-stage → 1.2.0-rc.64

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 (99) hide show
  1. package/android/build.gradle +31 -0
  2. package/android/consumer-rules.pro +9 -0
  3. package/android/hot-updater-fingerprint.gradle +130 -0
  4. package/android/hot-updater-min-bundle-id.gradle +68 -0
  5. package/android/resolve-hot-updater-cli.js +16 -0
  6. package/android/src/main/AndroidManifest.xml +4 -0
  7. package/android/src/main/cpp/CMakeLists.txt +7 -0
  8. package/android/src/main/cpp/CrashMonitor.c +23 -0
  9. package/android/src/main/java/com/hotupdater/ArtifactEntry.kt +12 -0
  10. package/android/src/main/java/com/hotupdater/ArtifactFileResolver.kt +97 -0
  11. package/android/src/main/java/com/hotupdater/BsdiffPatch.kt +287 -0
  12. package/android/src/main/java/com/hotupdater/BuiltInAssetResolver.kt +414 -0
  13. package/android/src/main/java/com/hotupdater/BundleFileStorageService.kt +3277 -0
  14. package/android/src/main/java/com/hotupdater/BundleMetadata.kt +681 -0
  15. package/android/src/main/java/com/hotupdater/CohortService.kt +81 -0
  16. package/android/src/main/java/com/hotupdater/FileManagerService.kt +151 -0
  17. package/android/src/main/java/com/hotupdater/HashUtils.kt +47 -0
  18. package/android/src/main/java/com/hotupdater/HotUpdaterException.kt +429 -0
  19. package/android/src/main/java/com/hotupdater/HotUpdaterInstanceEnvironment.kt +181 -0
  20. package/android/src/main/java/com/hotupdater/HotUpdaterUpdateCheck.kt +141 -0
  21. package/android/src/main/java/com/hotupdater/InstallIdentityService.kt +47 -0
  22. package/android/src/main/java/com/hotupdater/KeyValueStorageService.kt +104 -0
  23. package/android/src/main/java/com/hotupdater/NativeBuildValues.kt +47 -0
  24. package/android/src/main/java/com/hotupdater/NativeConfigUtils.kt +58 -0
  25. package/android/src/main/java/com/hotupdater/NativeRuntimeDefaults.kt +35 -0
  26. package/android/src/main/java/com/hotupdater/NativeUpdateChecker.kt +1171 -0
  27. package/android/src/main/java/com/hotupdater/NativeUpdateEventQueue.kt +134 -0
  28. package/android/src/main/java/com/hotupdater/NetworkState.kt +31 -0
  29. package/android/src/main/java/com/hotupdater/NoBackupStorage.kt +17 -0
  30. package/android/src/main/java/com/hotupdater/OkHttpDownloadService.kt +384 -0
  31. package/android/src/main/java/com/hotupdater/OkHttpUpdateCheckTransport.kt +88 -0
  32. package/android/src/main/java/com/hotupdater/PostCrashUpdateCheck.kt +197 -0
  33. package/android/src/main/java/com/hotupdater/RelativePathResolver.kt +42 -0
  34. package/android/src/main/java/com/hotupdater/ReleaseCatalog.kt +504 -0
  35. package/android/src/main/java/com/hotupdater/ReleaseCatalogCacheService.kt +166 -0
  36. package/android/src/main/java/com/hotupdater/ReleaseCatalogClient.kt +405 -0
  37. package/android/src/main/java/com/hotupdater/ReleaseSelection.kt +476 -0
  38. package/android/src/main/java/com/hotupdater/SignatureVerifier.kt +417 -0
  39. package/android/src/main/java/com/hotupdater/Standalone/HotUpdaterClient.kt +328 -0
  40. package/android/src/main/java/com/hotupdater/Standalone/HotUpdaterOptions.kt +15 -0
  41. package/android/src/main/java/com/hotupdater/Standalone/RuntimeCrashMonitor.kt +111 -0
  42. package/android/src/main/java/com/hotupdater/StrictJson.kt +392 -0
  43. package/android/src/main/java/com/hotupdater/TarArchiveInputStream.kt +321 -0
  44. package/android/src/main/java/com/hotupdater/TarBrArchiveExtractor.kt +119 -0
  45. package/android/src/main/java/com/hotupdater/VersionedPreferencesService.kt +83 -0
  46. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/BitReader.java +314 -0
  47. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/BrotliError.java +47 -0
  48. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/BrotliInputStream.java +174 -0
  49. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/BrotliRuntimeException.java +21 -0
  50. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/Context.java +58 -0
  51. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/Decode.java +1574 -0
  52. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/Decoder.java +72 -0
  53. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/Dictionary.java +103 -0
  54. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/DictionaryData.java +82 -0
  55. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/Huffman.java +143 -0
  56. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/LICENSE +19 -0
  57. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/README.md +39 -0
  58. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/State.java +100 -0
  59. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/Transform.java +240 -0
  60. package/android/src/main/java/com/hotupdater/vendor/brotli/dec/Utils.java +163 -0
  61. package/apple/Package.swift +13 -0
  62. package/apple/Sources/HotUpdaterBsdiffPatch/HotUpdaterPatch.cpp +311 -0
  63. package/apple/Sources/HotUpdaterBsdiffPatch/include/HotUpdaterPatch.h +13 -0
  64. package/apple/Sources/HotUpdaterCore/ArtifactEntry.swift +16 -0
  65. package/apple/Sources/HotUpdaterCore/ArtifactFileResolver.swift +118 -0
  66. package/apple/Sources/HotUpdaterCore/ArtifactStageRequest.swift +221 -0
  67. package/apple/Sources/HotUpdaterCore/BrotliFileDecompressor.swift +171 -0
  68. package/apple/Sources/HotUpdaterCore/BuiltInAssetResolver.swift +234 -0
  69. package/apple/Sources/HotUpdaterCore/BundleFileStorageService.swift +3860 -0
  70. package/apple/Sources/HotUpdaterCore/BundleMetadata.swift +560 -0
  71. package/apple/Sources/HotUpdaterCore/CohortService.swift +71 -0
  72. package/apple/Sources/HotUpdaterCore/CrashMarkerFile.swift +67 -0
  73. package/apple/Sources/HotUpdaterCore/FileManagerService.swift +154 -0
  74. package/apple/Sources/HotUpdaterCore/FileUtilities.swift +64 -0
  75. package/apple/Sources/HotUpdaterCore/HashUtils.swift +63 -0
  76. package/apple/Sources/HotUpdaterCore/HotUpdaterInstanceEnvironment.swift +342 -0
  77. package/apple/Sources/HotUpdaterCore/KeyValueStorageService.swift +92 -0
  78. package/apple/Sources/HotUpdaterCore/LaunchPreparationLock.swift +106 -0
  79. package/apple/Sources/HotUpdaterCore/NativeUpdateCheck.swift +1925 -0
  80. package/apple/Sources/HotUpdaterCore/NativeUpdateEvents.swift +112 -0
  81. package/apple/Sources/HotUpdaterCore/PostCrashUpdateCheck.swift +254 -0
  82. package/apple/Sources/HotUpdaterCore/ReleaseCatalog.swift +646 -0
  83. package/apple/Sources/HotUpdaterCore/ReleaseCatalogCacheService.swift +213 -0
  84. package/apple/Sources/HotUpdaterCore/ReleaseSelection.swift +484 -0
  85. package/apple/Sources/HotUpdaterCore/RuntimeClientOptions.swift +89 -0
  86. package/apple/Sources/HotUpdaterCore/RuntimeConfiguration.swift +52 -0
  87. package/apple/Sources/HotUpdaterCore/SignatureVerifier.swift +412 -0
  88. package/apple/Sources/HotUpdaterCore/Standalone/HotUpdaterClient.swift +304 -0
  89. package/apple/Sources/HotUpdaterCore/Standalone/HotUpdaterOptions.swift +6 -0
  90. package/apple/Sources/HotUpdaterCore/Standalone/RuntimeCrashMonitor.swift +43 -0
  91. package/apple/Sources/HotUpdaterCore/StrictJson.swift +363 -0
  92. package/apple/Sources/HotUpdaterCore/TarArchiveExtractor.swift +257 -0
  93. package/apple/Sources/HotUpdaterCore/URLSessionDownloadService.swift +486 -0
  94. package/apple/Sources/HotUpdaterCore/UpdateFailure.swift +417 -0
  95. package/apple/Sources/HotUpdaterCore/VersionedPreferencesService.swift +82 -0
  96. package/apple/Sources/HotUpdaterCrashMarker/HotUpdaterCrashMarker.c +209 -0
  97. package/apple/Sources/HotUpdaterCrashMarker/include/HotUpdaterCrashMarker.h +16 -0
  98. package/package.json +23 -3
  99. package/README.md +0 -3
@@ -0,0 +1,31 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'org.jetbrains.kotlin.android'
4
+ }
5
+
6
+ android {
7
+ namespace 'com.hotupdater'
8
+ compileSdk 36
9
+ defaultConfig {
10
+ minSdk 24
11
+ consumerProguardFiles "consumer-rules.pro"
12
+ }
13
+ compileOptions {
14
+ sourceCompatibility JavaVersion.VERSION_17
15
+ targetCompatibility JavaVersion.VERSION_17
16
+ }
17
+ buildFeatures { buildConfig true }
18
+ externalNativeBuild { cmake { path 'src/main/cpp/CMakeLists.txt' } }
19
+ }
20
+
21
+ kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) } }
22
+
23
+ apply from: 'hot-updater-min-bundle-id.gradle'
24
+ apply from: 'hot-updater-fingerprint.gradle'
25
+
26
+ dependencies {
27
+ implementation 'androidx.core:core:1.13.1'
28
+ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
29
+ implementation 'org.apache.commons:commons-compress:1.27.1'
30
+ implementation 'com.squareup.okhttp3:okhttp:4.12.0'
31
+ }
@@ -0,0 +1,9 @@
1
+ # Preserve the Brotli decoder and its embedded static dictionary
2
+ # (DictionaryData). R8 otherwise strips the dictionary's static init, causing
3
+ # per-file Brotli decompression to fail at runtime with:
4
+ # java.io.IOException: Brotli stream decoding failed
5
+ # Caused by: brotli dictionary is not set
6
+ -keep class com.hotupdater.vendor.brotli.** { *; }
7
+
8
+ # JNI resolves this class and its native methods by name.
9
+ -keep class com.hotupdater.RuntimeCrashMonitor { native <methods>; }
@@ -0,0 +1,130 @@
1
+ // Writes the fingerprint each build variant embeds into a generated source, at
2
+ // execution time on every build, so neither an up-to-date check nor the
3
+ // configuration cache keeps an earlier build's value.
4
+ //
5
+ // The app root is the HOT_UPDATER_APP_ROOT Gradle property when set (relative
6
+ // to the Android project), else the directory above the Android project
7
+ // (<app>/android). Without a
8
+ // fingerprint.json there, the app uses the appVersion strategy and the
9
+ // fingerprint is empty. The debug build type embeds the hash fingerprint.json
10
+ // holds; any other runs `hot-updater fingerprint hash`, which computes it from
11
+ // the inputs fingerprint.json records, so the binary carries the fingerprint
12
+ // of the native interface it was built from.
13
+ abstract class GenerateHotUpdaterFingerprintHashTask extends DefaultTask {
14
+ @Input
15
+ abstract Property<String> getAppRoot()
16
+
17
+ @Input
18
+ abstract Property<Boolean> getRecordedOnly()
19
+
20
+ @Input
21
+ abstract Property<String> getNodeBinary()
22
+
23
+ // resolve-hot-updater-cli.js beside this file, which locates the app's CLI.
24
+ @InputFile
25
+ @PathSensitive(PathSensitivity.NONE)
26
+ abstract RegularFileProperty getCliResolver()
27
+
28
+ @OutputDirectory
29
+ abstract DirectoryProperty getOutputDirectory()
30
+
31
+ private String run(List<String> command, File workingDirectory) {
32
+ def builder = new ProcessBuilder(command).directory(workingDirectory)
33
+ // Build adapters that spawn npm's tools, such as Rock's `npx rock config`,
34
+ // find them beside a node given by path.
35
+ def executable = new File(command[0])
36
+ if (executable.isAbsolute()) {
37
+ def environment = builder.environment()
38
+ environment.put("PATH", executable.parent + File.pathSeparator + (environment.get("PATH") ?: ""))
39
+ }
40
+ def process = builder.start()
41
+ def stdout = new StringBuilder()
42
+ def stderr = new StringBuilder()
43
+ process.waitForProcessOutput(stdout, stderr)
44
+ stderr.toString().readLines().findAll { it.trim() }.each { logger.warn(it) }
45
+ if (process.exitValue() != 0) {
46
+ throw new GradleException("[HotUpdater] `${command.join(' ')}` failed with exit code ${process.exitValue()}.")
47
+ }
48
+ return stdout.toString().trim()
49
+ }
50
+
51
+ @TaskAction
52
+ void generate() {
53
+ def appRoot = new File(getAppRoot().get()).canonicalFile
54
+ def fingerprintJson = new File(appRoot, "fingerprint.json")
55
+ def fingerprintHash = ""
56
+ if (fingerprintJson.isFile()) {
57
+ def recorded = new groovy.json.JsonSlurper().parse(fingerprintJson)
58
+ // Only a CLI with `fingerprint hash` records `inputs`; with an older one
59
+ // the build embeds the recorded hash.
60
+ if (getRecordedOnly().get() || recorded?.inputs == null) {
61
+ if (!getRecordedOnly().get()) {
62
+ logger.warn("[HotUpdater] fingerprint.json records no inputs, so the build embeds the hash it holds. Run `npx hot-updater fingerprint create` with this version of hot-updater.")
63
+ }
64
+ fingerprintHash = recorded?.android?.hash ?: ""
65
+ } else {
66
+ def node = getNodeBinary().get()
67
+ def cli = run([node, getCliResolver().get().asFile.path, appRoot.path], appRoot)
68
+ fingerprintHash = run([node, cli, "fingerprint", "hash", "-p", "android"], appRoot)
69
+ }
70
+ }
71
+
72
+ def source = getOutputDirectory().file("com/hotupdater/HotUpdaterBuildFingerprintHash.java").get().asFile
73
+ source.parentFile.mkdirs()
74
+ source.text = """package com.hotupdater;
75
+
76
+ // Generated by generateHotUpdaterFingerprintHash on every build.
77
+ final class HotUpdaterBuildFingerprintHash {
78
+ private HotUpdaterBuildFingerprintHash() {}
79
+
80
+ static String get() {
81
+ return "${fingerprintHash}";
82
+ }
83
+ }
84
+ """
85
+ }
86
+ }
87
+
88
+ // A relative HOT_UPDATER_APP_ROOT is relative to the Android project, not to
89
+ // the directory Gradle was started from.
90
+ def hotUpdaterAndroidRoot = rootProject.projectDir
91
+ def hotUpdaterAppRoot = providers.gradleProperty("HOT_UPDATER_APP_ROOT")
92
+ .map { String root ->
93
+ def file = new File(root)
94
+ (file.isAbsolute() ? file : new File(hotUpdaterAndroidRoot, root)).absolutePath
95
+ }
96
+ .orElse(hotUpdaterAndroidRoot.parentFile.absolutePath)
97
+
98
+ // The node that runs the CLI: the HOT_UPDATER_NODE_BINARY Gradle property,
99
+ // else NODE_BINARY, as iOS builds read from ios/.xcode.env, else node on PATH.
100
+ def hotUpdaterNodeBinary = providers.gradleProperty("HOT_UPDATER_NODE_BINARY")
101
+ .orElse(providers.environmentVariable("NODE_BINARY"))
102
+ .orElse("node")
103
+
104
+ def registerHotUpdaterFingerprintTask = { String variantName, String buildType ->
105
+ tasks.register("generateHotUpdaterFingerprintHash${variantName.capitalize()}", GenerateHotUpdaterFingerprintHashTask) {
106
+ appRoot.set(hotUpdaterAppRoot)
107
+ recordedOnly.set(buildType == "debug")
108
+ nodeBinary.set(hotUpdaterNodeBinary)
109
+ cliResolver.set(layout.projectDirectory.file("resolve-hot-updater-cli.js"))
110
+ outputDirectory.set(layout.buildDirectory.dir("generated/source/hotUpdaterFingerprintHash/${variantName}"))
111
+ outputs.upToDateWhen { false }
112
+ }
113
+ }
114
+
115
+ // AGP 7.3 added generated source directories. Earlier versions register the
116
+ // task through the legacy variant API.
117
+ def hotUpdaterAgpVersion = androidComponents.pluginVersion
118
+ if (hotUpdaterAgpVersion.major > 7 || (hotUpdaterAgpVersion.major == 7 && hotUpdaterAgpVersion.minor >= 3)) {
119
+ androidComponents {
120
+ onVariants(selector().all()) { variant ->
121
+ def task = registerHotUpdaterFingerprintTask(variant.name, variant.buildType)
122
+ variant.sources.java.addGeneratedSourceDirectory(task) { it.outputDirectory }
123
+ }
124
+ }
125
+ } else {
126
+ android.libraryVariants.all { variant ->
127
+ def task = registerHotUpdaterFingerprintTask(variant.name, variant.buildType.name)
128
+ variant.registerJavaGeneratingTask(task, task.get().outputDirectory.get().asFile)
129
+ }
130
+ }
@@ -0,0 +1,68 @@
1
+ // Writes this build's MIN_BUNDLE_ID into a generated source on every build,
2
+ // at execution time, so neither an up-to-date check nor the configuration
3
+ // cache keeps an earlier build's value. MIN_BUNDLE_ID is a UUIDv7 with zeroed
4
+ // random bits on the same epoch millisecond clock as the bundle IDs
5
+ // `hot-updater deploy` issues. The hot-updater CLI passes its own value as
6
+ // -PMIN_BUNDLE_ID, which wins.
7
+ abstract class GenerateHotUpdaterMinBundleIdTask extends DefaultTask {
8
+ @Input
9
+ @Optional
10
+ abstract Property<String> getMinBundleId()
11
+
12
+ @OutputDirectory
13
+ abstract DirectoryProperty getOutputDirectory()
14
+
15
+ @TaskAction
16
+ void generate() {
17
+ def minBundleId = getMinBundleId().getOrNull()?.toLowerCase(Locale.ROOT)
18
+ if (minBundleId == null) {
19
+ def timestampMs = System.currentTimeMillis()
20
+ minBundleId = String.format(
21
+ "%08x-%04x-7000-8000-000000000000",
22
+ timestampMs >>> 16,
23
+ timestampMs & 0xffff
24
+ )
25
+ } else if (!(minBundleId ==~ /[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/)) {
26
+ throw new GradleException("MIN_BUNDLE_ID must be a UUIDv7, got: ${getMinBundleId().get()}")
27
+ }
28
+
29
+ def source = getOutputDirectory().file("com/hotupdater/HotUpdaterMinBundleId.java").get().asFile
30
+ source.parentFile.mkdirs()
31
+ source.text = """package com.hotupdater;
32
+
33
+ // Generated by generateHotUpdaterMinBundleId on every build.
34
+ final class HotUpdaterMinBundleId {
35
+ private HotUpdaterMinBundleId() {}
36
+
37
+ static String get() {
38
+ return "${minBundleId}";
39
+ }
40
+ }
41
+ """
42
+ }
43
+ }
44
+
45
+ def generateHotUpdaterMinBundleId = tasks.register("generateHotUpdaterMinBundleId", GenerateHotUpdaterMinBundleIdTask) {
46
+ minBundleId.set(providers.gradleProperty("MIN_BUNDLE_ID"))
47
+ outputDirectory.set(layout.buildDirectory.dir("generated/source/hotUpdaterMinBundleId"))
48
+ outputs.upToDateWhen { false }
49
+ }
50
+
51
+ def agpVersion = androidComponents.pluginVersion
52
+
53
+ // AGP 7.3 added generated source directories. Earlier versions register the
54
+ // task through the legacy variant API.
55
+ if (agpVersion.major > 7 || (agpVersion.major == 7 && agpVersion.minor >= 3)) {
56
+ androidComponents {
57
+ onVariants(selector().all()) { variant ->
58
+ variant.sources.java.addGeneratedSourceDirectory(generateHotUpdaterMinBundleId) { it.outputDirectory }
59
+ }
60
+ }
61
+ } else {
62
+ android.libraryVariants.all { variant ->
63
+ variant.registerJavaGeneratingTask(
64
+ generateHotUpdaterMinBundleId,
65
+ generateHotUpdaterMinBundleId.get().outputDirectory.get().asFile
66
+ )
67
+ }
68
+ }
@@ -0,0 +1,16 @@
1
+ // Prints the path of the hot-updater CLI the app root given as the first
2
+ // argument resolves. hot-updater-fingerprint.gradle runs this file rather than
3
+ // an inline `node -e` script, so no code passes through the command line,
4
+ // which Windows quotes differently from macOS and Linux.
5
+ const path = require("node:path");
6
+
7
+ const manifest = require.resolve("hot-updater/package.json", {
8
+ paths: [process.argv[2]],
9
+ });
10
+ const { bin } = require(manifest);
11
+ console.log(
12
+ path.join(
13
+ path.dirname(manifest),
14
+ typeof bin === "string" ? bin : bin["hot-updater"],
15
+ ),
16
+ );
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET" />
3
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
4
+ </manifest>
@@ -0,0 +1,7 @@
1
+ cmake_minimum_required(VERSION 3.13)
2
+ project(hotupdater_runtime_recovery C)
3
+ set(marker "${CMAKE_CURRENT_SOURCE_DIR}/../../../../apple/Sources/HotUpdaterCrashMarker")
4
+ add_library(hotupdater_runtime_recovery SHARED CrashMonitor.c "${marker}/HotUpdaterCrashMarker.c")
5
+ target_include_directories(hotupdater_runtime_recovery PRIVATE "${marker}/include")
6
+ target_compile_features(hotupdater_runtime_recovery PRIVATE c_std_11)
7
+ target_link_options(hotupdater_runtime_recovery PRIVATE "-Wl,-z,max-page-size=16384")
@@ -0,0 +1,23 @@
1
+ #include <jni.h>
2
+ #include "HotUpdaterCrashMarker.h"
3
+
4
+ JNIEXPORT jint JNICALL Java_com_hotupdater_RuntimeCrashMonitor_registerPaths(
5
+ JNIEnv *env, jobject self, jstring candidate, jstring marker) {
6
+ (void)self;
7
+ const char *a = (*env)->GetStringUTFChars(env, candidate, NULL);
8
+ if (!a) return -1;
9
+ const char *b = (*env)->GetStringUTFChars(env, marker, NULL);
10
+ int slot = b ? hu_crash_watch_register(a, b) : -1;
11
+ if (b) (*env)->ReleaseStringUTFChars(env, marker, b);
12
+ (*env)->ReleaseStringUTFChars(env, candidate, a);
13
+ return slot;
14
+ }
15
+ JNIEXPORT void JNICALL Java_com_hotupdater_RuntimeCrashMonitor_arm(JNIEnv *env, jobject self, jint slot) {
16
+ hu_crash_watch_arm(slot);
17
+ }
18
+ JNIEXPORT void JNICALL Java_com_hotupdater_RuntimeCrashMonitor_disarm(JNIEnv *env, jobject self, jint slot) {
19
+ hu_crash_watch_disarm(slot);
20
+ }
21
+ JNIEXPORT void JNICALL Java_com_hotupdater_RuntimeCrashMonitor_onUncaught(JNIEnv *env, jobject self) {
22
+ hu_crash_watch_uncaught();
23
+ }
@@ -0,0 +1,12 @@
1
+ package com.hotupdater
2
+
3
+ /** The archive path emitted by the build adapter and its legacy manifest conventions. */
4
+ class ArtifactEntry(
5
+ val path: String,
6
+ private val legacyLaunchMatch: (String) -> Boolean = { false },
7
+ private val legacyInstallMatch: (String) -> Boolean = { false },
8
+ ) {
9
+ fun matchesLaunch(assetPath: String) = assetPath == path || legacyLaunchMatch(assetPath)
10
+
11
+ fun matchesInstall(assetPath: String) = assetPath == path || legacyInstallMatch(assetPath)
12
+ }
@@ -0,0 +1,97 @@
1
+ package com.hotupdater
2
+
3
+ import kotlinx.coroutines.Dispatchers
4
+ import kotlinx.coroutines.withContext
5
+ import okhttp3.MediaType.Companion.toMediaType
6
+ import okhttp3.OkHttpClient
7
+ import okhttp3.Request
8
+ import okhttp3.RequestBody.Companion.toRequestBody
9
+ import org.json.JSONArray
10
+ import org.json.JSONObject
11
+ import java.util.concurrent.TimeUnit
12
+
13
+ /** A download URL the server signed for one manifest file. */
14
+ data class ResolvedArtifactFile(
15
+ val url: String,
16
+ val compression: String?,
17
+ )
18
+
19
+ /**
20
+ * Artifact protocol v2: the server signs only the files an install downloads
21
+ * one by one, after reusing local files and choosing the archive.
22
+ */
23
+ interface ArtifactFileResolver {
24
+ /** Download URLs for [paths], at most [ARTIFACT_FILES_REQUEST_LIMIT]. */
25
+ suspend fun resolve(paths: List<String>): Map<String, ResolvedArtifactFile>
26
+
27
+ companion object {
28
+ /** `ARTIFACT_FILES_REQUEST_LIMIT` in @hot-updater/protocol. */
29
+ const val ARTIFACT_FILES_REQUEST_LIMIT = 100
30
+ }
31
+ }
32
+
33
+ /**
34
+ * POSTs `{ paths }` to the files URL the SDK composed, with the update check's
35
+ * headers and request timeout. [onResponse] receives each response's status
36
+ * and body, or a null body when it could not be read.
37
+ */
38
+ class HttpArtifactFileResolver(
39
+ private val filesUrl: String,
40
+ private val headers: Map<String, String>,
41
+ private val timeoutMs: Long = DEFAULT_TIMEOUT_MS,
42
+ private val onResponse: ((status: Int, body: String?) -> Unit)? = null,
43
+ ) : ArtifactFileResolver {
44
+ override suspend fun resolve(paths: List<String>): Map<String, ResolvedArtifactFile> =
45
+ withContext(Dispatchers.IO) {
46
+ val body = JSONObject().put("paths", JSONArray(paths)).toString()
47
+ val request =
48
+ Request
49
+ .Builder()
50
+ .url(filesUrl)
51
+ .header("Accept", "application/json")
52
+ .apply { headers.forEach { (name, value) -> header(name, value) } }
53
+ .post(body.toRequestBody("application/json".toMediaType()))
54
+ .build()
55
+ client
56
+ .newBuilder()
57
+ .callTimeout(timeoutMs, TimeUnit.MILLISECONDS)
58
+ .build()
59
+ .newCall(request)
60
+ .execute()
61
+ .use { response ->
62
+ val body =
63
+ try {
64
+ response.body?.string()
65
+ } catch (error: java.io.IOException) {
66
+ onResponse?.invoke(response.code, null)
67
+ throw error
68
+ }
69
+ onResponse?.invoke(response.code, body)
70
+ if (!response.isSuccessful) {
71
+ throw HttpStatusException(response.code, response.message)
72
+ }
73
+ // As JSON.parse reads it, which org.json's parser does not.
74
+ val files =
75
+ (StrictJson.parse(body ?: "") as? JSONObject)?.opt("files") as? JSONObject
76
+ ?: throw InvalidUpdateResponseException("Artifact files response has no files")
77
+ paths.associateWith { path ->
78
+ val file =
79
+ files.opt(path) as? JSONObject
80
+ ?: throw InvalidUpdateResponseException("Artifact files response omits $path")
81
+ ResolvedArtifactFile(
82
+ url =
83
+ file.opt("url") as? String
84
+ ?: throw InvalidUpdateResponseException("Artifact files response has no URL for $path"),
85
+ compression = file.opt("compression") as? String,
86
+ )
87
+ }
88
+ }
89
+ }
90
+
91
+ companion object {
92
+ /** The SDK's request timeout when the app sets none. */
93
+ const val DEFAULT_TIMEOUT_MS = 5_000L
94
+
95
+ private val client = OkHttpClient()
96
+ }
97
+ }