@h1r-ai/croche-react-native 0.5.4 → 0.6.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 (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -0,0 +1,51 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.ffi.*
5
+ import java.util.concurrent.ConcurrentHashMap
6
+
7
+ internal class NativePal(private val storage: CoreStoragePal, private val host: HostPal, private val emit: (String) -> Unit) {
8
+ private val http = ConcurrentHashMap<String, CancelToken>()
9
+ private val httpLock = Any()
10
+ private val cancelledBeforeStart = mutableSetOf<String>()
11
+ private fun JsonElement.bytes(): ByteArray = asJsonArray.map { it.asInt.toByte() }.toByteArray()
12
+ private fun ByteArray.numbers() = map { it.toInt() and 255 }
13
+ fun call(method: String, a: JsonArray): Any? = when (method) {
14
+ "read" -> storage.read(a.text(0)); "write" -> storage.write(a.text(0), a.text(1)).let { null }
15
+ "remove" -> storage.remove(a.text(0)).let { null }; "list" -> storage.list(a.text(0))
16
+ "lock" -> if (storage.lock(a.text(0)) == PalLockOutcome.ACQUIRED) "acquired" else "held"
17
+ "unlock" -> storage.unlock(a.text(0)).let { null }
18
+ "readSecret" -> storage.readSecret(a.text(0)); "writeSecret" -> storage.writeSecret(a.text(0), a.text(1)).let { null }
19
+ "removeSecret" -> storage.removeSecret(a.text(0)).let { null }
20
+ "platformFacts" -> host.platformFacts().let { f -> mapOf("targetKind" to when (f.targetKind) { PalTargetKind.IOS_DEVICE -> "ios-device"; PalTargetKind.IOS_SIMULATOR -> "ios-simulator"; PalTargetKind.ANDROID -> "android"; PalTargetKind.OTHER -> "other" }, "debuggable" to f.debuggable, "locale" to f.locale, "attestationPlatform" to f.attestationPlatform, "browserFetch" to f.browserFetch).filterValues { it != null } }
21
+ "readAsset" -> host.readAsset(a.text(0))?.numbers()
22
+ "resolve" -> host.resolve(a.text(0), CancelToken())
23
+ "readImage" -> host.readImage(PalImageReadRequest(PalImageReadSource.Local(a.text(0)), a[1].asLong.toULong()), CancelToken()).numbers()
24
+ "codecAvailable" -> host.imageCodecAvailable()
25
+ "decode" -> host.decodeImage(a[0].bytes(), PalImageDecodeOptions(0u, true), CancelToken()).let { mapOf("handle" to it.handle, "width" to it.width.toLong(), "height" to it.height.toLong(), "hasAlpha" to it.hasAlpha) }
26
+ "render" -> a[0].asJsonObject.let { p -> host.renderImage(PalImageRenderRequest(p.get("handle").asString, p.get("width").asLong.toUInt(), p.get("height").asLong.toUInt(), if (p.get("format").asString == "png") PalImageFormat.PNG else PalImageFormat.JPEG, p.get("quality")?.asDouble), CancelToken()).numbers() }
27
+ "release" -> host.releaseDecodedImage(a.text(0)).let { null }
28
+ "cancelHttp" -> {
29
+ val id = a.text(0)
30
+ val token = synchronized(httpLock) { http[id].also { if (it == null) cancelledBeforeStart.add(id) } }
31
+ token?.cancel(); null
32
+ }
33
+ "http" -> {
34
+ val id = a.text(0); val p = a[1].asJsonObject; val token = CancelToken()
35
+ val cancelled = synchronized(httpLock) { http[id] = token; cancelledBeforeStart.remove(id) }
36
+ if (cancelled) token.cancel()
37
+ try {
38
+ val request = PalHttpRequest(p.get("connectTo")?.takeUnless { it.isJsonNull }?.asString, p.get("url").asString, p.get("method").asString,
39
+ p.getAsJsonArray("headers").map { PalHeader(it.asJsonArray.text(0), it.asJsonArray.text(1)) },
40
+ p.get("body")?.takeUnless { it.isJsonNull }?.asString, p.get("timeoutMs").asLong.toULong(), p.get("responseMode").asString, p.get("maxResponseBytes").asLong.toULong())
41
+ host.http(request, object : HttpSink(NoHandle) {
42
+ override fun head(status: UShort, headers: List<PalHeader>) { emit(json(mapOf("id" to id, "type" to "head", "status" to status.toInt(), "headers" to headers.map { listOf(it.name, it.value) }))) }
43
+ override fun chunk(bytes: ByteArray): Boolean { emit(json(mapOf("id" to id, "type" to "chunk", "bytes" to bytes.numbers()))); return true }
44
+ }, token)
45
+ null
46
+ } finally { synchronized(httpLock) { http.remove(id) } }
47
+ }
48
+ else -> error("Unknown native PAL method")
49
+ }
50
+ private fun JsonArray.getOrNull(i: Int): JsonElement? = if (size() > i) get(i) else null
51
+ }
@@ -0,0 +1,9 @@
1
+ package dev.croche.reactnative
2
+
3
+ import dev.croche.ffi.HostPal
4
+ import dev.croche.ffi.HostStreamPlatform
5
+
6
+ /** One OS registrar: S7 owns WorkManager registration and schedule timing. */
7
+ internal fun rnHostPal(host: HostPal): HostPal = object : HostPal by host {
8
+ override fun streamPlatform() = HostStreamPlatform.REACT_NATIVE
9
+ }
@@ -1,49 +1,50 @@
1
1
  package dev.croche.reactnative
2
2
 
3
- import com.google.gson.JsonParser
4
- import dev.croche.CrocheException
5
- import dev.croche.ffi.CoreRuntimeInterface
6
- import dev.croche.ffi.EventListener
3
+ import dev.croche.ffi.*
7
4
  import org.junit.Assert.*
8
5
  import org.junit.Test
9
- import java.lang.reflect.Proxy
10
6
 
11
7
  class AgentMemoryTest {
12
- @Test fun everyOperationUsesTheAgentCoreAndPreservesDeferredAndClosed() {
13
- val calls = mutableListOf<Pair<String, List<Any?>>>()
14
- var observer: EventListener? = null
15
- var closed = false
16
- val core = Proxy.newProxyInstance(CoreRuntimeInterface::class.java.classLoader,
17
- arrayOf(CoreRuntimeInterface::class.java)) { _, method, args ->
18
- if (closed) throw CrocheException("closed", "Agent is closed")
19
- calls.add(method.name to (args?.toList() ?: emptyList()))
20
- when (method.name) {
21
- "memoryList" -> "[{\"id\":\"m1\"}]"
22
- "memoryExport" -> "{\"enabled\":true,\"items\":[]}"
23
- "setMemoryObserver" -> { observer = args?.get(0) as EventListener?; null }
24
- else -> "{\"deferred\":true}"
25
- }
26
- } as CoreRuntimeInterface
27
- val args = JsonParser.parseString("{\"id\":\"m1\",\"on\":true}").asJsonObject
28
- val changes = mutableListOf<String>()
29
- assertEquals("[{\"id\":\"m1\"}]", agentMemory(core, "list", args, changes::add))
30
- assertEquals("{\"enabled\":true,\"items\":[]}", agentMemory(core, "export", args, changes::add))
31
- for (op in listOf("delete", "clear", "enabled")) assertEquals("{\"deferred\":true}", agentMemory(core, op, args, changes::add))
32
- assertEquals("null", agentMemory(core, "observe", args, changes::add))
33
- // Don't enter UniFFI's thread attach hook from a pure JVM test; assert the listener is installed.
34
- assertNotNull(observer)
35
- assertEquals(listOf("memoryList", "memoryExport", "memoryDelete", "memoryClear", "memorySetEnabled", "setMemoryObserver"), calls.map { it.first })
36
- assertEquals(listOf("m1"), calls.first { it.first == "memoryDelete" }.second)
37
- assertEquals(listOf(true), calls.first { it.first == "memorySetEnabled" }.second)
38
- args.addProperty("on", false)
39
- agentMemory(core, "observe", args, changes::add)
40
- assertNull(observer)
41
- try { agentMemory(core, "set", args, changes::add); fail("set must be refused") }
42
- catch (error: CrocheException) { assertEquals("invalid_memory", error.code); assertTrue(error.message!!.contains("memory.set")) }
43
- closed = true
44
- for (op in listOf("list", "delete", "clear", "enabled", "export", "observe")) {
45
- try { agentMemory(core, op, args, changes::add); fail("closed $op must be refused") }
46
- catch (error: CrocheException) { assertEquals("closed", error.code) }
47
- }
8
+ @Test fun memoryIsTheS1AgentHandleAndErrorsPassThrough() {
9
+ val agent = MemoryAgentFake()
10
+ val bridge = CoreDispatch({ error("Memory must not open a new host") }, { error("Memory must not request platform storage") }) { error("Memory must not emit a legacy observer event") }
11
+ val id = bridge.handles.hold(agent)
12
+ assertEquals("[{\"id\":\"m1\"}]", bridge.call(id, "memoryList", args("[]")))
13
+ assertNull(bridge.call(id, "memoryDelete", args("[\"m1\"]")))
14
+ assertNull(bridge.call(id, "memoryClear", args("[]")))
15
+ assertNull(bridge.call(id, "memoryEnabled", args("[true]")))
16
+ assertEquals(listOf("memoryList","memoryDelete","memoryClear","memoryEnabled"), agent.calls.map { it.first })
17
+ assertEquals(listOf("m1"), agent.calls[1].second)
18
+ assertEquals(listOf(true), agent.calls[3].second)
19
+ agent.closed = true
20
+ try { bridge.call(id, "memoryList", args("[]")); fail("closed agent must refuse") }
21
+ catch (error: CoreApiException.Failure) { assertEquals("closed", error.code); assertEquals("Agent is closed", error.detail) }
48
22
  }
49
23
  }
24
+
25
+ // A concrete implementation preserves checked Core exceptions without JVM Proxy wrapping.
26
+ private class MemoryAgentFake : CoreAgentInterface {
27
+ val calls = mutableListOf<Pair<String, List<Any?>>>()
28
+ var closed = false
29
+ private fun record(name: String, args: List<Any?> = emptyList()) {
30
+ if (closed) throw CoreApiException.Failure("closed", "Agent is closed", "closed", null, null)
31
+ calls += name to args
32
+ }
33
+ override fun `cancel`(`inputId`: kotlin.String?) = error("Unexpected cancel")
34
+ override fun `clearHistory`() = error("Unexpected clearHistory")
35
+ override fun `decide`(`inputJson`: kotlin.String, `optionsJson`: kotlin.String?, `cancel`: CancelToken?): kotlin.String = error("Unexpected decide")
36
+ override fun `id`(): kotlin.String = error("Unexpected id")
37
+ override fun `instance`(): kotlin.String? = error("Unexpected instance")
38
+ override fun `memoryClear`() { record("memoryClear") }
39
+ override fun `memoryDelete`(`id`: kotlin.String) { record("memoryDelete", listOf(id)) }
40
+ override fun `memoryEnabled`(`on`: kotlin.Boolean) { record("memoryEnabled", listOf(on)) }
41
+ override fun `memoryList`(): kotlin.String { record("memoryList"); return "[{\"id\":\"m1\"}]" }
42
+ override fun `request`(`inputJson`: kotlin.String, `images`: List<CoreImageInput>, `optionsJson`: kotlin.String?, `cancel`: CancelToken?): kotlin.String = error("Unexpected request")
43
+ override fun `resetTools`() = error("Unexpected resetTools")
44
+ override fun `resetWiki`() = error("Unexpected resetWiki")
45
+ override fun `send`(`inputJson`: kotlin.String, `images`: List<CoreImageInput>, `optionsJson`: kotlin.String?, `cancel`: CancelToken?): kotlin.String = error("Unexpected send")
46
+ override fun `setTools`(`scopeJson`: kotlin.String) = error("Unexpected setTools")
47
+ override fun `setWiki`(`scopeJson`: kotlin.String) = error("Unexpected setWiki")
48
+ override fun `shutdown`() = error("Unexpected shutdown")
49
+ override fun `subscribe`(`selectionJson`: kotlin.String, `eventSink`: CoreEventSink): CoreSubscription = error("Unexpected subscribe")
50
+ }
@@ -0,0 +1,71 @@
1
+ package dev.croche.reactnative
2
+
3
+ import dev.croche.ffi.*
4
+ import org.junit.Assert.*
5
+ import org.junit.Test
6
+
7
+ class BackgroundDelegationTest {
8
+ @Test fun backgroundRegistrationAndTimingHaveOnlyTheS7Owner() {
9
+ val wake = CoreBackgroundWake(NoHandle)
10
+ val calls = mutableListOf<String>()
11
+ val refusal = CorePalException.Failure("capability_unsupported", "not installed")
12
+ val base = BackgroundHostFake(wake, calls, refusal)
13
+ val rn = rnHostPal(base)
14
+ try { rn.registerBackground("from-core", wake); fail("silent Ok") }
15
+ catch (actual: CorePalException.Failure) { assertSame(refusal, actual) }
16
+ rn.schedule("opaque schedule")
17
+ assertEquals(listOf("registerBackground", "schedule"), calls)
18
+ assertEquals(HostStreamPlatform.REACT_NATIVE, rn.streamPlatform())
19
+ }
20
+ }
21
+
22
+ // Throw the actual checked PAL error from a concrete method, never a Proxy handler.
23
+ private class BackgroundHostFake(
24
+ private val expectedWake: CoreBackgroundWake,
25
+ private val calls: MutableList<String>,
26
+ private val refusal: CorePalException.Failure,
27
+ ) : HostPal {
28
+ override fun `streamPlatform`(): HostStreamPlatform = error("Unexpected streamPlatform")
29
+ override fun `imageCodecAvailable`(): kotlin.Boolean = error("Unexpected imageCodecAvailable")
30
+ override fun `readImage`(`request`: PalImageReadRequest, `cancel`: CancelToken): kotlin.ByteArray = error("Unexpected readImage")
31
+ override fun `prepareImage`(`source`: PalImageBytes, `plan`: PalImagePreparePlan, `cancel`: CancelToken): PalImageBytes = error("Unexpected prepareImage")
32
+ override fun `releaseImage`(`capture`: kotlin.String) = error("Unexpected releaseImage")
33
+ override fun `decodeImage`(`bytes`: kotlin.ByteArray, `options`: PalImageDecodeOptions, `cancel`: CancelToken): PalDecodedImage = error("Unexpected decodeImage")
34
+ override fun `renderImage`(`request`: PalImageRenderRequest, `cancel`: CancelToken): kotlin.ByteArray = error("Unexpected renderImage")
35
+ override fun `releaseDecodedImage`(`handle`: kotlin.String) = error("Unexpected releaseDecodedImage")
36
+ override fun `http`(`request`: PalHttpRequest, `sink`: HttpSink, `cancel`: CancelToken) = error("Unexpected http")
37
+ override fun `resolve`(`host`: kotlin.String, `cancel`: CancelToken): List<kotlin.String> = error("Unexpected resolve")
38
+ override fun `platformFacts`(): PalPlatformFacts = error("Unexpected platformFacts")
39
+ override fun `readAsset`(`path`: kotlin.String): kotlin.ByteArray? = error("Unexpected readAsset")
40
+ override fun `list`(`prefix`: kotlin.String): List<kotlin.String> = error("Unexpected list")
41
+ override fun `read`(`key`: kotlin.String): kotlin.String? = error("Unexpected read")
42
+ override fun `write`(`key`: kotlin.String, `value`: kotlin.String) = error("Unexpected write")
43
+ override fun `readSecret`(`key`: kotlin.String): kotlin.String? = error("Unexpected readSecret")
44
+ override fun `writeSecret`(`key`: kotlin.String, `value`: kotlin.String) = error("Unexpected writeSecret")
45
+ override fun `remove`(`key`: kotlin.String) = error("Unexpected remove")
46
+ override fun `removeSecret`(`key`: kotlin.String) = error("Unexpected removeSecret")
47
+ override fun `lock`(`key`: kotlin.String): PalLockOutcome = error("Unexpected lock")
48
+ override fun `unlock`(`key`: kotlin.String) = error("Unexpected unlock")
49
+ override fun `storeIdentity`(): kotlin.String = error("Unexpected storeIdentity")
50
+ override fun `tool`(`invocation`: kotlin.String, `cancel`: CancelToken): ToolOutput = error("Unexpected tool")
51
+ override fun `attest`(`request`: kotlin.String, `timeoutMs`: kotlin.ULong): kotlin.String = error("Unexpected attest")
52
+ override fun `nowMs`(): kotlin.Double = error("Unexpected nowMs")
53
+ override fun `utcOffsetMinutes`(`atMs`: kotlin.Double): kotlin.Long = error("Unexpected utcOffsetMinutes")
54
+ override fun `random`(): kotlin.String = error("Unexpected random")
55
+ override fun `wake`(`atMs`: kotlin.Double?) = error("Unexpected wake")
56
+ override fun `schedule`(`entries`: kotlin.String) {
57
+ calls += "schedule"
58
+ assertEquals("opaque schedule", entries)
59
+ }
60
+ override fun `registerBackground`(`identifier`: kotlin.String, `wake`: CoreBackgroundWake) {
61
+ calls += "registerBackground"
62
+ assertEquals("from-core", identifier); assertSame(expectedWake, wake)
63
+ throw refusal
64
+ }
65
+ override fun `archiveAppendLine`(`entry`: kotlin.String, `line`: kotlin.String) = error("Unexpected archiveAppendLine")
66
+ override fun `archiveReadLines`(`entry`: kotlin.String): List<kotlin.String> = error("Unexpected archiveReadLines")
67
+ override fun `archiveReplaceLines`(`entry`: kotlin.String, `lines`: List<kotlin.String>) = error("Unexpected archiveReplaceLines")
68
+ override fun `archiveRemove`(`entry`: kotlin.String) = error("Unexpected archiveRemove")
69
+ override fun `archiveEntries`(`prefix`: kotlin.String): List<ArchiveEntry> = error("Unexpected archiveEntries")
70
+ override fun `storageCapability`(): StorageCapability = error("Unexpected storageCapability")
71
+ }
@@ -0,0 +1,29 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.JsonArray
4
+ import dev.croche.ffi.HostPal
5
+ import java.lang.reflect.Proxy
6
+ import kotlinx.coroutines.runBlocking
7
+ import org.junit.Assert.*
8
+
9
+ /** Capture the actual RN open boundary before the native factory; no native library or network. */
10
+ internal fun forwardedOpen(options: String, recovery: String? = null): String {
11
+ class Captured : RuntimeException()
12
+ var observed: String? = null
13
+ val host = Proxy.newProxyInstance(HostPal::class.java.classLoader, arrayOf(HostPal::class.java)) { _, method, _ ->
14
+ error("Open forwarding must not run a host effect: ${method.name}")
15
+ } as HostPal
16
+ val bridge = CoreDispatch({ host }, { error("Open must use its storage argument") },
17
+ openFactory = { json, registrations, storage, actualHost, actualRecovery ->
18
+ observed = json
19
+ assertEquals(recovery, actualRecovery)
20
+ assertTrue(registrations.isEmpty())
21
+ assertTrue(storage is CallbackStorage)
22
+ assertSame(host, actualHost)
23
+ throw Captured()
24
+ }, emit = { error("Open forwarding must not emit an event") })
25
+ val arguments = JsonArray().apply { add(options); add(JsonArray()); add("storage"); add("host"); add(recovery) }
26
+ try { runBlocking { bridge.open(arguments) }; fail("Capture must interrupt the native factory") }
27
+ catch (_: Captured) { }
28
+ return requireNotNull(observed) { "The real RN open path did not call the factory" }
29
+ }
@@ -1,42 +1,29 @@
1
1
  package dev.croche.reactnative
2
2
 
3
- import com.google.gson.JsonParser
4
- import dev.croche.RuntimeAttestation
5
- import dev.croche.RuntimeAttestor
6
- import dev.croche.RuntimeCancellation
7
- import org.junit.Assert.assertEquals
8
- import org.junit.Assert.assertFalse
9
- import org.junit.Assert.assertNull
3
+ import dev.croche.ffi.*
4
+ import java.lang.reflect.Proxy
5
+ import org.junit.Assert.*
10
6
  import org.junit.Test
11
7
 
12
- /** sdk-internal #24: the host fields the project API gives Core name the attestor's platform
13
- * exactly when the bridge has an attestor. Core's side (it then attests at register) is the
14
- * driver gate `project_a_host_naming_its_attestation_platform_attests_each_agent_at_register`. */
8
+ /** Attestation availability is a PAL fact; RN never derives it from app options. */
15
9
  class ProjectAttestationTest {
16
- private class Fake : RuntimeAttestor {
17
- override val platform = "android-play-integrity"
18
- override fun attest(clientData: String, clientDataHash: String, cancellation: RuntimeCancellation) = RuntimeAttestation("fixture")
10
+ private fun host(facts: PalPlatformFacts): HostPal {
11
+ val base = Proxy.newProxyInstance(HostPal::class.java.classLoader, arrayOf(HostPal::class.java)) { _, method, _ ->
12
+ check(method.name == "platformFacts") { "Unexpected effect ${method.name}" }
13
+ facts
14
+ } as HostPal
15
+ return rnHostPal(base)
19
16
  }
20
- private fun options(extra: String) =
21
- JsonParser.parseString("""{"host":{"cloudUrl":"https://fixture.example","projectKey":"pk_fixture"}$extra}""").asJsonObject
22
- private fun host(extra: String) = options(extra).let { projectHost(it, projectAttestor(it) { Fake() }) }
23
-
24
- @Test fun aCloudProjectNumberGivesAnAttestorAndCoreHearsItsPlatform() {
25
- val host = host(""","android":{"cloudProjectNumber":123}""")
26
- assertEquals("android-play-integrity", host.get("attestationPlatform").asString)
27
- assertEquals("pk_fixture", host.get("projectKey").asString)
17
+ @Test fun availableAttestorFactReachesCoreUnchanged() {
18
+ val facts = PalPlatformFacts(PalTargetKind.ANDROID, false, "ko-KR", "android-play-integrity", false)
19
+ assertSame("platform facts unchanged", facts, host(facts).platformFacts())
28
20
  }
29
-
30
- @Test fun noCloudProjectNumberOrAttestationOffNamesNothing() {
31
- for (extra in listOf("", ""","attestation":"off","android":{"cloudProjectNumber":123}""")) {
32
- assertNull(projectAttestor(options(extra)) { Fake() })
33
- assertFalse(extra, host(extra).has("attestationPlatform"))
34
- }
21
+ @Test fun absentAttestorFactStaysAbsentWithoutSdkDefaults() {
22
+ val facts = PalPlatformFacts(PalTargetKind.OTHER, null, null, null, null)
23
+ assertSame("platform facts unchanged", facts, host(facts).platformFacts())
35
24
  }
36
-
37
- @Test fun theOptionsAreNotChanged() {
38
- val options = options(""","android":{"cloudProjectNumber":123}""")
39
- projectHost(options, projectAttestor(options) { Fake() })
40
- assertFalse(options.getAsJsonObject("host").has("attestationPlatform"))
25
+ @Test fun factsAreNotInjectedIntoTheOptions() {
26
+ val options = """{"projectKey":"pk_fixture","future":{"value":"unchanged"}}"""
27
+ assertEquals("opaque options", options, forwardedOpen(options))
41
28
  }
42
29
  }
@@ -0,0 +1,32 @@
1
+ package dev.croche.reactnative
2
+
3
+ import java.util.concurrent.CountDownLatch
4
+ import org.junit.Assert.*
5
+ import org.junit.Test
6
+
7
+ /** The SDK retains opaque callback references, not its own per-instance handler registry. */
8
+ class ProjectHandlerStagesTest {
9
+ @Test fun concurrentTransportOwnersKeepTheirOwnReferencesAndCleanup() {
10
+ val handles = CoreHandles()
11
+ val start = CountDownLatch(1)
12
+ val values = listOf(Any(), Any())
13
+ val ids = arrayOfNulls<String>(2)
14
+ val workers = values.mapIndexed { i, value -> Thread { start.await(); ids[i] = handles.hold(value) }.also { it.start() } }
15
+ start.countDown(); workers.forEach { it.join() }
16
+ assertNotEquals("transport handles do not alias", ids[0], ids[1])
17
+ assertSame("transport owner unchanged", values[0], handles.value(ids[0]!!))
18
+ assertSame("transport owner unchanged", values[1], handles.value(ids[1]!!))
19
+ handles.forget(ids[0]!!)
20
+ assertSame("transport owner unchanged", values[1], handles.value(ids[1]!!))
21
+ try { handles.value(ids[0]!!); fail("Retired handle must be absent") } catch (_: IllegalStateException) { }
22
+ }
23
+ @Test fun agentLabelsAndMaintenanceNamesAreOpaqueValues() {
24
+ val handles = CoreHandles()
25
+ val names = listOf("default", "other", "[\"도우미\",\"thread/one\"]", "[\"\$gc\",\"pass\"]")
26
+ val ids = names.map(handles::hold)
27
+ assertEquals("transport handles do not alias", names.size, ids.toSet().size)
28
+ ids.zip(names).forEach { (id, value) -> assertEquals("transport owner unchanged", value, handles.value(id)) }
29
+ handles.clear()
30
+ for (id in ids) try { handles.value(id); fail("Cleared handle must be absent") } catch (_: IllegalStateException) { }
31
+ }
32
+ }
@@ -0,0 +1,12 @@
1
+ package dev.croche.reactnative
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Test
5
+
6
+ class ProjectRecoveryTest {
7
+ @Test fun recoveryJsonIsASeparateUnchangedNativeArgument() {
8
+ for (mode in listOf("{\"recover\":\"delete\"}", "{}", "{\"recover\":\"invalid\"}")) {
9
+ assertEquals("{\"wholeOptions\":true}", forwardedOpen("{\"wholeOptions\":true}", mode))
10
+ }
11
+ }
12
+ }
@@ -1,24 +1,20 @@
1
1
  package dev.croche.reactnative
2
2
 
3
- import com.google.gson.JsonParser
4
- import dev.croche.CrocheException
5
- import org.junit.Assert.*
3
+ import org.junit.Assert.assertEquals
6
4
  import org.junit.Test
7
5
 
6
+ /** Core owns defaults/validation. The RN open transport preserves each input literally. */
8
7
  class ProjectTimeZoneTest {
9
- private fun options(json: String) = JsonParser.parseString(json).asJsonObject
10
-
11
- @Test fun passedZoneChangesTheOffset() {
12
- assertEquals(-600, projectZone(options("""{"timeZone":"Pacific/Honolulu"}"""))!!.getOffset(0) / 60_000)
8
+ @Test fun explicitZoneReachesCoreUnchanged() {
9
+ val options = """{"projectKey":"pk_fixture","timeZone":"Pacific/Honolulu"}"""
10
+ assertEquals("opaque options", options, forwardedOpen(options))
13
11
  }
14
- @Test fun absentAndNullKeepTheDeviceZone() {
15
- assertNull(projectZone(options("{}")))
16
- assertNull(projectZone(options("""{"timeZone":null}""")))
12
+ @Test fun absentAndNullReachCoreWithoutADeviceDefault() {
13
+ for (options in listOf("""{"projectKey":"pk_fixture"}""", """{"projectKey":"pk_fixture","timeZone":null}"""))
14
+ assertEquals("opaque options", options, forwardedOpen(options))
17
15
  }
18
- @Test fun badZoneAndNonStringAreInvalidConfiguration() {
19
- for (json in listOf("""{"timeZone":"Not/AZone"}""", """{"timeZone":42}""")) {
20
- try { projectZone(options(json)); fail("Invalid timeZone accepted") }
21
- catch (error: CrocheException) { assertEquals("invalid_configuration", error.code) }
22
- }
16
+ @Test fun invalidZoneAndNonStringReachCoresValidatorUnchanged() {
17
+ for (options in listOf("""{"projectKey":"pk_fixture","timeZone":"Not/AZone"}""", """{"projectKey":"pk_fixture","timeZone":42}"""))
18
+ assertEquals("opaque options", options, forwardedOpen(options))
23
19
  }
24
20
  }
@@ -0,0 +1,27 @@
1
+ package dev.croche.android
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import dev.croche.ffi.CoreDelivery
6
+ import dev.croche.ffi.CoreEventSink
7
+
8
+ /** Platform dispatch only. Core owns serialization, buffering, entry fences and completion.
9
+ * No SDK queue; the platform's UI dispatcher runs the one delivery supplied by Core. */
10
+ internal class AndroidEventSink(private val onEvent: (String) -> Unit) : CoreEventSink {
11
+ private val ui = Handler(Looper.getMainLooper())
12
+ override fun deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) {
13
+ val invoke = Runnable {
14
+ if (!delivery.tryEnter()) return@Runnable
15
+ val outcome = try {
16
+ onEvent(eventJson)
17
+ "{\"outcome\":\"returned\"}"
18
+ } catch (_: Throwable) {
19
+ // This is the invocation fact, not an SDK error code/category decision.
20
+ "{\"outcome\":\"threw\"}"
21
+ }
22
+ delivery.complete(outcome)
23
+ }
24
+ if (Looper.myLooper() == ui.looper) invoke.run()
25
+ else if (!ui.post(invoke)) delivery.complete("{\"outcome\":\"unavailable\"}")
26
+ }
27
+ }
@@ -9,7 +9,7 @@ import com.google.android.play.core.integrity.IntegrityServiceException
9
9
  import com.google.android.play.core.integrity.IntegrityTokenRequest
10
10
  import com.google.gson.JsonObject
11
11
  import com.google.gson.JsonParser
12
- import dev.croche.CrocheException
12
+ import dev.croche.CrocheError
13
13
  import dev.croche.RuntimeAttestation
14
14
  import dev.croche.RuntimeAttestor
15
15
  import dev.croche.RuntimeCancellation
@@ -64,8 +64,8 @@ class KeystoreSecretStore(context: Context, name: String) : RuntimeSecretStore {
64
64
  file.delete(); return JsonObject()
65
65
  }
66
66
  val saved = try { JsonParser.parseString(String(plain, Charsets.UTF_8)) }
67
- catch (_: Exception) { throw CrocheException("corrupt_store", "Runtime credentials are unreadable") }
68
- if (!saved.isJsonObject) throw CrocheException("corrupt_store", "Runtime credentials must be an object")
67
+ catch (_: Exception) { throw CrocheError("corrupt_store", "Runtime credentials are unreadable") }
68
+ if (!saved.isJsonObject) throw CrocheError("corrupt_store", "Runtime credentials must be an object")
69
69
  return saved.asJsonObject
70
70
  }
71
71
 
@@ -79,7 +79,7 @@ class KeystoreSecretStore(context: Context, name: String) : RuntimeSecretStore {
79
79
  val temporary = File(file.parentFile, file.name + ".tmp")
80
80
  try {
81
81
  FileOutputStream(temporary).use { output -> output.write(sealed); output.fd.sync() }
82
- if (!temporary.renameTo(file)) throw CrocheException("storage_error", "Could not replace Runtime credentials")
82
+ if (!temporary.renameTo(file)) throw CrocheError("storage_error", "Could not replace Runtime credentials")
83
83
  } finally { temporary.delete() }
84
84
  }
85
85
 
@@ -117,7 +117,7 @@ class PlayIntegrityAttestor(context: Context, private val cloudProjectNumber: Lo
117
117
  // -1 API_NOT_AVAILABLE) is what a release setup is debugged with, and it carries no
118
118
  // secret. The Core shows the host's code, not its message, so the number goes there.
119
119
  val play = generateSequence<Throwable>(e) { it.cause }.filterIsInstance<IntegrityServiceException>().firstOrNull()
120
- throw CrocheException(play?.let { "play_integrity_${it.errorCode}" } ?: "attestation_failed", "Play Integrity could not attest this app")
120
+ throw CrocheError(play?.let { "play_integrity_${it.errorCode}" } ?: "attestation_failed", "Play Integrity could not attest this app")
121
121
  }
122
122
  cancellation.check()
123
123
  return RuntimeAttestation(response.token())
@@ -125,7 +125,7 @@ class PlayIntegrityAttestor(context: Context, private val cloudProjectNumber: Lo
125
125
  }
126
126
 
127
127
  /** The wiki documents shipped in the app's assets under `folder` (`src/main/assets/wiki/`),
128
- * paths relative to it: `CrocheRuntime.create(..., wiki = wikiFromAssets(context.assets))`. */
128
+ * paths relative to it: `LegacyAgentEngine.create(..., wiki = wikiFromAssets(context.assets))`. */
129
129
  fun wikiFromAssets(assets: android.content.res.AssetManager, folder: String = "wiki"): List<dev.croche.WikiDocument> =
130
130
  dev.croche.WikiDocument.fromTree(
131
131
  list = { path -> assets.list(if (path.isEmpty()) folder else "$folder/$path") },
@@ -0,0 +1,16 @@
1
+ package dev.croche.android
2
+
3
+ import android.content.Context
4
+ import dev.croche.ffi.CoreStoragePal
5
+ import dev.croche.ffi.CoreEventSink
6
+ import dev.croche.ffi.HostPal
7
+ import dev.croche.s7.BackgroundCalls
8
+
9
+ /** Explicit Context resolves the native PAL; the whole options JSON reaches Core unchanged. */
10
+ internal class BackgroundRegistration(
11
+ private val hostForContext: (Context) -> HostPal,
12
+ private val storageForContext: (Context) -> CoreStoragePal,
13
+ ) {
14
+ fun registerBackground(context: Context, optionsJson: String, sink: CoreEventSink? = null) =
15
+ BackgroundCalls.registerBackground(optionsJson, storageForContext(context), hostForContext(context), sink)
16
+ }
@@ -0,0 +1,51 @@
1
+ package dev.croche.android
2
+
3
+ import android.content.Context
4
+ import androidx.work.ExistingWorkPolicy
5
+ import androidx.work.OneTimeWorkRequestBuilder
6
+ import androidx.work.WorkManager
7
+ import androidx.work.Worker
8
+ import androidx.work.WorkerParameters
9
+ import dev.croche.ffi.CancelToken
10
+ import dev.croche.ffi.CoreBackgroundWake
11
+ import dev.croche.s7.BackgroundOsRegistration
12
+ import java.util.concurrent.TimeUnit
13
+
14
+ /** Process callback only. The Core wake object owns a weak service reference. */
15
+ internal object AndroidBackgroundWake {
16
+ @Volatile private var registration: BackgroundOsRegistration? = null
17
+
18
+ @Synchronized fun install(context: Context, identifier: String, wake: CoreBackgroundWake) {
19
+ val app = context.applicationContext
20
+ val entry = registration ?: BackgroundOsRegistration { name, keep, delay ->
21
+ val work = OneTimeWorkRequestBuilder<BackgroundWakeWorker>()
22
+ .setInitialDelay(delay, TimeUnit.MILLISECONDS).build()
23
+ // A returned Operation is not confirmation; wait for WorkManager's persisted result.
24
+ WorkManager.getInstance(app).enqueueUniqueWork(name,
25
+ if (keep) ExistingWorkPolicy.KEEP else ExistingWorkPolicy.REPLACE, work).result.get()
26
+ Unit
27
+ }
28
+ entry.install(identifier, wake)
29
+ registration = entry
30
+ }
31
+
32
+ fun schedule(earliest: Long?, now: Long) { registration?.schedule(earliest, now) }
33
+ fun callback(): CoreBackgroundWake? = registration?.wake()
34
+ }
35
+
36
+ /** No SDK retries, tools or turns. WorkManager stop cancels only this Core wake run. */
37
+ class BackgroundWakeWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
38
+ private val cancel = CancelToken()
39
+ private val stopLock = Any()
40
+ private var finished = false
41
+ override fun doWork(): Result {
42
+ if (isStopped) cancel.cancel()
43
+ try {
44
+ // WorkManager exposes no absolute execution deadline, so pass null, not a guess.
45
+ AndroidBackgroundWake.callback()?.run(null, cancel)
46
+ return Result.success()
47
+ } catch (_: Exception) { return Result.failure() }
48
+ finally { synchronized(stopLock) { finished = true; cancel.close() } }
49
+ }
50
+ override fun onStopped() { synchronized(stopLock) { if (!finished) cancel.cancel() } }
51
+ }