@h1r-ai/croche-react-native 0.5.5 → 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 (248) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +90 -451
  3. package/THIRD-PARTY-NOTICES +906 -14
  4. package/android/build.gradle +6 -1
  5. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
  6. package/android/src/main/AndroidManifest.xml +0 -5
  7. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
  8. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
  9. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
  10. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
  11. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  12. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
  13. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
  14. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  15. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  16. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -0
  17. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  18. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  19. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  20. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  21. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  22. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  33. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  34. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
  35. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  36. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  37. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  38. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  39. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
  40. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  82. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  83. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
  84. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  85. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  86. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
  87. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  88. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  89. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  90. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  91. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
  92. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  93. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  94. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  95. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  96. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  97. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  98. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  99. package/croche-react-native.podspec +1 -0
  100. package/dist/package.json +1 -0
  101. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  102. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  103. package/dist/react-native/src/core-native.d.ts +6 -0
  104. package/dist/react-native/src/core-native.js +316 -0
  105. package/dist/react-native/src/core-wire.d.ts +55 -0
  106. package/dist/react-native/src/core-wire.js +1 -0
  107. package/dist/react-native/src/native-module.d.ts +8 -0
  108. package/dist/react-native/src/native-module.js +53 -0
  109. package/dist/rn-shared-build.json +16 -0
  110. package/dist/runtime/src/adapters.d.ts +8 -0
  111. package/dist/runtime/src/adapters.js +29 -0
  112. package/dist/runtime/src/agent.d.ts +91 -0
  113. package/dist/runtime/src/agent.js +137 -0
  114. package/dist/runtime/src/app-api.d.ts +572 -0
  115. package/dist/runtime/src/app-api.js +1 -0
  116. package/dist/runtime/src/cancel.d.ts +9 -0
  117. package/dist/runtime/src/cancel.js +27 -0
  118. package/dist/runtime/src/core/foreground.d.ts +3 -0
  119. package/dist/runtime/src/core/foreground.js +40 -0
  120. package/dist/runtime/src/core/port.d.ts +247 -0
  121. package/dist/runtime/src/core/port.js +1 -0
  122. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  123. package/dist/runtime/src/core/wasm-owner.js +237 -0
  124. package/dist/runtime/src/core/wasm.d.ts +1 -0
  125. package/dist/runtime/src/core/wasm.js +2 -0
  126. package/dist/runtime/src/croche.d.ts +97 -0
  127. package/dist/runtime/src/croche.js +172 -0
  128. package/dist/runtime/src/errors.d.ts +33 -0
  129. package/dist/runtime/src/errors.js +63 -0
  130. package/dist/runtime/src/events.d.ts +5 -0
  131. package/dist/runtime/src/events.js +31 -0
  132. package/dist/runtime/src/generated/app-stream.d.ts +328 -0
  133. package/dist/runtime/src/generated/app-stream.js +127 -0
  134. package/dist/runtime/src/image-input.d.ts +5 -0
  135. package/dist/runtime/src/image-input.js +60 -0
  136. package/dist/runtime/src/index.d.ts +6 -0
  137. package/dist/runtime/src/index.js +5 -0
  138. package/dist/runtime/src/index.native.d.ts +1 -0
  139. package/dist/runtime/src/index.native.js +2 -0
  140. package/dist/runtime/src/json.d.ts +13 -0
  141. package/dist/runtime/src/json.js +120 -0
  142. package/dist/runtime/src/native-adapter.d.ts +3 -0
  143. package/dist/runtime/src/native-adapter.js +30 -0
  144. package/dist/runtime/src/pal/host.d.ts +5 -0
  145. package/dist/runtime/src/pal/host.js +60 -0
  146. package/dist/runtime/src/pal/platform.d.ts +21 -0
  147. package/dist/runtime/src/pal/platform.js +7 -0
  148. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  149. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  150. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  151. package/dist/runtime/src/pal/state-store.js +1 -0
  152. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  153. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  154. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  155. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  156. package/dist/runtime/src/rn-entry.d.ts +1 -0
  157. package/dist/runtime/src/rn-entry.js +4 -0
  158. package/dist/runtime/src/run-tool.d.ts +33 -0
  159. package/dist/runtime/src/run-tool.js +7 -0
  160. package/dist/runtime/src/tools.d.ts +35 -0
  161. package/dist/runtime/src/tools.js +94 -0
  162. package/ios/CoreAgentTransport.swift +14 -0
  163. package/ios/CoreDeliveryTransport.swift +58 -0
  164. package/ios/CoreNativePal.swift +98 -0
  165. package/ios/CorePlatformTransport.swift +44 -0
  166. package/ios/CoreWireDispatch.swift +122 -0
  167. package/ios/CoreWireSupport.swift +286 -0
  168. package/ios/CrocheRuntimeBridge.swift +34 -994
  169. package/ios/ProjectPal.swift +49 -0
  170. package/ios/RNCrocheRuntime.mm +18 -201
  171. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  172. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  173. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
  174. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  175. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  176. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  177. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
  178. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
  179. package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
  180. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  181. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  182. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  183. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
  184. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  185. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
  186. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
  187. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
  188. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
  189. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  190. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
  191. package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
  192. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
  193. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  194. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  195. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
  196. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  197. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  198. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
  199. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
  200. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  201. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
  202. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  203. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
  204. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
  205. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
  206. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
  207. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
  208. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  209. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  210. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  211. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
  212. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
  213. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  214. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
  215. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
  216. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  217. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +899 -608
  218. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  219. package/package.json +18 -8
  220. package/scripts/README.md +11 -0
  221. package/scripts/build-shared.mjs +46 -0
  222. package/scripts/build.mjs +11 -0
  223. package/scripts/check-swift-vendor-modules.sh +15 -0
  224. package/scripts/vendor-native.sh +8 -6
  225. package/src/NativeCrocheRuntime.ts +12 -159
  226. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  227. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  228. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  229. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  230. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  231. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
  232. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  233. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
  234. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  235. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  236. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  237. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  238. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  239. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
  240. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  241. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  242. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
  243. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
  244. package/src/index.ts +0 -664
  245. package/src/project-types.ts +0 -35
  246. package/src/project.ts +0 -434
  247. package/src/protocol.ts +0 -28
  248. package/src/types.ts +0 -9
