@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
@@ -0,0 +1,100 @@
1
+ #if CROCHE_TEST_HOOKS
2
+ import Foundation
3
+
4
+ // TEST-HOOKS BUILDS ONLY (CROCHE_SWIFT_TEST_HOOKS=1, Atlas's shared recipe): the private
5
+ // `openForTests` entry with a fixture Cloud origin. Never compiled into a release; the release
6
+ // bindings have no `openForTests`.
7
+
8
+ /// While a test sets `serve`, `Croche.open` opens through `openForTests` with the fixture origin,
9
+ /// and every HTTP effect is answered in-process by `serve`. No request leaves the process.
10
+ enum FixtureCloud {
11
+ /// The origin Core is given. Nothing listens there: the host answers in-process.
12
+ static let origin = "http://127.0.0.1:9"
13
+ /// Hosts the fixture may name besides the origin (its registration's gateway).
14
+ static let gatewayHosts: Set<String> = ["gateway.example"]
15
+ nonisolated(unsafe) static var serve: RuntimeHTTP?
16
+ /// Image bytes by URL, served to a pinned fetch where the platform dials pins (macOS).
17
+ nonisolated(unsafe) static var images: [String: Data] = [:]
18
+ /// `(url, connectTo)` of every image fetch served, so a test can assert the pin.
19
+ nonisolated(unsafe) static var pinned: [(url: String, pin: String?)] = []
20
+ /// URLs refused because they were outside the fixture: a test asserts this stays empty.
21
+ nonisolated(unsafe) static var refused: [String] = []
22
+ static let lock = NSLock()
23
+ }
24
+
25
+ /// The platform PAL with HTTP and DNS answered by the fixture; everything else is the real PAL.
26
+ final class FixtureHost: HostPal, @unchecked Sendable {
27
+ let base: PlatformPal
28
+ private let serve: RuntimeHTTP
29
+ init(base: PlatformPal, serve: @escaping RuntimeHTTP) { self.base = base; self.serve = serve }
30
+
31
+ func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws {
32
+ // The platform's own pin rule first (iOS: a named pin is capability_unsupported).
33
+ if request.connectTo != nil && !PlatformHTTP.dialsNamedPins { try effect { try PlatformHTTP.check(request) } }
34
+ if let image = FixtureCloud.lock.withLock({ FixtureCloud.images[request.url] }) {
35
+ FixtureCloud.lock.withLock { FixtureCloud.pinned.append((request.url, request.connectTo)) }
36
+ sink.head(status: 200, headers: [PalHeader(name: "content-type", value: "image/png")])
37
+ _ = sink.chunk(bytes: image)
38
+ return
39
+ }
40
+ let host = URL(string: request.url)?.host ?? ""
41
+ guard request.url.hasPrefix(FixtureCloud.origin + "/") || FixtureCloud.gatewayHosts.contains(host) else {
42
+ FixtureCloud.lock.withLock { FixtureCloud.refused.append(request.url) }
43
+ throw CorePalError.Failure(code: "host_unavailable", detail: "Outside the fixture: \(request.url)")
44
+ }
45
+ let serve = self.serve
46
+ try effect {
47
+ _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
48
+ try await RuntimeHTTPAdapter.adapt(serve, request, sink, signal); return true
49
+ }
50
+ }
51
+ }
52
+ /// A fixed public answer: no DNS query leaves the process.
53
+ func resolve(host: String, cancel: CancelToken) throws -> [String] { ["93.184.216.34"] }
54
+
55
+ func blobOperation(operation: String, key: String, cursor: String?, bytes: Data?) throws -> PalBlobReply {
56
+ try base.blobOperation(operation: operation, key: key, cursor: cursor, bytes: bytes)
57
+ }
58
+ func streamPlatform() -> HostStreamPlatform { base.streamPlatform() }
59
+ func imageSupport() -> String? { base.imageSupport() }
60
+ func imageOperation(operation: String, bytes: Data, optionsJson: String, cancel: CancelToken) throws -> PalImageReply { try base.imageOperation(operation: operation, bytes: bytes, optionsJson: optionsJson, cancel: cancel) }
61
+ func readImage(request: PalImageReadRequest, cancel: CancelToken) throws -> Data { try base.readImage(request: request, cancel: cancel) }
62
+ func releaseImage(capture: String) { base.releaseImage(capture: capture) }
63
+ func platformFacts() -> PalPlatformFacts { base.platformFacts() }
64
+ func readAsset(path: String) throws -> Data? { try base.readAsset(path: path) }
65
+ func list(prefix: String) throws -> [String] { try base.list(prefix: prefix) }
66
+ func read(key: String) throws -> String? { try base.read(key: key) }
67
+ func write(key: String, value: String) throws { try base.write(key: key, value: value) }
68
+ func readSecret(key: String) throws -> String? { try base.readSecret(key: key) }
69
+ func writeSecret(key: String, value: String) throws { try base.writeSecret(key: key, value: value) }
70
+ func remove(key: String) throws { try base.remove(key: key) }
71
+ func purgeInstance(prefix: String) throws { try base.purgeInstance(prefix: prefix) }
72
+ func removeSecret(key: String) throws { try base.removeSecret(key: key) }
73
+ func lock(key: String) throws -> PalLockOutcome { try base.lock(key: key) }
74
+ func unlock(key: String) throws { try base.unlock(key: key) }
75
+ func storeIdentity() -> String { base.storeIdentity() }
76
+ func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput { try base.tool(invocation: invocation, cancel: cancel) }
77
+ func attest(request: String, timeoutMs: UInt64) throws -> String { try base.attest(request: request, timeoutMs: timeoutMs) }
78
+ func nowMs() -> Double { base.nowMs() }
79
+ func utcOffsetMinutes(atMs: Double) -> Int64 { base.utcOffsetMinutes(atMs: atMs) }
80
+ func random() -> String { base.random() }
81
+ func wake(atMs: Double?) { base.wake(atMs: atMs) }
82
+ func schedule(entries: String) throws { try base.schedule(entries: entries) }
83
+ func registerBackground(identifier: String, wake: CoreBackgroundWake) throws { try base.registerBackground(identifier: identifier, wake: wake) }
84
+ }
85
+
86
+ extension Croche {
87
+ /// `open` through the private test entry, when a test has set `FixtureCloud.serve`.
88
+ static func fixtureOpen(_ open: String, _ registrations: [CoreToolRegistration], _ selected: SelectedAdapters,
89
+ _ recoveryJson: String?, _ serve: @escaping RuntimeHTTP) async throws -> Croche {
90
+ let base = try platformHost(image: selected.image), host = FixtureHost(base: base, serve: serve)
91
+ let store = PlatformStorageAdapter(base, state: selected.state)
92
+ return Croche(core: try await owner({ try CoreCroche.openForTests(openJson: open, registrations: registrations,
93
+ storage: store, host: host, bindingFactsJson: BindingFacts.json(),
94
+ intervalsJson: fixtureSettings, recoveryJson: recoveryJson) },
95
+ discard: { try? $0.shutdown() }))
96
+ }
97
+
98
+ private static let fixtureSettings = #"{"cloudOrigin":"\#(FixtureCloud.origin)"}"#
99
+ }
100
+ #endif
@@ -0,0 +1,278 @@
1
+ import Foundation
2
+
3
+ /// What the model asked for. Bound arguments are already merged in by Core.
4
+ public struct ToolCall: Sendable {
5
+ /// The manifest command key the model called.
6
+ public let key: String
7
+ /// The call's arguments, bound values included.
8
+ public let args: [String: JSON]
9
+ }
10
+
11
+ /// The source owner and id for an explicit app-held attachment copy.
12
+ public struct AttachmentSource: Sendable {
13
+ /// The agent that holds the attachment.
14
+ public let agent: String
15
+ /// The attachment id.
16
+ public let id: String
17
+ /// The instance that holds it, or `nil` for the default instance.
18
+ public let instance: String?
19
+ /// Creates an attachment source.
20
+ public init(agent: String, id: String, instance: String? = nil) { self.agent = agent; self.id = id; self.instance = instance }
21
+ var json: JSON { var value: [String: JSON] = ["agent": .string(agent), "id": .string(id)]; if let instance { value["instance"] = .string(instance) }; return .object(value) }
22
+ }
23
+ /// An original attachment read through Core's scoped capability. `data` is base64.
24
+ public struct AttachmentData: Sendable, Decodable, Equatable {
25
+ /// The original's media type, such as `image/png`.
26
+ public let mediaType: String
27
+ /// The original bytes, base64-encoded.
28
+ public let data: String
29
+ }
30
+ /// Who the call works for. Cancellation is the Task's: it fires on cancel, agent close and teardown.
31
+ public struct ToolContext: Sendable {
32
+ /// The call id, matching the agent's tool event.
33
+ public let callId: String
34
+ let attachments: any CoreAttachmentReader
35
+ /// Let an app tool read the file the user shared for that action.
36
+ ///
37
+ /// Reads from the calling instance only; a missing attachment fails with `unknown_id`.
38
+ public func attachment(_ id: String) async throws -> AttachmentData {
39
+ try decode(AttachmentData.self, await blocking { try attachments.attachment(id: id) })
40
+ }
41
+ /// The agent that made the call.
42
+ public let agentId: String
43
+ /// nil = the default instance.
44
+ public let instance: String?
45
+ /// The Croche's user, or `nil` when it was opened without one.
46
+ public let user: String?
47
+ /// The input ids this call works for (avoid buying twice).
48
+ public let causedBy: [String]
49
+ }
50
+
51
+ /// One part of a tool's ``ToolResult/content(_:)`` result.
52
+ ///
53
+ /// For images, `attach: true` keeps the original on the final message; omit it for model-only input. Any other
54
+ /// explicit value is refused with `invalid_tool_result`.
55
+ public enum ToolContent: Sendable, Equatable {
56
+ /// Text for the model.
57
+ case text(String)
58
+ /// Base64 bytes.
59
+ case image(mediaType: String, data: String, alt: String? = nil, attach: Bool? = nil)
60
+ /// A `file://` URL, read by the native host.
61
+ case imageFile(mediaType: String, uri: String, alt: String? = nil, attach: Bool? = nil)
62
+ }
63
+
64
+ /// A tool's tagged result. Returning nil is the empty result.
65
+ public enum ToolResult: Sendable, Equatable {
66
+ /// Text and images for the model.
67
+ case content([ToolContent])
68
+ /// A JSON value for the model.
69
+ case json(JSON)
70
+ }
71
+
72
+ /// Its message reaches the model verbatim. Core chooses every code.
73
+ public struct ToolError: Error, Sendable {
74
+ /// The text the model sees.
75
+ public let message: String
76
+ /// Creates a tool error with the text the model sees.
77
+ public init(_ message: String) { self.message = message }
78
+ }
79
+
80
+ /// Let the app apply its own permissions and use its own data for an action the agent requests.
81
+ public typealias ToolExecute = @Sendable (ToolCall, ToolContext) async throws -> ToolResult?
82
+
83
+ /// A manifest (JSON, the same on every SDK) plus its execute. Core validates the manifest
84
+ /// here: an invalid one throws `invalid_tool` with Core's path.
85
+ public final class ToolDefinition: Sendable {
86
+ private let make: @Sendable () throws -> CoreToolDefinition
87
+ /// The registered tool name, from the manifest.
88
+ public let name: String
89
+ init(make: @escaping @Sendable () throws -> CoreToolDefinition) throws {
90
+ self.make = make
91
+ // A validation export lasts only for this call; reusable public tools hold immutable inputs.
92
+ name = try make().name()
93
+ }
94
+ convenience init(manifest: JSON, execute: @escaping ToolExecute) throws {
95
+ let encoded = text(manifest)
96
+ do { try self.init(make: { try CoreToolDefinition(manifestJson: encoded, execute: ToolExecuteAdapter(execute)) }) }
97
+ catch { throw CrocheError(error) }
98
+ }
99
+ func core() throws -> CoreToolDefinition { try make() }
100
+ }
101
+
102
+ /// Let the agent use app-owned features such as looking up an order.
103
+ public func defineTool(_ manifest: JSON, _ execute: @escaping ToolExecute) throws -> ToolDefinition {
104
+ try ToolDefinition(manifest: manifest, execute: execute)
105
+ }
106
+
107
+ // Leo 17:23Z.
108
+ /// Let the agent use app-owned features such as looking up an order.
109
+ ///
110
+ /// The same, for a handler that returns a plain Swift value: String, a number,
111
+ /// Bool, nil, a Dictionary or Array of those, or any `Encodable`. It is serialized to JSON
112
+ /// mechanically (no policy); a `ToolResult` passes through and nil is "nothing to report", as
113
+ /// for `ToolExecute`. A value that has no JSON form (a non-finite number, a non-string key, a
114
+ /// class instance) reaches Core as `invalid_result`; Core chooses the code.
115
+ public func defineTool(_ manifest: JSON, _ execute: @escaping @Sendable (ToolCall, ToolContext) async throws -> (any Sendable)?) throws -> ToolDefinition {
116
+ try ToolDefinition(manifest: manifest, execute: PlainToolValue.execute(execute))
117
+ }
118
+
119
+ /// Mechanical Swift value -> JSON for tool returns. Serialization only.
120
+ enum PlainToolValue {
121
+ /// The value had no JSON form: the adapter reports `invalid_result`.
122
+ struct Unconvertible: Error, CustomStringConvertible {
123
+ let reason: String
124
+ var description: String { "The tool's return value has no JSON form: \(reason)" }
125
+ }
126
+
127
+ /// The plain handler as a `ToolExecute`: a `ToolResult` passes through, nil is nothing to report.
128
+ static func execute(_ plain: @escaping @Sendable (ToolCall, ToolContext) async throws -> (any Sendable)?) -> ToolExecute {
129
+ { call, context in
130
+ guard let value = try await plain(call, context) else { return nil }
131
+ if let result = value as? ToolResult { return result }
132
+ let json = try json(value)
133
+ return json == .null ? nil : .json(json)
134
+ }
135
+ }
136
+
137
+ static func json(_ value: Any) throws -> JSON {
138
+ let mirror = Mirror(reflecting: value)
139
+ if mirror.displayStyle == .optional { return try mirror.children.first.map { try json($0.value) } ?? .null }
140
+ if value is NSNull { return .null }
141
+ switch value {
142
+ case let value as JSON: return value
143
+ case let value as String: return .string(value)
144
+ case let value as Bool: return .bool(value)
145
+ case let value as Int: return try number(Double(exactly: value), "\(value)")
146
+ case let value as Int8: return .number(Double(value))
147
+ case let value as Int16: return .number(Double(value))
148
+ case let value as Int32: return .number(Double(value))
149
+ case let value as Int64: return try number(Double(exactly: value), "\(value)")
150
+ case let value as UInt: return try number(Double(exactly: value), "\(value)")
151
+ case let value as UInt8: return .number(Double(value))
152
+ case let value as UInt16: return .number(Double(value))
153
+ case let value as UInt32: return .number(Double(value))
154
+ case let value as UInt64: return try number(Double(exactly: value), "\(value)")
155
+ // A non-finite number has no JSON text: the adapter's encoding fallback sends invalid_result.
156
+ case let value as Double: return .number(value)
157
+ case let value as Float: return .number(Double(value))
158
+ case let value as [String: Any]: return .object(try value.mapValues { try json($0) })
159
+ case let value as [Any]: return .array(try value.map { try json($0) })
160
+ case let value as any Encodable:
161
+ do { return try JSON(data: JSONEncoder().encode(value)) }
162
+ catch { throw Unconvertible(reason: "\(type(of: value)) did not encode: \(error)") }
163
+ default: throw Unconvertible(reason: "\(type(of: value)) is not String, a number, Bool, nil, a Dictionary or Array of those, or Encodable")
164
+ }
165
+ }
166
+
167
+ private static func number(_ value: Double?, _ text: String) throws -> JSON {
168
+ guard let value else { throw Unconvertible(reason: "\(text) is not a number JSON can carry exactly") }
169
+ return .number(value)
170
+ }
171
+ }
172
+
173
+ /// `Croche.open` registration: a tool, or a tool with a bind for every agent. No commands or guide here.
174
+ public enum ToolRegistration: Sendable {
175
+ /// The tool as defined, with no bind.
176
+ case tool(ToolDefinition)
177
+ /// The tool with argument values bound for every agent.
178
+ ///
179
+ /// `[:]` is an explicit empty bind and reaches Core as `{}`, distinct from `.tool`.
180
+ case bound(ToolDefinition, bind: [String: JSON])
181
+
182
+ /// The entry as the app wrote it, with only the opaque tool replaced by null (Atlas's S1
183
+ /// ABI): a bare tool = null; a wrapper keeps every key. Core validates, never this layer.
184
+ var json: JSON {
185
+ switch self {
186
+ case .tool: .null
187
+ case .bound(_, let bind): .object(["tool": .null, "bind": .object(bind)])
188
+ }
189
+ }
190
+
191
+ func core() throws -> CoreToolRegistration {
192
+ switch self {
193
+ case .tool(let tool): CoreToolRegistration(tool: try tool.core(), optionsJson: nil)
194
+ case .bound(let tool, _): CoreToolRegistration(tool: try tool.core(), optionsJson: text(json))
195
+ }
196
+ }
197
+ }
198
+
199
+ /// Core-owned tools. Registered name `webSearch`.
200
+ public enum CrocheTools {
201
+ /// Croche's paid web search tool.
202
+ public static var webSearch: ToolDefinition { try! ToolDefinition(make: { coreWebSearch() }) }
203
+ /// Croche's built-in image tool.
204
+ public static var image: ToolDefinition { try! ToolDefinition(make: { coreImage() }) }
205
+ }
206
+
207
+ /// Core's execute callback, on a Core worker thread. Reports one tagged fact; Core applies policy
208
+ /// (tool_failed, cancelled, timeouts): empty | json | result | tool_error | handler_error | cancelled |
209
+ /// unavailable | invalid_result, discriminated by `type` (Atlas's pin, 10-30).
210
+ final class ToolExecuteAdapter: CoreToolExecute, @unchecked Sendable {
211
+ private let execute: ToolExecute
212
+ init(_ execute: @escaping ToolExecute) { self.execute = execute }
213
+
214
+ func execute(callJson: String, contextJson: String, cancel: CancelToken, attachments: any CoreAttachmentReader) throws -> String {
215
+ let call = try JSON(callJson), context = try JSON(contextJson)
216
+ let toolCall = ToolCall(key: call["key"].string ?? "", args: call["args"].object ?? [:])
217
+ let toolContext = ToolContext(callId: context["callId"].string ?? "", attachments: attachments, agentId: context["agentId"].string ?? "", instance: context["instance"].string,
218
+ user: context["user"].string, causedBy: context["causedBy"].array?.compactMap(\.string) ?? [])
219
+ let execute = self.execute
220
+ let box = ResultBox<ToolResult?>()
221
+ let done = DispatchSemaphore(value: 0)
222
+ let task = appTask {
223
+ do { box.set(.success(try await execute(toolCall, toolContext))) } catch { box.set(.failure(error)) }
224
+ done.signal()
225
+ }
226
+ cancel.onCancel(callback: TaskCancel(task))
227
+ done.wait()
228
+ // A result JSON cannot carry (a non-finite number) is a transport fact; Core picks the code.
229
+ return (strictText(Self.completion(box, cancelled: cancel.isCancelled()))) ?? #"{"type":"invalid_result"}"#
230
+ }
231
+
232
+ static func completion(_ box: ResultBox<ToolResult?>, cancelled: Bool) -> JSON {
233
+ do {
234
+ switch try box.get() {
235
+ case nil: return .object(["type": .string("empty")])
236
+ case .json(let value)?: return .object(["type": .string("json"), "value": value])
237
+ case .content(let content)?: return .object(["type": .string("result"), "content": .array(content.map(\.json))])
238
+ }
239
+ } catch is PlainToolValue.Unconvertible {
240
+ return .object(["type": .string("invalid_result")])
241
+ } catch let error as ToolError {
242
+ return .object(["type": .string("tool_error"), "message": .string(error.message)])
243
+ } catch {
244
+ if error is CancellationError || cancelled { return .object(["type": .string("cancelled")]) }
245
+ // The throw passes unchanged; Core applies tool_failed and maps no code here.
246
+ return .object(["type": .string("handler_error"),
247
+ "error": .object(["type": .string(String(reflecting: type(of: error))), "message": .string("\(error)")])])
248
+ }
249
+ }
250
+ }
251
+
252
+ private final class TaskCancel: CancelCallback, @unchecked Sendable {
253
+ private let task: Task<Void, Never>
254
+ init(_ task: Task<Void, Never>) { self.task = task }
255
+ func cancelled() { task.cancel() }
256
+ }
257
+
258
+ extension ToolContent {
259
+ var json: JSON {
260
+ switch self {
261
+ case .text(let text): .object(["type": .string("text"), "text": .string(text)])
262
+ case .image(let mediaType, let data, let alt, let attach):
263
+ Self.imageJSON(mediaType, "data", data, alt, attach)
264
+ case .imageFile(let mediaType, let uri, let alt, let attach):
265
+ Self.imageJSON(mediaType, "uri", uri, alt, attach)
266
+ }
267
+ }
268
+ }
269
+
270
+ extension ToolContent {
271
+ private static func imageJSON(_ mediaType: String, _ key: String, _ source: String,
272
+ _ alt: String?, _ attach: Bool?) -> JSON {
273
+ var image: [String: JSON] = ["type": .string("image"), "mediaType": .string(mediaType), key: .string(source)]
274
+ image["alt"] = alt.map(JSON.string)
275
+ image["attach"] = attach.map(JSON.bool)
276
+ return .object(image)
277
+ }
278
+ }
@@ -0,0 +1,27 @@
1
+ import Foundation
2
+
3
+ // Founder 2026-11-22 02:31:47Z.
4
+ /// How Croche Cloud verified this installation (``Croche/verification()``).
5
+ /// Verification is not access: a withheld key leaves it unchanged. The strings match TS/RN and Kotlin,
6
+ /// and the set is open (`String`, like `RunToolResult.costStatus`).
7
+ public struct Verification: Sendable, Equatable, Decodable {
8
+ /// `attested`, `server`, `development`, `unverified`, or `unknown` (not registered yet, or Cloud did not say).
9
+ public let status: String
10
+ /// The device-side code of the last attestor attempt without a usable proof, or nil.
11
+ /// Nil does not mean Cloud accepted a proof; read `status` for that.
12
+ public let lastAttestation: String?
13
+
14
+ /// Creates a verification value.
15
+ public init(status: String, lastAttestation: String?) {
16
+ self.status = status; self.lastAttestation = lastAttestation
17
+ }
18
+ }
19
+
20
+ extension Croche {
21
+ /// Let the app show how Croche Cloud verified this installation, or explain a withheld key.
22
+ /// Read-only, from stored registration state; it never calls Cloud.
23
+ public func verification() async throws -> Verification {
24
+ let core = try self.core
25
+ return try decode(Verification.self, await blocking { try core.verification() })
26
+ }
27
+ }
@@ -0,0 +1,189 @@
1
+ import Foundation
2
+
3
+ /// One write in a ``StateStore/commit(_:_:)`` batch. A batch never repeats a key.
4
+ public enum StateOp: Sendable, Equatable {
5
+ /// Store `value` under `key`, replacing any earlier value.
6
+ case put(key: String, value: String)
7
+ /// Remove `key`. Deleting an absent key succeeds.
8
+ case delete(key: String)
9
+
10
+ var key: String {
11
+ switch self {
12
+ case .put(let key, _), .delete(let key): return key
13
+ }
14
+ }
15
+ }
16
+
17
+ /// The guard of a commit: the batch applies only if `key` is at `version` now.
18
+ public struct StateCondition: Sendable, Equatable {
19
+ /// The guard key.
20
+ public var key: String
21
+ /// The version the key must have; `nil` means the key must be absent.
22
+ public var version: String?
23
+ /// Creates a commit condition.
24
+ public init(key: String, version: String?) { self.key = key; self.version = version }
25
+ }
26
+
27
+ /// The outcome of a ``StateStore/commit(_:_:)``.
28
+ public enum StateCommitResult: Sendable, Equatable {
29
+ /// The whole batch was applied. `version` is the guard key's resulting version.
30
+ case committed(version: String?)
31
+ /// The guard did not match and nothing was written. Do not retry or merge the batch: Core decides what follows.
32
+ case conflict
33
+ }
34
+
35
+ /// How ``StateStore/list(_:_:)`` pages through a prefix.
36
+ public struct StateListOptions: Sendable, Equatable {
37
+ /// Inclusive lower bound within the prefix. It stays a lower bound when `reverse` is set.
38
+ public var start: String?
39
+ /// List in descending UTF-8 key order instead of ascending.
40
+ public var reverse: Bool
41
+ /// Most entries in one page, up to 128.
42
+ public var limit: UInt32?
43
+ /// The previous page's ``StatePage/nextCursor``, used with the same prefix, start and direction.
44
+ public var cursor: String?
45
+ /// Creates list options.
46
+ public init(start: String? = nil, reverse: Bool = false, limit: UInt32? = nil, cursor: String? = nil) {
47
+ self.start = start
48
+ self.reverse = reverse
49
+ self.limit = limit
50
+ self.cursor = cursor
51
+ }
52
+ }
53
+
54
+ /// One key and value in a ``StatePage``.
55
+ public struct StateEntry: Sendable, Equatable {
56
+ /// The full key.
57
+ public var key: String
58
+ /// The stored text.
59
+ public var value: String
60
+ /// Creates an entry.
61
+ public init(key: String, value: String) { self.key = key; self.value = value }
62
+ }
63
+
64
+ /// One page of ``StateStore/list(_:_:)``.
65
+ public struct StatePage: Sendable, Equatable {
66
+ /// The entries, in the requested order, no more than the limit.
67
+ public var entries: [StateEntry]
68
+ /// Opaque cursor to continue strictly past this page; `nil` when the range is exhausted. A page with a cursor
69
+ /// holds at least one entry; a short page can still have one.
70
+ public var nextCursor: String?
71
+ /// Creates a page.
72
+ public init(entries: [StateEntry], nextCursor: String? = nil) {
73
+ self.entries = entries
74
+ self.nextCursor = nextCursor
75
+ }
76
+ }
77
+
78
+ func validateStateBatch(_ ops: [StateOp], _ condition: StateCondition) throws {
79
+ try validateStateKey(condition.key)
80
+ _ = try storageVersion(condition.version)
81
+ guard !ops.isEmpty else { throw stateBatchError() }
82
+ var keys: Set<String> = []
83
+ for op in ops {
84
+ try validateStateKey(op.key)
85
+ guard keys.insert(op.key).inserted else { throw stateBatchError() }
86
+ }
87
+ }
88
+
89
+ func validateStateKey(_ key: String) throws {
90
+ guard PlatformStorage.valid(key) else { throw stateBatchError() }
91
+ }
92
+
93
+ private func stateBatchError() -> LegacyCrocheError { LegacyCrocheError("invalid_configuration", "Invalid StateStore batch or list range.") }
94
+
95
+ /// State keys are ASCII, so the database's BINARY collation matches UTF-8 order.
96
+ struct StateRange {
97
+ private struct Cursor: Codable {
98
+ let prefix: String
99
+ let start: String?
100
+ let reverse: Bool
101
+ let after: String
102
+ }
103
+
104
+ private let prefix: String
105
+ private let options: StateListOptions
106
+ let lower: String
107
+ let upper: String
108
+ let after: String
109
+ let limit: Int
110
+ var reverse: Bool { options.reverse }
111
+
112
+ // The two key bounds of this page (HLD storage, "Range reads"). A cursor replaces a bound.
113
+ // Written as a third predicate it makes SQLite seek to the range start and filter every
114
+ // earlier page again.
115
+ private var resumed: Bool { options.cursor != nil }
116
+ /// Lower bound: exclusive when an ascending walk resumes after its cursor, else inclusive.
117
+ var from: String { !reverse && resumed ? after : lower }
118
+ var fromExclusive: Bool { !reverse && resumed }
119
+ /// Upper bound, always exclusive: the cursor when a descending walk resumes.
120
+ var to: String { reverse && resumed ? after : upper }
121
+ /// The page statement for a `(key, value)` table; binds `from`, `to`, then the row limit.
122
+ func statement(table: String) -> String {
123
+ "SELECT key, value FROM \(table) WHERE key \(fromExclusive ? ">" : ">=") ? AND key < ? "
124
+ + "ORDER BY key \(reverse ? "DESC" : "ASC") LIMIT ?"
125
+ }
126
+
127
+ init(prefix: String, options: StateListOptions) throws {
128
+ if !prefix.isEmpty { try validateStateKey(prefix) }
129
+ if let start = options.start { try validateStateKey(start) }
130
+ guard options.limit != 0 else { throw stateBatchError() }
131
+ self.prefix = prefix
132
+ self.options = options
133
+ lower = max(prefix, options.start ?? prefix)
134
+ if let last = prefix.utf8.last {
135
+ upper = String(decoding: Array(prefix.utf8.dropLast()) + [last + 1], as: UTF8.self)
136
+ } else {
137
+ upper = "\u{7f}"
138
+ }
139
+ limit = Int(min(options.limit ?? 128, 128))
140
+ if let token = options.cursor {
141
+ let cursor = try JSONDecoder().decode(Cursor.self, from: Data(token.utf8))
142
+ try validateStateKey(cursor.after)
143
+ guard cursor.prefix == prefix, cursor.start == options.start, cursor.reverse == options.reverse,
144
+ cursor.after >= lower, cursor.after < upper else { throw stateBatchError() }
145
+ after = cursor.after
146
+ } else {
147
+ after = options.reverse ? upper : ""
148
+ }
149
+ }
150
+
151
+ func page(_ rows: [StateEntry]) throws -> StatePage {
152
+ let entries = Array(rows.prefix(limit))
153
+ guard rows.count > limit, let last = entries.last else { return StatePage(entries: entries) }
154
+ let cursor = Cursor(prefix: prefix, start: options.start, reverse: reverse, after: last.key)
155
+ return StatePage(entries: entries, nextCursor: String(decoding: try JSONEncoder().encode(cursor), as: UTF8.self))
156
+ }
157
+ }
158
+
159
+ extension CoreStateOp {
160
+ func app() -> StateOp {
161
+ switch self {
162
+ case .put(let key, let value): return .put(key: key, value: value)
163
+ case .delete(let key): return .delete(key: key)
164
+ }
165
+ }
166
+ }
167
+
168
+ extension CoreStateCondition {
169
+ func app() -> StateCondition { StateCondition(key: key, version: version) }
170
+ }
171
+
172
+ extension CoreStateListOptions {
173
+ func app() -> StateListOptions { StateListOptions(start: start, reverse: reverse, limit: limit, cursor: cursor) }
174
+ }
175
+
176
+ extension StateCommitResult {
177
+ func core() throws -> CoreStateCommit {
178
+ switch self {
179
+ case .committed(let version): return .committed(version: try storageVersion(version))
180
+ case .conflict: return .conflict
181
+ }
182
+ }
183
+ }
184
+
185
+ extension StatePage {
186
+ func core() -> CoreStatePage {
187
+ CoreStatePage(entries: entries.map { CoreStateEntry(key: $0.key, value: $0.value) }, nextCursor: nextCursor)
188
+ }
189
+ }
@@ -0,0 +1,68 @@
1
+ import Foundation
2
+
3
+ struct VersionedValue: Sendable, Equatable {
4
+ let value: String?, version: String?
5
+ init(value: String?, version: String?) { self.value = value; self.version = version }
6
+ }
7
+ enum WriteOutcome: Sendable, Equatable { case written(version: String?), conflict(version: String?) }
8
+
9
+ func logicalStorageKey(_ key: String) throws -> String {
10
+ guard key.split(separator: "/", omittingEmptySubsequences: true).last != ".p1" else {
11
+ throw CoreStorageFailure.Failure(detail: "Reserved storage sibling")
12
+ }
13
+ return key
14
+ }
15
+ func versionedStorageKey(_ key: String) throws -> String {
16
+ _ = try logicalStorageKey(key)
17
+ guard PlatformStorage.valid(key), key.utf8.count <= 196, !key.split(separator: "/").contains("secret-index") else {
18
+ throw CoreStorageFailure.Failure(detail: "Invalid versioned storage key")
19
+ }
20
+ return key
21
+ }
22
+ func storageVersion(_ token: String?) throws -> String? {
23
+ if let token {
24
+ guard (1...128).contains(token.utf8.count), token.utf8.allSatisfy({ (0x21...0x7e).contains($0) }) else {
25
+ throw CoreStorageFailure.Failure(detail: "Invalid storage version")
26
+ }
27
+ }
28
+ return token
29
+ }
30
+ extension VersionedValue {
31
+ func core() throws -> CoreVersionedValue {
32
+ let token = try storageVersion(version)
33
+ guard (value == nil) == (token == nil) else { throw CoreStorageFailure.Failure(detail: "Unpaired storage value and version") }
34
+ return CoreVersionedValue(value: value, version: token)
35
+ }
36
+ }
37
+ extension WriteOutcome {
38
+ func core(for requestedValue: String?) throws -> CoreWriteOutcome {
39
+ switch self {
40
+ case let .conflict(version): return .conflict(version: try storageVersion(version))
41
+ case let .written(version):
42
+ let token = try storageVersion(version)
43
+ guard (requestedValue == nil) == (token == nil) else { throw CoreStorageFailure.Failure(detail: "Written version does not match request") }
44
+ guard token != "legacy" else { throw CoreStorageFailure.Failure(detail: "Written must return a new storage version") }
45
+ return .written(version: token)
46
+ }
47
+ }
48
+ }
49
+
50
+ func storageNullableString(_ value: Any?) throws -> String? {
51
+ guard let value else { throw CoreStorageFailure.Failure(detail: "Missing storage field") }
52
+ if value is NSNull { return nil }
53
+ guard let text = value as? String else { throw CoreStorageFailure.Failure(detail: "Invalid storage field") }
54
+ return text
55
+ }
56
+ func decodeStorageValue(_ value: Any) throws -> CoreVersionedValue {
57
+ guard let row = value as? [String: Any] else { throw CoreStorageFailure.Failure(detail: "Invalid versioned reply") }
58
+ return try VersionedValue(value: storageNullableString(row["value"]), version: storageNullableString(row["version"])).core()
59
+ }
60
+ func decodeStorageOutcome(_ value: Any, for request: String?) throws -> CoreWriteOutcome {
61
+ guard let row = value as? [String: Any] else { throw CoreStorageFailure.Failure(detail: "Invalid conditional reply") }
62
+ let version = try storageNullableString(row["version"])
63
+ switch row["type"] as? String {
64
+ case "written": return try WriteOutcome.written(version: version).core(for: request)
65
+ case "conflict": return try WriteOutcome.conflict(version: version).core(for: request)
66
+ default: throw CoreStorageFailure.Failure(detail: "Invalid conditional outcome")
67
+ }
68
+ }