@h1r-ai/croche-react-native 0.6.0 → 0.7.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 (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -4,6 +4,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
4
4
  import androidx.test.platform.app.InstrumentationRegistry
5
5
  import com.google.gson.JsonArray
6
6
  import com.google.gson.JsonParser
7
+ import dev.croche.SelectedAdapters
7
8
  import dev.croche.ffi.*
8
9
  import dev.croche.s7.CoreFactoryCalls
9
10
  import dev.croche.s7.attached
@@ -24,7 +25,7 @@ import org.junit.runner.RunWith
24
25
  private const val CONFIG = """{"schema":7,"project":{"defaults":{"model":"google/gemini-3.8-flash"},
25
26
  "languages":{"default":"en","supported":["en"]}},"agents":{"helper":{"instructions":"Reply briefly."}}}"""
26
27
  private const val REGISTER = """{"runtime_token":"synthetic_______________________________________________________","project_id":"prj_test","user_id":"usr_test","gateway_key":{"gateway":"openrouter","base_url":"https://openrouter.ai/api/v1","key_id":"local","api_key":"synthetic","limit":1,"models":["google/gemini-3.8-flash"]}}"""
27
- private const val SYNC = """{"protocol_version":1,"control_version":1,"project_id":"prj_test","host_budget_control":{"enabled":true,"currency":"USD","version":1,"expires_at":"2099-01-01T00:00:00Z","limits":{"max_user_allowance":2,"max_single_adjustment":0.5,"max_positive_adjustment_per_window":1},"window":{"type":"daily"}},"user_allowance":{"user_id":"usr_test","allowance":1,"policy_version":1},"runtime_policy":{}}"""
28
+ private const val SYNC = """{"protocol_version":1,"control_version":1,"project_id":"prj_test","host_budget_control":{"enabled":true,"currency":"USD","version":1,"expires_at":"2099-01-01T00:00:00Z","limits":{"max_user_allowance":2,"default_user_allowance":1},"window":{"type":"daily"}},"user_allowance":{"user_id":"usr_test","policy_version":1},"runtime_policy":{}}"""
28
29
  private fun frame(delta: String, finish: String = "null", usage: String = "") =
29
30
  "data: {\"id\":\"gen-local\",\"model\":\"google/gemini-3.8-flash\",\"choices\":[{\"index\":0,\"delta\":$delta,\"finish_reason\":$finish}]$usage}\n\n"
30
31
  private const val USAGE = ",\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":3,\"total_tokens\":13,\"cost\":0}"
@@ -81,7 +82,7 @@ class WikiFileBridgeTest {
81
82
  val absent = File(file.parentFile, "absent-${UUID.randomUUID()}.md").toURI().toString()
82
83
  file.writeText("Written before open.")
83
84
  val uri = file.toURI().toString()
84
- val pals = nativePlatform(InstrumentationRegistry.getInstrumentation().targetContext, null)
85
+ val pals = nativePlatform(InstrumentationRegistry.getInstrumentation().targetContext, SelectedAdapters())
85
86
  val host = WikiFakeHost(rnHostPal(pals.host))
86
87
  val dispatch = CoreDispatch({ host }, { pals.storage },
87
88
  openFactory = { json, registrations, _, actual, recoveryJson -> CoreFactoryCalls.open(json, registrations, pals.storage, actual, recoveryJson = recoveryJson) },
@@ -90,7 +91,7 @@ class WikiFileBridgeTest {
90
91
  {"path":"policy.md","description":"Refund policy","file":"$uri"},{"path":"absent.md","description":"Gone","file":"$absent"}]}"""
91
92
  val root = withContext(Dispatchers.IO) { dispatch.open(JsonArray().apply { add(options); add(JsonArray()); add("storage"); add("host") }) }
92
93
  try {
93
- val listed = JsonParser.parseString(dispatch.call(root, "wikiList", JsonArray()) as String).asJsonArray
94
+ val listed = JsonParser.parseString(dispatch.call(root, "wikiList", JsonArray()) as String).asJsonObject.getAsJsonArray("items").asJsonArray
94
95
  assertEquals(setOf("policy.md", "absent.md"), listed.map { it.asJsonObject.get("path").asString }.toSet())
95
96
  assertEquals(emptyList<String>(), host.reads.toList())
96
97
  file.writeText("Written after open.")
@@ -1,8 +1,3 @@
1
1
  <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
2
  <uses-permission android:name="android.permission.INTERNET" />
3
- <application>
4
- <provider android:name="dev.croche.android.CrocheProjectRecordProvider"
5
- android:authorities="${applicationId}.croche.project-record"
6
- android:exported="false" />
7
- </application>
8
3
  </manifest>
@@ -16,22 +16,35 @@ internal class CoreDispatch(
16
16
  val handles = CoreHandles()
17
17
  val callbacks = CoreCallbacks(emit)
18
18
  private fun storage(a: JsonArray) = CallbackStorage(a.text(2), a.text(3), callbacks)
19
+ private fun selectedHost(a: JsonArray, supportIndex: Int): HostPal =
20
+ CallbackHost(host(), a.text(3), a.takeIf { it.size() > supportIndex }?.get(supportIndex)?.takeUnless { it.isJsonNull }?.toString(),
21
+ callbacks, handles, a.takeIf { it.size() > supportIndex + 1 }?.get(supportIndex + 1)?.asBoolean == true)
19
22
  suspend fun open(a: JsonArray): String {
20
23
  val registrations = a[1].asJsonArray.map {
21
24
  val row = it.asJsonObject
22
25
  CoreToolRegistration(handles.get(row.get("tool").asString), row.get("optionsJson")?.asString)
23
26
  }
24
- return handles.hold(openFactory(a.text(0), registrations, storage(a), host(), a.optional(4)))
27
+ return handles.hold(openFactory(a.text(0), registrations, storage(a), selectedHost(a, 5), a.optional(4)))
25
28
  }
26
- fun call(id: String, method: String, a: JsonArray, images: List<CoreImageInput> = emptyList()): Any? {
29
+ fun call(id: String, method: String, a: JsonArray, images: List<CoreAttachmentInput> = emptyList()): Any? {
27
30
  if (method == "release") { handles.forget(id); return null }
28
31
  if (id.isEmpty()) return when (method) {
32
+ "platformImageSupport" -> host().imageSupport()?.let { JsonParser.parseString(it) }
33
+ "platformImageOperation" -> host().imageOperation(a.text(0), a[1].asJsonArray.map { it.asInt.toByte() }.toByteArray(), a[2].toString(), handles.get(a.text(3))).let {
34
+ mapOf("info" to JsonParser.parseString(it.metadataJson), "bytes" to it.bytes.map { b -> b.toInt() and 255 })
35
+ }
29
36
  "newCancel" -> handles.hold(CancelToken())
30
37
  "defineTool" -> handles.hold(CoreToolDefinition(a.text(0), attached(NativeExecute(a.text(1), callbacks, handles))))
31
38
  "webSearch" -> handles.hold(coreWebSearch())
32
- "wakeTimes" -> coreWakeTimes(a.text(0), a.optional(1), attached(storage(a)), attached(host()))
39
+ "image" -> handles.hold(coreImage())
40
+ "wakeTimes" -> coreWakeTimes(a.text(0), a.optional(1), attached(storage(a)), attached(selectedHost(a, 4)))
33
41
  // The same CoreEventSink/CoreDelivery protocol as subscribe; no fake ack.
34
- "registerBackground" -> coreRegisterBackground(a.text(0), a.optional(1)?.let { attached(NativeSink(it, callbacks, handles)) }, attached(storage(a)), a.optional(4)?.let { attached(platformStorage()) }, attached(host()), rnBindingFacts).let { null }
42
+ "registerBackground" -> {
43
+ val backgroundHost = if (a.size() > 6 && a[6].asBoolean) selectedHost(a, 5) else host()
44
+ coreRegisterBackground(a.text(0), a.optional(1)?.let { attached(NativeSink(it, callbacks, handles)) },
45
+ attached(storage(a)), a.optional(4)?.let { attached(platformStorage()) }, attached(backgroundHost), rnBindingFacts)
46
+ null
47
+ }
35
48
  else -> error("Unknown native module method")
36
49
  }
37
50
  val owner = handles.value(id)
@@ -41,14 +54,19 @@ internal class CoreDispatch(
41
54
  "complete" -> owner.complete(a.text(0)).also { handles.forget(id) }.let { null }
42
55
  else -> error("Unknown delivery method")
43
56
  }
57
+ if (owner is CoreAttachmentReader) { check(method == "attachment"); return owner.attachment(a.text(0)) }
44
58
  if (owner is CoreToolDefinition) { check(method == "name"); return owner.name() }
45
59
  if (owner is CoreCroche) return when (method) {
46
60
  "runTool" -> owner.runTool(a.text(0), a.text(1), a.text(2), handles.get(a.text(3)))
61
+ "attachment" -> owner.attachment(a.text(0))
62
+ "deleteAttachment" -> owner.deleteAttachment(a.text(0)).let { null }
63
+ "listAttachments" -> owner.listAttachments(a.optional(0))
64
+ "allowanceSet" -> owner.allowanceSet(a.text(0)).let { null }
65
+ "verification" -> owner.verification()
47
66
  "agent" -> handles.hold(owner.agent(a.text(0), a.optional(1)))
48
67
  "deleteData" -> owner.deleteData(a.optional(0)).let { null }
49
- "agentIds" -> owner.agentIds()
50
68
  "deliverDue" -> owner.deliverDue(a.optional(0), handles.get(a.text(1)))
51
- "wikiList" -> owner.wikiList()
69
+ "wikiList" -> owner.wikiList(a.optional(0))
52
70
  "wikiPut" -> owner.wikiPut(a.text(0)).let { null }
53
71
  "wikiRemove" -> owner.wikiRemove(a.text(0)).let { null }
54
72
  "debugAttach" -> owner.debugAttach(a.text(0))
@@ -57,13 +75,20 @@ internal class CoreDispatch(
57
75
  else -> error("Unknown project method")
58
76
  }
59
77
  if (owner is CoreAgentInterface) return when (method) {
78
+ "attachment" -> owner.attachment(a.text(0))
79
+ "deleteAttachment" -> owner.deleteAttachment(a.text(0)).let { null }
80
+ "listAttachments" -> owner.listAttachments(a.optional(0))
81
+ "copyAttachment" -> owner.copyAttachment(a.text(0))
82
+ "releaseAttachment" -> owner.releaseAttachment(a.text(0)).let { null }
83
+
60
84
  "id" -> owner.id(); "instance" -> owner.instance()
85
+ "decide" -> owner.decide(a.text(0), a.optional(1), handles.get(a.text(2)))
61
86
  "send" -> owner.send(a.text(0), images, a.optional(1), handles.get(a.text(2)))
62
87
  "request" -> owner.request(a.text(0), images, a.optional(1), handles.get(a.text(2)))
63
88
  "subscribe" -> handles.hold(owner.subscribe(a.text(0), attached(NativeSink(a.text(1), callbacks, handles))))
64
89
  "cancel" -> owner.cancel(a.optional(0)).let { null }
65
- "clearHistory" -> owner.clearHistory().let { null }
66
- "memoryList" -> owner.memoryList(); "memoryDelete" -> owner.memoryDelete(a.text(0)).let { null }
90
+ "clearHistory" -> owner.clearHistory(a.optional(0)).let { null }
91
+ "memoryList" -> owner.memoryList(a.optional(0)); "memoryDelete" -> owner.memoryDelete(a.text(0)).let { null }
67
92
  "memoryClear" -> owner.memoryClear().let { null }; "memoryEnabled" -> owner.memoryEnabled(a[0].asBoolean).let { null }
68
93
  "setTools" -> owner.setTools(a.text(0)).let { null }; "resetTools" -> owner.resetTools().let { null }
69
94
  "setWiki" -> owner.setWiki(a.text(0)).let { null }; "resetWiki" -> owner.resetWiki().let { null }
@@ -2,12 +2,17 @@ package dev.croche.reactnative
2
2
 
3
3
  import com.google.gson.*
4
4
  import dev.croche.ffi.*
5
+ import dev.croche.s7.toCore
6
+ import dev.croche.s7.versionedStorageKey
7
+ import dev.croche.s7.storageVersion
8
+ import dev.croche.s7.storageCallback
5
9
  import dev.croche.s7.attached
6
10
  import java.util.UUID
7
11
  import java.util.concurrent.ConcurrentHashMap
8
12
  import java.util.concurrent.CountDownLatch
9
13
 
10
- internal val rnGson = Gson()
14
+ // Required nullable storage fields must remain present on the wire.
15
+ internal val rnGson = GsonBuilder().serializeNulls().create()
11
16
  internal fun json(value: Any?): String = rnGson.toJson(value)
12
17
  internal fun args(text: String): JsonArray = JsonParser.parseString(text).asJsonArray
13
18
  internal fun JsonArray.text(i: Int): String = get(i).asString
@@ -19,7 +24,7 @@ internal class CoreHandles {
19
24
  fun hold(value: Any): String = UUID.randomUUID().toString().also { handles[it] = value }
20
25
  inline fun <reified T> get(id: String): T = value(id) as T
21
26
  fun value(id: String): Any = handles[id] ?: error("Unknown native transport handle")
22
- fun forget(id: String) { handles.remove(id) }
27
+ fun forget(id: String) { (handles.remove(id) as? Disposable)?.destroy() }
23
28
  fun clear() { handles.clear() }
24
29
  }
25
30
  internal class CoreCallbacks(private val emit: (String) -> Unit) {
@@ -37,6 +42,58 @@ internal class CoreCallbacks(private val emit: (String) -> Unit) {
37
42
  fun reply(id: String, text: String) { pending[id]?.let { it.json = text; it.done.countDown() } }
38
43
  fun invalidate() { alive = false; pending.values.forEach { it.done.countDown() } }
39
44
  }
45
+ internal fun p1Nullable(value: JsonElement?): String? {
46
+ if (value == null) throw CoreStorageFailure.Failure("Missing storage field")
47
+ if (value.isJsonNull) return null
48
+ if (!value.isJsonPrimitive || !value.asJsonPrimitive.isString) throw CoreStorageFailure.Failure("Invalid storage field")
49
+ return value.asString
50
+ }
51
+ internal fun stateRequiredString(value: JsonElement?): String =
52
+ p1Nullable(value) ?: throw CoreStorageFailure.Failure("Missing StateStore field")
53
+
54
+ internal fun stateOps(raw: JsonArray): List<CoreStateOp> = raw.map { encoded ->
55
+ val row = encoded.asJsonObject
56
+ val key = stateRequiredString(row.get("key"))
57
+ when (stateRequiredString(row.get("type"))) {
58
+ "put" -> CoreStateOp.Put(key, stateRequiredString(row.get("value")))
59
+ "delete" -> CoreStateOp.Delete(key)
60
+ else -> throw CoreStorageFailure.Failure("Invalid StateStore operation")
61
+ }
62
+ }
63
+
64
+ /** The app StateStore's list options, as the wire carries them: every field optional. */
65
+ internal fun stateListOptions(raw: JsonElement): CoreStateListOptions {
66
+ val fields = raw.asJsonObject
67
+ val limit = fields.get("limit")?.takeUnless { it.isJsonNull }?.let {
68
+ val value = it.asJsonPrimitive
69
+ if (!value.isNumber || value.asDouble != value.asLong.toDouble() || value.asLong !in 1..UInt.MAX_VALUE.toLong()) {
70
+ throw CoreStorageFailure.Failure("Invalid StateStore range limit")
71
+ }
72
+ value.asLong.toUInt()
73
+ }
74
+ val reverse = fields.get("reverse")?.takeUnless { it.isJsonNull }?.let {
75
+ if (!it.isJsonPrimitive || !it.asJsonPrimitive.isBoolean) throw CoreStorageFailure.Failure("Invalid StateStore range direction")
76
+ it.asBoolean
77
+ } ?: false
78
+ // An absent field and a JSON null both mean "not given".
79
+ fun text(name: String) = fields.get(name)?.let(::p1Nullable)
80
+ return CoreStateListOptions(text("start"), reverse, limit, text("cursor"))
81
+ }
82
+
83
+ private fun stateListOptionsJson(options: CoreStateListOptions) = buildMap<String, Any> {
84
+ options.start?.let { put("start", it) }
85
+ if (options.reverse) put("reverse", true)
86
+ options.limit?.let { put("limit", it.toLong()) }
87
+ options.cursor?.let { put("cursor", it) }
88
+ }
89
+
90
+ private fun stateOpsJson(ops: List<CoreStateOp>) = ops.map {
91
+ when (it) {
92
+ is CoreStateOp.Put -> mapOf("type" to "put", "key" to it.key, "value" to it.value)
93
+ is CoreStateOp.Delete -> mapOf("type" to "delete", "key" to it.key)
94
+ }
95
+ }
96
+
40
97
  internal class CallbackStorage(private val id: String, private val host: String, private val callbacks: CoreCallbacks) : CoreStoragePal {
41
98
  private fun call(method: String, vararg arguments: Any?): JsonElement = try {
42
99
  val result = JsonParser.parseString(callbacks.invoke(mapOf("type" to "storage", "storage" to id, "method" to method, "args" to arguments))).asJsonObject
@@ -44,9 +101,41 @@ internal class CallbackStorage(private val id: String, private val host: String,
44
101
  result.get("value") ?: error("Missing storage reply")
45
102
  } catch (error: CoreStorageFailure) { throw error }
46
103
  catch (error: Throwable) { throw CoreStorageFailure.Failure(error.message ?: "") }
104
+ override fun listState(prefix: String, options: CoreStateListOptions): CoreStatePage = storageCallback {
105
+ val page = call("listState", prefix, stateListOptionsJson(options)).asJsonObject
106
+ val entries = page.getAsJsonArray("entries").map {
107
+ val row = it.asJsonObject
108
+ CoreStateEntry(stateRequiredString(row.get("key")), stateRequiredString(row.get("value")))
109
+ }
110
+ CoreStatePage(entries, page.get("nextCursor")?.let(::p1Nullable))
111
+ }
112
+ override fun commitState(ops: List<CoreStateOp>, condition: CoreStateCondition): CoreStateCommit = storageCallback {
113
+ val guard = mapOf("key" to condition.key, "version" to condition.version)
114
+ val result = call("commit", stateOpsJson(ops), guard).asJsonObject
115
+ when (stateRequiredString(result.get("type"))) {
116
+ "committed" -> CoreStateCommit.Committed(p1Nullable(result.get("version")))
117
+ "conflict" -> CoreStateCommit.Conflict
118
+ else -> throw CoreStorageFailure.Failure("Invalid StateStore commit reply")
119
+ }
120
+ }
121
+ override fun readVersioned(key: String): CoreVersionedValue = storageCallback {
122
+ val result = call("readVersioned", versionedStorageKey(key)).asJsonObject
123
+ dev.croche.VersionedValue(p1Nullable(result.get("value")), p1Nullable(result.get("version"))).toCore()
124
+ }
125
+ override fun writeIf(key: String, value: String?, expect: String?): CoreWriteOutcome = storageCallback {
126
+ val result = call("writeIf", versionedStorageKey(key), value, storageVersion(expect)).asJsonObject
127
+ val version = p1Nullable(result.get("version"))
128
+ val outcome = when (p1Nullable(result.get("type"))) {
129
+ "written" -> dev.croche.WriteOutcome.Written(version)
130
+ "conflict" -> dev.croche.WriteOutcome.Conflict(version)
131
+ else -> throw CoreStorageFailure.Failure("Invalid conditional outcome")
132
+ }
133
+ outcome.toCore(value)
134
+ }
47
135
  override fun read(key: String) = call("read", key).let { if (it.isJsonNull) null else it.asString }
48
136
  override fun write(key: String, value: String) { call("write", key, value) }
49
137
  override fun remove(key: String) { call("remove", key) }
138
+ override fun purgeInstance(prefix: String, secretKey: String?) { call("purgeInstance", prefix, secretKey) }
50
139
  override fun list(prefix: String) = call("list", prefix).asJsonArray.map { it.asString }
51
140
  override fun lock(name: String) = when (call("lock", name).asString) {
52
141
  "acquired" -> PalLockOutcome.ACQUIRED; "held" -> PalLockOutcome.HELD
@@ -64,11 +153,12 @@ internal class CallbackStorage(private val id: String, private val host: String,
64
153
  internal class NativeExecute(private val execute: String, private val callbacks: CoreCallbacks, private val handles: CoreHandles) : CoreToolExecute {
65
154
  @Suppress("deprecation")
66
155
  protected fun finalize() { runCatching { callbacks.post(mapOf("type" to "retired", "executors" to listOf(execute), "hosts" to emptyList<String>(), "storages" to emptyList<String>(), "sinks" to emptyList<String>(), "tokens" to emptyList<String>())) } }
67
- override fun execute(callJson: String, contextJson: String, cancel: CancelToken): String {
156
+ override fun execute(callJson: String, contextJson: String, cancel: CancelToken, attachments: CoreAttachmentReader): String {
68
157
  val token = handles.hold(cancel)
158
+ val reader = handles.hold(attachments)
69
159
  cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { callbacks.post(mapOf("type" to "cancel", "token" to token)) } }))
70
- return try { callbacks.invoke(mapOf("type" to "execute", "execute" to execute, "callJson" to callJson, "contextJson" to contextJson, "cancel" to token)) }
71
- catch (_: Throwable) { "{\"type\":\"unavailable\"}" }
160
+ return try { callbacks.invoke(mapOf("type" to "execute", "execute" to execute, "callJson" to callJson, "contextJson" to contextJson, "cancel" to token, "attachments" to reader)) }
161
+ catch (_: Throwable) { handles.forget(reader); "{\"type\":\"unavailable\"}" }
72
162
  finally { handles.forget(token) }
73
163
  }
74
164
  }
@@ -81,3 +171,47 @@ internal class NativeSink(private val sink: String, private val callbacks: CoreC
81
171
  catch (error: Throwable) { delivery.complete("{\"outcome\":\"unavailable\"}"); handles.forget(id); throw error }
82
172
  }
83
173
  }
174
+
175
+ /** Selected JS adapters replace only their native counterparts. */
176
+ internal class CallbackHost(private val base: HostPal, private val id: String, private val support: String?,
177
+ private val callbacks: CoreCallbacks, private val handles: CoreHandles,
178
+ private val customBlobs: Boolean,
179
+ ) : HostPal by base {
180
+ override fun blobOperation(operation: String, key: String, cursor: String?, bytes: ByteArray?): PalBlobReply {
181
+ if (!customBlobs) return base.blobOperation(operation, key, cursor, bytes)
182
+ try {
183
+ val packet = mapOf("type" to "blob", "host" to id, "operation" to operation, "key" to key,
184
+ "cursor" to cursor, "bytes" to bytes?.map { it.toInt() and 255 })
185
+ val reply = JsonParser.parseString(callbacks.invoke(packet)).asJsonObject
186
+ reply.getAsJsonObject("error")?.let {
187
+ throw FfiException.Failure("storage_error", it.get("detail")?.asString ?: "")
188
+ }
189
+ val value = reply.getAsJsonObject("value") ?: error("Blob adapter unavailable")
190
+ val entries = if (operation == "list") value.getAsJsonArray("entries").map {
191
+ val entry = it.asJsonObject
192
+ PalBlobEntry(entry.get("key").asString, entry.get("size").asString.toULong())
193
+ } else emptyList()
194
+ val output = if (operation == "get" && !value.get("bytes").isJsonNull) {
195
+ value.getAsJsonArray("bytes").map {
196
+ val byte = it.asInt
197
+ require(byte in 0..255)
198
+ byte.toByte()
199
+ }.toByteArray()
200
+ } else null
201
+ return PalBlobReply(output, entries, value.get("nextCursor")?.takeUnless { it.isJsonNull }?.asString)
202
+ } catch (error: FfiException) { throw error }
203
+ catch (_: Exception) { throw FfiException.Failure("storage_error", "Invalid blob transport reply") }
204
+ }
205
+ override fun imageSupport() = support
206
+ override fun imageOperation(operation: String, bytes: ByteArray, optionsJson: String, cancel: CancelToken): PalImageReply {
207
+ val token = handles.hold(cancel)
208
+ cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { callbacks.post(mapOf("type" to "cancel", "token" to token)) } }))
209
+ try {
210
+ val reply = JsonParser.parseString(callbacks.invoke(mapOf("type" to "image", "host" to id, "operation" to operation,
211
+ "bytes" to bytes.map { it.toInt() and 255 }, "options" to JsonParser.parseString(optionsJson), "cancel" to token))).asJsonObject
212
+ reply.getAsJsonObject("error")?.let { throw CorePalException.Failure(it.get("code")?.asString ?: "image_unsupported", it.get("message")?.asString ?: "Image adapter failed") }
213
+ val value = reply.getAsJsonObject("value") ?: throw CorePalException.Failure("image_unsupported", "Image adapter is unavailable")
214
+ return PalImageReply(value.get("info")?.toString() ?: "{}", value.getAsJsonArray("bytes")?.map { it.asInt.toByte() }?.toByteArray() ?: byteArrayOf())
215
+ } finally { handles.forget(token) }
216
+ }
217
+ }
@@ -3,7 +3,9 @@ package dev.croche.reactnative
3
3
  import com.facebook.react.bridge.*
4
4
  import com.facebook.react.modules.core.DeviceEventManagerModule
5
5
  import com.google.gson.*
6
+ import dev.croche.SelectedAdapters
6
7
  import dev.croche.ffi.*
8
+ import dev.croche.s7.ensureNativeCoreInitialized
7
9
  import dev.croche.s7.nativePlatform
8
10
  import kotlinx.coroutines.*
9
11
 
@@ -11,8 +13,9 @@ import kotlinx.coroutines.*
11
13
  // KotlinHost/legacy engine, app defaults, second scheduler or second stream queue.
12
14
  class CrocheRuntimeModule(private val context: ReactApplicationContext) : NativeCrocheRuntimeSpec(context) {
13
15
  companion object { const val NAME = "CrocheRuntime" }
16
+ init { ensureNativeCoreInitialized() }
14
17
  private val worker = CoroutineScope(SupervisorJob() + Dispatchers.IO)
15
- private val pals by lazy { nativePlatform(context, null) }
18
+ private val pals by lazy { nativePlatform(context, SelectedAdapters()) }
16
19
  private fun host(): HostPal = rnHostPal(pals.host)
17
20
  private fun emit(name: String, packet: String) {
18
21
  check(context.hasActiveReactInstance()) { "JavaScript runtime unavailable" }
@@ -29,7 +32,7 @@ class CrocheRuntimeModule(private val context: ReactApplicationContext) : Native
29
32
  // Copy owned bytes on entry, before handing work to another thread.
30
33
  val bytes = (0 until images.size()).map { i ->
31
34
  val row = images.getMap(i)!!; val input = row.getArray("bytes")!!
32
- CoreImageInput(row.getDouble("element").toLong().toUInt(), ByteArray(input.size()) { input.getDouble(it).toInt().toByte() })
35
+ CoreAttachmentInput(row.getDouble("element").toLong().toUInt(), ByteArray(input.size()) { input.getDouble(it).toInt().toByte() })
33
36
  }
34
37
  worker.launch {
35
38
  try {
@@ -8,23 +8,40 @@ internal class NativePal(private val storage: CoreStoragePal, private val host:
8
8
  private val http = ConcurrentHashMap<String, CancelToken>()
9
9
  private val httpLock = Any()
10
10
  private val cancelledBeforeStart = mutableSetOf<String>()
11
- private fun JsonElement.bytes(): ByteArray = asJsonArray.map { it.asInt.toByte() }.toByteArray()
12
11
  private fun ByteArray.numbers() = map { it.toInt() and 255 }
13
12
  fun call(method: String, a: JsonArray): Any? = when (method) {
13
+ "listState" -> {
14
+ require(a.size() == 2)
15
+ val page = storage.listState(a.text(0), stateListOptions(a[1]))
16
+ mapOf("entries" to page.entries.map { mapOf("key" to it.key, "value" to it.value) }, "nextCursor" to page.nextCursor)
17
+ }
18
+ "commit" -> {
19
+ val guard = a[1].asJsonObject
20
+ val condition = CoreStateCondition(stateRequiredString(guard.get("key")), p1Nullable(guard.get("version")))
21
+ when (val result = storage.commitState(stateOps(a[0].asJsonArray), condition)) {
22
+ is CoreStateCommit.Committed -> mapOf("type" to "committed", "version" to result.version)
23
+ CoreStateCommit.Conflict -> mapOf("type" to "conflict")
24
+ }
25
+ }
26
+ "readVersioned" -> storage.readVersioned(p1Nullable(a.getOrNull(0)) ?: throw CoreStorageFailure.Failure("Missing storage key")).let { mapOf("value" to it.value, "version" to it.version) }
27
+ "writeIf" -> {
28
+ require(a.size() == 3)
29
+ when (val result = storage.writeIf(p1Nullable(a[0]) ?: throw CoreStorageFailure.Failure("Missing storage key"), p1Nullable(a[1]), p1Nullable(a[2]))) {
30
+ is CoreWriteOutcome.Written -> mapOf("type" to "written", "version" to result.version)
31
+ is CoreWriteOutcome.Conflict -> mapOf("type" to "conflict", "version" to result.version)
32
+ }
33
+ }
14
34
  "read" -> storage.read(a.text(0)); "write" -> storage.write(a.text(0), a.text(1)).let { null }
15
35
  "remove" -> storage.remove(a.text(0)).let { null }; "list" -> storage.list(a.text(0))
16
36
  "lock" -> if (storage.lock(a.text(0)) == PalLockOutcome.ACQUIRED) "acquired" else "held"
17
37
  "unlock" -> storage.unlock(a.text(0)).let { null }
18
38
  "readSecret" -> storage.readSecret(a.text(0)); "writeSecret" -> storage.writeSecret(a.text(0), a.text(1)).let { null }
19
39
  "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 } }
40
+ "purgeInstance" -> storage.purgeInstance(a.text(0), a.getOrNull(1)?.let(::p1Nullable)).let { null }
41
+ "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).filterValues { it != null } }
21
42
  "readAsset" -> host.readAsset(a.text(0))?.numbers()
22
43
  "resolve" -> host.resolve(a.text(0), CancelToken())
23
44
  "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
45
  "cancelHttp" -> {
29
46
  val id = a.text(0)
30
47
  val token = synchronized(httpLock) { http[id].also { if (it == null) cancelledBeforeStart.add(id) } }
@@ -5,11 +5,26 @@ import org.junit.Assert.*
5
5
  import org.junit.Test
6
6
 
7
7
  class AgentMemoryTest {
8
+ @Test fun decisionDispatchForwardsJsonOptionsAndTokenAndPreservesCoreError() {
9
+ val agent = MemoryAgentFake()
10
+ val bridge = CoreDispatch({ error("No new host") }, { error("No platform storage") }) { error("No event") }
11
+ val id = bridge.handles.hold(agent)
12
+ val cancel = CancelToken(NoHandle)
13
+ val token = bridge.handles.hold(cancel)
14
+ val input = """{"state":{"raw":[null,false,0]}}"""
15
+ val arguments = com.google.gson.JsonArray().apply { add(input); add(com.google.gson.JsonNull.INSTANCE); add(token) }
16
+ assertEquals("""{"id":"decision"}""", bridge.call(id, "decide", arguments))
17
+ assertEquals(listOf("decide" to listOf(input, null, cancel)), agent.calls)
18
+ assertSame(cancel, agent.calls.single().second[2])
19
+ agent.closed = true
20
+ try { bridge.call(id, "decide", arguments); fail("Core refusal") }
21
+ catch (error: CoreApiException.Failure) { assertEquals("closed", error.code); assertEquals("Agent is closed", error.detail) }
22
+ }
8
23
  @Test fun memoryIsTheS1AgentHandleAndErrorsPassThrough() {
9
24
  val agent = MemoryAgentFake()
10
25
  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
26
  val id = bridge.handles.hold(agent)
12
- assertEquals("[{\"id\":\"m1\"}]", bridge.call(id, "memoryList", args("[]")))
27
+ assertEquals("{\"items\":[{\"id\":\"m1\"}]}", bridge.call(id, "memoryList", args("[]")))
13
28
  assertNull(bridge.call(id, "memoryDelete", args("[\"m1\"]")))
14
29
  assertNull(bridge.call(id, "memoryClear", args("[]")))
15
30
  assertNull(bridge.call(id, "memoryEnabled", args("[true]")))
@@ -31,18 +46,25 @@ private class MemoryAgentFake : CoreAgentInterface {
31
46
  calls += name to args
32
47
  }
33
48
  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")
49
+ override fun `clearHistory`(`optionsJson`: kotlin.String?) = error("Unexpected clearHistory")
50
+ override fun `decide`(`inputJson`: kotlin.String, `optionsJson`: kotlin.String?, `cancel`: CancelToken?): kotlin.String {
51
+ record("decide", listOf(inputJson, optionsJson, cancel)); return """{"id":"decision"}"""
52
+ }
36
53
  override fun `id`(): kotlin.String = error("Unexpected id")
37
54
  override fun `instance`(): kotlin.String? = error("Unexpected instance")
55
+ override fun attachment(id: String): String = error("Unexpected image")
56
+ override fun listAttachments(optionsJson: String?): String = error("Unexpected listAttachments")
57
+ override fun copyAttachment(sourceJson: String): String = error("Unexpected copyAttachment")
58
+ override fun deleteAttachment(id: String): Unit = error("Unexpected deleteAttachment")
59
+ override fun releaseAttachment(id: String): Unit = error("Unexpected releaseAttachment")
38
60
  override fun `memoryClear`() { record("memoryClear") }
39
61
  override fun `memoryDelete`(`id`: kotlin.String) { record("memoryDelete", listOf(id)) }
40
62
  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")
63
+ override fun `memoryList`(`optionsJson`: kotlin.String?): kotlin.String { record("memoryList"); return "{\"items\":[{\"id\":\"m1\"}]}" }
64
+ override fun `request`(`inputJson`: kotlin.String, `images`: List<CoreAttachmentInput>, `optionsJson`: kotlin.String?, `cancel`: CancelToken?): kotlin.String = error("Unexpected request")
43
65
  override fun `resetTools`() = error("Unexpected resetTools")
44
66
  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")
67
+ override fun `send`(`inputJson`: kotlin.String, `images`: List<CoreAttachmentInput>, `optionsJson`: kotlin.String?, `cancel`: CancelToken?): kotlin.String = error("Unexpected send")
46
68
  override fun `setTools`(`scopeJson`: kotlin.String) = error("Unexpected setTools")
47
69
  override fun `setWiki`(`scopeJson`: kotlin.String) = error("Unexpected setWiki")
48
70
  override fun `shutdown`() = error("Unexpected shutdown")
@@ -25,14 +25,12 @@ private class BackgroundHostFake(
25
25
  private val calls: MutableList<String>,
26
26
  private val refusal: CorePalException.Failure,
27
27
  ) : HostPal {
28
+ override fun blobOperation(operation: String, key: String, cursor: String?, bytes: ByteArray?): PalBlobReply = error("Unexpected blob operation")
28
29
  override fun `streamPlatform`(): HostStreamPlatform = error("Unexpected streamPlatform")
29
- override fun `imageCodecAvailable`(): kotlin.Boolean = error("Unexpected imageCodecAvailable")
30
+ override fun imageSupport(): String? = error("Unexpected imageSupport")
31
+ override fun imageOperation(operation: String, bytes: ByteArray, optionsJson: String, cancel: CancelToken): PalImageReply = error("Unexpected imageOperation")
30
32
  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
33
  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
34
  override fun `http`(`request`: PalHttpRequest, `sink`: HttpSink, `cancel`: CancelToken) = error("Unexpected http")
37
35
  override fun `resolve`(`host`: kotlin.String, `cancel`: CancelToken): List<kotlin.String> = error("Unexpected resolve")
38
36
  override fun `platformFacts`(): PalPlatformFacts = error("Unexpected platformFacts")
@@ -43,6 +41,7 @@ private class BackgroundHostFake(
43
41
  override fun `readSecret`(`key`: kotlin.String): kotlin.String? = error("Unexpected readSecret")
44
42
  override fun `writeSecret`(`key`: kotlin.String, `value`: kotlin.String) = error("Unexpected writeSecret")
45
43
  override fun `remove`(`key`: kotlin.String) = error("Unexpected remove")
44
+ override fun purgeInstance(prefix: String) = error("Unexpected purgeInstance")
46
45
  override fun `removeSecret`(`key`: kotlin.String) = error("Unexpected removeSecret")
47
46
  override fun `lock`(`key`: kotlin.String): PalLockOutcome = error("Unexpected lock")
48
47
  override fun `unlock`(`key`: kotlin.String) = error("Unexpected unlock")
@@ -62,10 +61,4 @@ private class BackgroundHostFake(
62
61
  assertEquals("from-core", identifier); assertSame(expectedWake, wake)
63
62
  throw refusal
64
63
  }
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
64
  }
@@ -0,0 +1,107 @@
1
+ package dev.croche.reactnative
2
+
3
+ import dev.croche.s7.pal.BlobFiles
4
+ import dev.croche.ffi.FfiException
5
+ import java.io.File
6
+ import java.nio.file.Files
7
+ import org.junit.Assert.assertArrayEquals
8
+ import org.junit.Assert.assertEquals
9
+ import org.junit.Assert.assertFalse
10
+ import org.junit.Assert.assertNotNull
11
+ import org.junit.Assert.assertNull
12
+ import org.junit.Assert.assertThrows
13
+ import org.junit.Assert.assertTrue
14
+ import org.junit.Rule
15
+ import org.junit.Test
16
+ import org.junit.rules.TemporaryFolder
17
+
18
+ class BlobFilesTest {
19
+ @get:Rule val temp = TemporaryFolder()
20
+
21
+ @Test fun blobFailureRetainsTheLocalCause() {
22
+ val store = BlobFiles(temp.newFolder()) {}
23
+ val failure = assertThrows(FfiException.Failure::class.java) {
24
+ store.operation("get", "../invalid", null, null)
25
+ }
26
+ assertEquals("storage_error", failure.code)
27
+ assertEquals("Blob operation failed", failure.detail)
28
+ assertTrue(failure.cause is IllegalArgumentException)
29
+ }
30
+
31
+ @Test fun rawObjectsReopenAndPageWithinTheirPrefix() {
32
+ val directory = temp.newFolder()
33
+ val store = BlobFiles(directory) {}
34
+ val prefix = "project/user/agent/~default/files/"
35
+ val other = "project/user/agent/named/files/other"
36
+ val data = byteArrayOf(0, -1, -128, 11)
37
+ val keys = (0..1000).map { prefix + it.toString().padStart(4, '0') }
38
+ val first = keys.first()
39
+ assertNull(store.get(first))
40
+ store.put(other, data)
41
+ store.put(first, data)
42
+ assertArrayEquals(data, File(directory, "blobs/$first/object").readBytes())
43
+ for (key in keys.drop(1).asReversed()) store.put(key, byteArrayOf(1))
44
+
45
+ val reopened = BlobFiles(directory) {}
46
+ assertArrayEquals(data, reopened.get(first))
47
+ assertEquals(listOf(BlobFiles.Entry(first, data.size.toLong())), reopened.list(first, null).entries)
48
+ val page = reopened.list(prefix, null)
49
+ assertEquals(keys.take(1000), page.entries.map { it.key })
50
+ assertNotNull(page.nextCursor)
51
+ val tail = reopened.list(prefix, page.nextCursor)
52
+ assertEquals(listOf(BlobFiles.Entry(keys.last(), 1)), tail.entries)
53
+ assertNull(tail.nextCursor)
54
+
55
+ reopened.delete(first)
56
+ reopened.delete(first)
57
+ assertNull(reopened.get(first))
58
+ assertTrue(reopened.list(first, null).entries.isEmpty())
59
+ keys.drop(1).forEach(reopened::delete)
60
+
61
+ val staged = File(directory, "blobs/${prefix}unpublished/.tmp-crash")
62
+ Files.createDirectories(staged.parentFile.toPath())
63
+ staged.writeBytes(data)
64
+ reopened.purgeStaging(prefix)
65
+ assertTrue(!staged.exists())
66
+ assertTrue(File(directory, "blobs/$prefix").isDirectory)
67
+ assertTrue(reopened.list(prefix, null).entries.isEmpty())
68
+ assertArrayEquals(data, reopened.get(other))
69
+ }
70
+
71
+ @Test fun stagingPurgeRemovesOnlyRegularCrashFiles() {
72
+ val directory = temp.newFolder()
73
+ val store = BlobFiles(directory) {}
74
+ val key = "owner/files/record/live"
75
+ val owner = File(directory, "blobs/owner/files")
76
+ val staged = File(owner, "record/live/.tmp-crash")
77
+ val unrelated = File(owner, "notes")
78
+ val foreign = File(owner, "!foreign/.tmp-foreign")
79
+ val outside = temp.newFolder()
80
+ val target = File(outside, ".tmp-target")
81
+ val sibling = File(directory, "blobs/sibling/.tmp-sibling")
82
+ val bytes = byteArrayOf(0, -1, -128)
83
+ store.put(key, bytes)
84
+ Files.createDirectory(foreign.parentFile.toPath())
85
+ Files.createDirectory(sibling.parentFile.toPath())
86
+ for (path in listOf(staged, unrelated, foreign, target, sibling)) path.writeBytes(bytes)
87
+ val link = File(owner, ".tmp-link").toPath()
88
+ val linkedDir = File(owner, "linked").toPath()
89
+ val linksSupported = File.separatorChar != '\\'
90
+ if (linksSupported) {
91
+ Files.createSymbolicLink(link, target.toPath())
92
+ Files.createSymbolicLink(linkedDir, outside.toPath())
93
+ }
94
+
95
+ store.purgeStaging("owner/files/")
96
+ assertArrayEquals("unrelated file survives", bytes, unrelated.readBytes())
97
+ assertArrayEquals(bytes, store.get(key))
98
+ assertFalse("selected temp disappears", staged.exists())
99
+ assertArrayEquals(bytes, foreign.readBytes())
100
+ assertArrayEquals(bytes, sibling.readBytes())
101
+ assertArrayEquals(bytes, target.readBytes())
102
+ if (linksSupported) {
103
+ assertEquals(target.toPath(), Files.readSymbolicLink(link))
104
+ assertEquals(outside.toPath(), Files.readSymbolicLink(linkedDir))
105
+ }
106
+ }
107
+ }