@@ -17,7 +17,10 @@ apply plugin: "com.facebook.react"
17
17
  android {
18
18
  namespace "dev.croche.reactnative"
19
19
  compileSdk 35
20
- defaultConfig { minSdk 26; consumerProguardFiles "vendor/CrocheRuntimeSDK/consumer-rules.pro" }
20
+ defaultConfig {
21
+ minSdk 26; consumerProguardFiles "vendor/CrocheRuntimeSDK/consumer-rules.pro"
22
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
23
+ }
21
24
  sourceSets {
22
25
  main {
23
26
  java.srcDirs += ["src/main/java", "vendor/CrocheRuntimeSDK/core", "vendor/CrocheRuntimeSDK/android"]
@@ -38,6 +41,8 @@ dependencies {
38
41
  implementation "com.google.android.play:integrity:1.4.0"
39
42
  implementation "androidx.work:work-runtime:2.10.1"
40
43
  testImplementation "junit:junit:4.13.2"
44
+ androidTestImplementation "androidx.test.ext:junit:1.2.1"
45
+ androidTestImplementation "androidx.test:runner:1.6.2"
41
46
  }
42
47
 
43
48
  react {
@@ -0,0 +1,126 @@
1
+ package dev.croche.reactnative
2
+
3
+ import androidx.test.ext.junit.runners.AndroidJUnit4
4
+ import androidx.test.platform.app.InstrumentationRegistry
5
+ import com.google.gson.JsonArray
6
+ import com.google.gson.JsonParser
7
+ import dev.croche.SelectedAdapters
8
+ import dev.croche.ffi.*
9
+ import dev.croche.s7.CoreFactoryCalls
10
+ import dev.croche.s7.attached
11
+ import dev.croche.s7.nativePlatform
12
+ import java.io.File
13
+ import java.net.URI
14
+ import java.util.UUID
15
+ import java.util.concurrent.CopyOnWriteArrayList
16
+ import java.util.concurrent.CountDownLatch
17
+ import java.util.concurrent.TimeUnit
18
+ import kotlinx.coroutines.Dispatchers
19
+ import kotlinx.coroutines.runBlocking
20
+ import kotlinx.coroutines.withContext
21
+ import org.junit.Assert.*
22
+ import org.junit.Test
23
+ import org.junit.runner.RunWith
24
+
25
+ private const val CONFIG = """{"schema":7,"project":{"defaults":{"model":"google/gemini-3.8-flash"},
26
+ "languages":{"default":"en","supported":["en"]}},"agents":{"helper":{"instructions":"Reply briefly."}}}"""
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"]}}"""
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":{}}"""
29
+ private fun frame(delta: String, finish: String = "null", usage: String = "") =
30
+ "data: {\"id\":\"gen-local\",\"model\":\"google/gemini-3.8-flash\",\"choices\":[{\"index\":0,\"delta\":$delta,\"finish_reason\":$finish}]$usage}\n\n"
31
+ private const val USAGE = ",\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":3,\"total_tokens\":13,\"cost\":0}"
32
+ private fun runs(command: String) = listOf(
33
+ frame("""{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"run_tool","arguments":"{\"cmd\":\"$command\"}"}}]}"""),
34
+ frame("{}", "\"tool_calls\"", USAGE), "data: [DONE]\n\n")
35
+ private val REPLY = listOf(frame("""{"role":"assistant","content":"Done."}"""), frame("{}", "\"stop\"", USAGE), "data: [DONE]\n\n")
36
+
37
+ /** Real asset path underneath; HTTP is answered in-process, never sent. The next model call runs `command`. */
38
+ private class WikiFakeHost(base: HostPal) : HostPal by base {
39
+ private val assets = base
40
+ val reads = CopyOnWriteArrayList<String>()
41
+ val bodies = CopyOnWriteArrayList<String>()
42
+ @Volatile var command: String? = null
43
+ override fun readAsset(path: String): ByteArray? { reads += path; return assets.readAsset(path) }
44
+ override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) {
45
+ val path = URI(request.url).path
46
+ if (path.endsWith("/chat/completions")) {
47
+ bodies += request.body ?: ""
48
+ val next = command; command = null
49
+ sink.head(200u, listOf(PalHeader("content-type", "text/event-stream")))
50
+ for (line in next?.let(::runs) ?: REPLY) if (!sink.chunk(line.toByteArray())) return
51
+ return
52
+ }
53
+ val body = when {
54
+ path.endsWith("/challenge") -> """{"challenge":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","attestation":"off"}"""
55
+ path.endsWith("/register") -> REGISTER
56
+ path.endsWith("/sync") -> SYNC
57
+ path.endsWith("/batch") -> {
58
+ val events = JsonParser.parseString(request.body ?: "{}").asJsonObject
59
+ .getAsJsonObject("payload")?.getAsJsonArray("events")
60
+ val accepted = events?.map { row ->
61
+ val o = row.asJsonObject; val p = o.getAsJsonObject("payload")
62
+ (p?.get("operation_id") ?: p?.get("adjustment_id") ?: o.get("message_id")).toString()
63
+ } ?: emptyList()
64
+ """{"accepted":[${accepted.joinToString(",")}],"duplicate":[],"rejected":[]}"""
65
+ }
66
+ else -> throw CorePalException.Failure("network_error", "Refused unplanned request $path")
67
+ }
68
+ sink.head(200u, listOf(PalHeader("content-type", "application/json")))
69
+ sink.chunk(body.toByteArray())
70
+ }
71
+ }
72
+
73
+ /**
74
+ * A `{path, description, file}` document through RN Android's host (rnHostPal over the S7 AndroidCoreHost,
75
+ * the module's real pair) and its dispatch, with the real native Core. Storage is the platform store: the
76
+ * JS callback storage has no JS here and is not under test.
77
+ */
78
+ @RunWith(AndroidJUnit4::class)
79
+ class WikiFileBridgeTest {
80
+ @Test fun aFileIsListedAtOpenReadOnFirstModelAccessAndMissingFailsOnRead() = runBlocking {
81
+ val file = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "wiki-${UUID.randomUUID()}.md")
82
+ val absent = File(file.parentFile, "absent-${UUID.randomUUID()}.md").toURI().toString()
83
+ file.writeText("Written before open.")
84
+ val uri = file.toURI().toString()
85
+ val pals = nativePlatform(InstrumentationRegistry.getInstrumentation().targetContext, SelectedAdapters())
86
+ val host = WikiFakeHost(rnHostPal(pals.host))
87
+ val dispatch = CoreDispatch({ host }, { pals.storage },
88
+ openFactory = { json, registrations, _, actual, recoveryJson -> CoreFactoryCalls.open(json, registrations, pals.storage, actual, recoveryJson = recoveryJson) },
89
+ emit = { })
90
+ val options = """{"projectKey":"pk_wiki_file_fixture","user":"${UUID.randomUUID()}","bundledConfig":$CONFIG,"wiki":[
91
+ {"path":"policy.md","description":"Refund policy","file":"$uri"},{"path":"absent.md","description":"Gone","file":"$absent"}]}"""
92
+ val root = withContext(Dispatchers.IO) { dispatch.open(JsonArray().apply { add(options); add(JsonArray()); add("storage"); add("host") }) }
93
+ try {
94
+ val listed = JsonParser.parseString(dispatch.call(root, "wikiList", JsonArray()) as String).asJsonObject.getAsJsonArray("items").asJsonArray
95
+ assertEquals(setOf("policy.md", "absent.md"), listed.map { it.asJsonObject.get("path").asString }.toSet())
96
+ assertEquals(emptyList<String>(), host.reads.toList())
97
+ file.writeText("Written after open.")
98
+ val handle = dispatch.call(root, "agent", JsonArray().apply { add("helper"); add(com.google.gson.JsonNull.INSTANCE) }) as String
99
+ val agent: CoreAgent = dispatch.handles.get(handle)
100
+ val codes = CopyOnWriteArrayList<String>(); val failed = CountDownLatch(1)
101
+ val subscription = agent.subscribe("""{"initialMessages":0}""", attached(object : CoreEventSink {
102
+ override fun deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) {
103
+ val event = JsonParser.parseString(eventJson).asJsonObject
104
+ if (event.get("type")?.asString == "input") event.getAsJsonObject("error")?.get("code")?.asString?.let { codes += it; failed.countDown() }
105
+ // As the SDK's own sink: enter the delivery, then complete it, off Core's delivery call.
106
+ Thread { if (delivery.tryEnter()) delivery.complete("""{"outcome":"returned"}""") }.start()
107
+ }
108
+ }))
109
+ suspend fun read(path: String) = withContext(Dispatchers.IO) {
110
+ host.command = "wiki read $path"
111
+ agent.request("""{"id":"${UUID.randomUUID()}","input":[{"type":"text","text":"Read it"}]}""", emptyList(), null, null)
112
+ }
113
+ read("policy.md")
114
+ assertEquals(listOf(uri), host.reads.toList())
115
+ assertTrue(host.bodies.first().contains("Refund policy"))
116
+ assertTrue(host.bodies.last(), host.bodies.last().contains("Written after open."))
117
+ assertFalse(host.bodies.last(), host.bodies.last().contains("Written before open."))
118
+ assertEquals(emptyList<String>(), codes.toList())
119
+ read("absent.md")
120
+ assertTrue("no failed input event", failed.await(10, TimeUnit.SECONDS))
121
+ assertEquals(listOf("invalid_wiki"), codes.toList())
122
+ assertEquals(absent, host.reads.last())
123
+ subscription.shutdown()
124
+ } finally { dispatch.call(root, "shutdown", JsonArray()); file.delete() }
125
+ }
126
+ }
@@ -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>
@@ -0,0 +1,106 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.*
4
+ import dev.croche.BindingFacts
5
+ import dev.croche.ffi.*
6
+ import dev.croche.s7.CoreFactoryCalls
7
+ import dev.croche.s7.attached
8
+
9
+ internal class CoreDispatch(
10
+ private val host: () -> HostPal,
11
+ private val platformStorage: () -> CoreStoragePal,
12
+ private val openFactory: suspend (String, List<CoreToolRegistration>, CoreStoragePal, HostPal, String?) -> CoreCroche =
13
+ { json, registrations, storage, host, recovery -> CoreFactoryCalls.open(json, registrations, storage, host, rnBindingFacts, recovery) },
14
+ emit: (String) -> Unit,
15
+ ) {
16
+ val handles = CoreHandles()
17
+ val callbacks = CoreCallbacks(emit)
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)
22
+ suspend fun open(a: JsonArray): String {
23
+ val registrations = a[1].asJsonArray.map {
24
+ val row = it.asJsonObject
25
+ CoreToolRegistration(handles.get(row.get("tool").asString), row.get("optionsJson")?.asString)
26
+ }
27
+ return handles.hold(openFactory(a.text(0), registrations, storage(a), selectedHost(a, 5), a.optional(4)))
28
+ }
29
+ fun call(id: String, method: String, a: JsonArray, images: List<CoreAttachmentInput> = emptyList()): Any? {
30
+ if (method == "release") { handles.forget(id); return null }
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
+ }
36
+ "newCancel" -> handles.hold(CancelToken())
37
+ "defineTool" -> handles.hold(CoreToolDefinition(a.text(0), attached(NativeExecute(a.text(1), callbacks, handles))))
38
+ "webSearch" -> handles.hold(coreWebSearch())
39
+ "image" -> handles.hold(coreImage())
40
+ "wakeTimes" -> coreWakeTimes(a.text(0), a.optional(1), attached(storage(a)), attached(selectedHost(a, 4)))
41
+ // The same CoreEventSink/CoreDelivery protocol as subscribe; no fake ack.
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
+ }
48
+ else -> error("Unknown native module method")
49
+ }
50
+ val owner = handles.value(id)
51
+ if (owner is CancelToken) return when (method) { "cancel" -> owner.cancel().let { null }; "isCancelled" -> owner.isCancelled(); else -> error("Unknown cancel method") }
52
+ if (owner is CoreDelivery) return when (method) {
53
+ "tryEnter" -> owner.tryEnter().also { if (!it) handles.forget(id) }
54
+ "complete" -> owner.complete(a.text(0)).also { handles.forget(id) }.let { null }
55
+ else -> error("Unknown delivery method")
56
+ }
57
+ if (owner is CoreAttachmentReader) { check(method == "attachment"); return owner.attachment(a.text(0)) }
58
+ if (owner is CoreToolDefinition) { check(method == "name"); return owner.name() }
59
+ if (owner is CoreCroche) return when (method) {
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()
66
+ "agent" -> handles.hold(owner.agent(a.text(0), a.optional(1)))
67
+ "deleteData" -> owner.deleteData(a.optional(0)).let { null }
68
+ "deliverDue" -> owner.deliverDue(a.optional(0), handles.get(a.text(1)))
69
+ "wikiList" -> owner.wikiList(a.optional(0))
70
+ "wikiPut" -> owner.wikiPut(a.text(0)).let { null }
71
+ "wikiRemove" -> owner.wikiRemove(a.text(0)).let { null }
72
+ "debugAttach" -> owner.debugAttach(a.text(0))
73
+ "debugDetach" -> owner.debugDetach().let { null }
74
+ "shutdown" -> owner.shutdown().let { null }
75
+ else -> error("Unknown project method")
76
+ }
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
+
84
+ "id" -> owner.id(); "instance" -> owner.instance()
85
+ "decide" -> owner.decide(a.text(0), a.optional(1), handles.get(a.text(2)))
86
+ "send" -> owner.send(a.text(0), images, a.optional(1), handles.get(a.text(2)))
87
+ "request" -> owner.request(a.text(0), images, a.optional(1), handles.get(a.text(2)))
88
+ "subscribe" -> handles.hold(owner.subscribe(a.text(0), attached(NativeSink(a.text(1), callbacks, handles))))
89
+ "cancel" -> owner.cancel(a.optional(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 }
92
+ "memoryClear" -> owner.memoryClear().let { null }; "memoryEnabled" -> owner.memoryEnabled(a[0].asBoolean).let { null }
93
+ "setTools" -> owner.setTools(a.text(0)).let { null }; "resetTools" -> owner.resetTools().let { null }
94
+ "setWiki" -> owner.setWiki(a.text(0)).let { null }; "resetWiki" -> owner.resetWiki().let { null }
95
+ "shutdown" -> owner.shutdown().let { null }; else -> error("Unknown agent method")
96
+ }
97
+ if (owner is CoreSubscription) return when (method) {
98
+ "history" -> owner.history(a.text(0)).let { null }; "ended" -> owner.ended(); "shutdown" -> owner.shutdown().let { null }
99
+ else -> error("Unknown subscription method")
100
+ }
101
+ error("Unknown native handle type")
102
+ }
103
+ }
104
+
105
+ /** The bridge's own binding facts: sdk "react-native" (BindingFacts, from the SDK sources it builds). */
106
+ internal val rnBindingFacts: String = BindingFacts.json("react-native")
@@ -0,0 +1,217 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.*
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
9
+ import dev.croche.s7.attached
10
+ import java.util.UUID
11
+ import java.util.concurrent.ConcurrentHashMap
12
+ import java.util.concurrent.CountDownLatch
13
+
14
+ // Required nullable storage fields must remain present on the wire.
15
+ internal val rnGson = GsonBuilder().serializeNulls().create()
16
+ internal fun json(value: Any?): String = rnGson.toJson(value)
17
+ internal fun args(text: String): JsonArray = JsonParser.parseString(text).asJsonArray
18
+ internal fun JsonArray.text(i: Int): String = get(i).asString
19
+ internal fun JsonArray.optional(i: Int): String? = if (size() > i && !get(i).isJsonNull) get(i).asString else null
20
+
21
+ // Opaque FFI references only, never an SDK project/agent registry.
22
+ internal class CoreHandles {
23
+ private val handles = ConcurrentHashMap<String, Any>()
24
+ fun hold(value: Any): String = UUID.randomUUID().toString().also { handles[it] = value }
25
+ inline fun <reified T> get(id: String): T = value(id) as T
26
+ fun value(id: String): Any = handles[id] ?: error("Unknown native transport handle")
27
+ fun forget(id: String) { (handles.remove(id) as? Disposable)?.destroy() }
28
+ fun clear() { handles.clear() }
29
+ }
30
+ internal class CoreCallbacks(private val emit: (String) -> Unit) {
31
+ private class Reply { val done = CountDownLatch(1); @Volatile var json: String? = null }
32
+ private val pending = ConcurrentHashMap<String, Reply>()
33
+ @Volatile private var alive = true
34
+ fun post(packet: Map<String, Any?>) { check(alive); emit(json(packet)) }
35
+ fun invoke(packet: Map<String, Any?>): String {
36
+ val id = UUID.randomUUID().toString(); val reply = Reply(); pending[id] = reply
37
+ try {
38
+ check(alive); post(packet + ("call" to id)); reply.done.await()
39
+ return reply.json ?: error("JavaScript callback unavailable")
40
+ } finally { pending.remove(id) }
41
+ }
42
+ fun reply(id: String, text: String) { pending[id]?.let { it.json = text; it.done.countDown() } }
43
+ fun invalidate() { alive = false; pending.values.forEach { it.done.countDown() } }
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
+
97
+ internal class CallbackStorage(private val id: String, private val host: String, private val callbacks: CoreCallbacks) : CoreStoragePal {
98
+ private fun call(method: String, vararg arguments: Any?): JsonElement = try {
99
+ val result = JsonParser.parseString(callbacks.invoke(mapOf("type" to "storage", "storage" to id, "method" to method, "args" to arguments))).asJsonObject
100
+ if (result.has("error")) throw CoreStorageFailure.Failure(result.getAsJsonObject("error").get("detail").asString)
101
+ result.get("value") ?: error("Missing storage reply")
102
+ } catch (error: CoreStorageFailure) { throw error }
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
+ }
135
+ override fun read(key: String) = call("read", key).let { if (it.isJsonNull) null else it.asString }
136
+ override fun write(key: String, value: String) { call("write", key, value) }
137
+ override fun remove(key: String) { call("remove", key) }
138
+ override fun purgeInstance(prefix: String, secretKey: String?) { call("purgeInstance", prefix, secretKey) }
139
+ override fun list(prefix: String) = call("list", prefix).asJsonArray.map { it.asString }
140
+ override fun lock(name: String) = when (call("lock", name).asString) {
141
+ "acquired" -> PalLockOutcome.ACQUIRED; "held" -> PalLockOutcome.HELD
142
+ else -> throw CoreStorageFailure.Failure("Invalid lock transport reply")
143
+ }
144
+ override fun unlock(name: String) { call("unlock", name) }
145
+ override fun readSecret(key: String) = call("readSecret", key).let { if (it.isJsonNull) null else it.asString }
146
+ override fun writeSecret(key: String, value: String) { call("writeSecret", key, value) }
147
+ override fun removeSecret(key: String) { call("removeSecret", key) }
148
+ // Like the UniFFI handle cleaner: retirement follows the native callback's
149
+ // lifetime, not bounded public close or an SDK timeout.
150
+ @Suppress("deprecation")
151
+ protected fun finalize() { runCatching { callbacks.post(mapOf("type" to "retired", "storages" to listOf(id), "hosts" to listOf(host), "sinks" to emptyList<String>(), "executors" to emptyList<String>(), "tokens" to emptyList<String>())) } }
152
+ }
153
+ internal class NativeExecute(private val execute: String, private val callbacks: CoreCallbacks, private val handles: CoreHandles) : CoreToolExecute {
154
+ @Suppress("deprecation")
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>())) } }
156
+ override fun execute(callJson: String, contextJson: String, cancel: CancelToken, attachments: CoreAttachmentReader): String {
157
+ val token = handles.hold(cancel)
158
+ val reader = handles.hold(attachments)
159
+ cancel.onCancel(attached(object : CancelCallback { override fun cancelled() { callbacks.post(mapOf("type" to "cancel", "token" to token)) } }))
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\"}" }
162
+ finally { handles.forget(token) }
163
+ }
164
+ }
165
+ internal class NativeSink(private val sink: String, private val callbacks: CoreCallbacks, private val handles: CoreHandles) : CoreEventSink {
166
+ @Suppress("deprecation")
167
+ protected fun finalize() { runCatching { callbacks.post(mapOf("type" to "retired", "sinks" to listOf(sink), "hosts" to emptyList<String>(), "storages" to emptyList<String>(), "executors" to emptyList<String>(), "tokens" to emptyList<String>())) } }
168
+ override fun deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) {
169
+ val id = handles.hold(delivery)
170
+ try { callbacks.post(mapOf("type" to "event", "sink" to sink, "id" to deliveryId, "eventJson" to eventJson, "delivery" to id)) }
171
+ catch (error: Throwable) { delivery.complete("{\"outcome\":\"unavailable\"}"); handles.forget(id); throw error }
172
+ }
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
+ }