@h1r-ai/croche-react-native 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -1,133 +1,4 @@
1
1
  import Foundation
2
- #if canImport(CryptoKit)
3
- import CryptoKit
4
- #endif
5
-
6
- enum DebugVisibility: String, Sendable { case runtime }
7
- enum Attestation: String, Sendable { case platform, off }
8
- // Q9 recommendation: backgroundDelivery is deferred until the per-agent identifier rule.
9
- struct LegacyOpenOptions: Sendable {
10
- var cloudUrl: String?
11
- var projectKey: String
12
- /// The app's bundled project configuration (a ProjectConfig or its release export); Core selects
13
- /// it or a newer released config. `temperature`: number 0...2, absent uses a tuned default, `.null` = omit.
14
- /// Structured calls always omit it. Remote temperature configs require schema 6 / 0.6+.
15
- var bundledConfig: JSON
16
- var user: String?
17
- var handlers: [String: ToolHandler]
18
- var language: String?
19
- var timeZone: String?
20
- var streaming: Bool?
21
- var backgroundSync: Bool?
22
- var maintenanceIntervalMs: Double?
23
- var debugKey: String?
24
- var requestTimeoutMs: Double?
25
- var maxPendingEvents: Int?
26
- var syncIntervalMs: Double?
27
- var maintenanceBackoffMs: Double?
28
- var retentionBytes: Int?
29
- var onUsage: (@Sendable (ProjectUsageEvent) -> Void)?
30
- var onDebugEvent: (@Sendable (RuntimeDebugEvent) -> Void)?
31
- var debugVisibility: DebugVisibility?
32
- var attestation: Attestation?
33
- var projectDirectory: URL?
34
- var http: RuntimeHTTP?
35
- init(cloudUrl: String? = nil,
36
- projectKey: String,
37
- bundledConfig: JSON,
38
- user: String? = nil,
39
- handlers: [String: ToolHandler] = [:],
40
- language: String? = nil,
41
- timeZone: String? = nil,
42
- streaming: Bool? = nil,
43
- backgroundSync: Bool? = nil,
44
- maintenanceIntervalMs: Double? = nil,
45
- debugKey: String? = nil,
46
- requestTimeoutMs: Double? = nil,
47
- maxPendingEvents: Int? = nil,
48
- syncIntervalMs: Double? = nil,
49
- maintenanceBackoffMs: Double? = nil,
50
- retentionBytes: Int? = nil,
51
- onUsage: (@Sendable (ProjectUsageEvent) -> Void)? = nil,
52
- onDebugEvent: (@Sendable (RuntimeDebugEvent) -> Void)? = nil,
53
- debugVisibility: DebugVisibility? = nil,
54
- attestation: Attestation? = nil,
55
- projectDirectory: URL? = nil,
56
- http: RuntimeHTTP? = nil) {
57
- self.cloudUrl = cloudUrl
58
- self.projectKey = projectKey
59
- self.bundledConfig = bundledConfig
60
- self.user = user
61
- self.handlers = handlers
62
- self.language = language
63
- self.timeZone = timeZone
64
- self.streaming = streaming
65
- self.backgroundSync = backgroundSync
66
- self.maintenanceIntervalMs = maintenanceIntervalMs
67
- self.debugKey = debugKey
68
- self.requestTimeoutMs = requestTimeoutMs
69
- self.maxPendingEvents = maxPendingEvents
70
- self.syncIntervalMs = syncIntervalMs
71
- self.maintenanceBackoffMs = maintenanceBackoffMs
72
- self.retentionBytes = retentionBytes
73
- self.onUsage = onUsage
74
- self.onDebugEvent = onDebugEvent
75
- self.debugVisibility = debugVisibility
76
- self.attestation = attestation
77
- self.projectDirectory = projectDirectory
78
- self.http = http
79
- }
80
- func hostJSON() -> JSON {
81
- var host: JSON = .object(["projectKey": .string(projectKey)])
82
- if let cloudUrl { host["cloudUrl"] = .string(cloudUrl) }
83
- if let debugKey { host["debugKey"] = .string(debugKey) }
84
- if let debugVisibility { host["debugVisibility"] = .string(debugVisibility.rawValue) }
85
- if let requestTimeoutMs { host["requestTimeoutMs"] = .number(requestTimeoutMs) }
86
- if let maxPendingEvents { host["maxPendingEvents"] = .number(Double(maxPendingEvents)) }
87
- if let syncIntervalMs { host["syncIntervalMs"] = .number(syncIntervalMs) }
88
- if let maintenanceBackoffMs { host["maintenanceBackoffMs"] = .number(maintenanceBackoffMs) }
89
- if let retentionBytes { host["retentionBytes"] = .number(Double(retentionBytes)) }
90
- return host
91
- }
92
- func resolvedLanguage(preferredLanguages: [String] = Locale.preferredLanguages) -> String? {
93
- language ?? preferredLanguages.first
94
- }
95
- func native() throws -> NativeProjectOptions {
96
- do { _ = try hostJSON().encoded(); _ = try bundledConfig.encoded() }
97
- catch { throw LegacyCrocheError("invalid_configuration", "Configuration must be JSON serializable.") }
98
- let records = try ProjectRecordFiles.forOpen(projectDirectory: projectDirectory)
99
- let directory = try NativeProjectFiles.directory(projectDirectory: projectDirectory)
100
- var identity = hostJSON(); identity["user"] = user.map(JSON.string) ?? .null
101
- let namespace = try storageIdentity(config: identity)["storageKey"].string ?? "croche.runtime"
102
- let zone: TimeZone?
103
- if let timeZone {
104
- guard let parsed = TimeZone(identifier: timeZone) else { throw LegacyCrocheError("invalid_configuration", "timeZone must name an IANA time zone") }
105
- zone = parsed
106
- } else { zone = nil }
107
- let attestor: (any RuntimeAttestor)?
108
- #if canImport(DeviceCheck) && os(iOS) && !targetEnvironment(simulator)
109
- attestor = attestation == .off ? nil : AppAttestAttestor()
110
- #else
111
- attestor = nil
112
- #endif
113
- let test = NativeProjectFiles.testing
114
- return NativeProjectOptions(host: hostJSON(), bundledConfig: bundledConfig, user: user,
115
- language: resolvedLanguage(), handlers: handlers, streaming: streaming ?? true,
116
- backgroundSync: backgroundSync ?? true, maintenanceIntervalMs: maintenanceIntervalMs ?? 60_000,
117
- storage: { slot in FileRuntimeStorage(url: NativeProjectFiles.file(directory: directory, namespace: namespace, slot: slot)) },
118
- secretStorage: { slot in
119
- let key = NativeProjectFiles.key(namespace: namespace, slot: slot)
120
- if let test { return FileRuntimeSecretStore(url: test.appendingPathComponent(key + ".secrets")) }
121
- #if canImport(Security) && !os(Linux)
122
- return KeychainSecretStore(account: key)
123
- #else
124
- return FileRuntimeSecretStore(url: directory.appendingPathComponent(key + ".secrets"))
125
- #endif
126
- }, attestor: attestor, fetch: http, timeZone: zone,
127
- records: { test.map { dir in ProjectRecordFiles(directory: { dir }) } ?? records },
128
- onUsage: onUsage, onDebugEvent: onDebugEvent)
129
- }
130
- }
131
2
 
132
3
  // Test-only redirection keeps host gates inside their own worktree, out of Keychain/private app storage.
133
4
  enum NativeProjectFiles {
@@ -146,30 +17,4 @@ enum NativeProjectFiles {
146
17
  return url
147
18
  #endif
148
19
  }
149
- static func file(directory: URL, namespace: String, slot: String) -> URL {
150
- directory.appendingPathComponent(key(namespace: namespace, slot: slot) + ".json")
151
- }
152
- static func key(namespace: String, slot: String) -> String {
153
- namespace + ".agent." + slotHash(slot)
154
- }
155
- static func slotHash(_ slot: String) -> String {
156
- #if canImport(CryptoKit)
157
- SHA256.hash(data: Data(slot.utf8)).map { String(format: "%02x", $0) }.joined()
158
- #else
159
- PortableSHA256.hex(Array(slot.utf8))
160
- #endif
161
- }
162
- }
163
-
164
- // Core's maintenance label selects the instance's physical store, never its live handle.
165
- enum NativeProjectSlot {
166
- static func isMaintenance(_ label: String) -> Bool {
167
- (try? JSON(label).array?.first?.string) == "$gc"
168
- }
169
- static func storageLabel(_ label: String) -> String {
170
- guard let parts = try? JSON(label).array, parts.count == 3,
171
- parts[0].string == "$gc", parts[1].string != nil, parts[2].string != nil else { return label }
172
- let encoder = JSONEncoder(); encoder.outputFormatting = [.withoutEscapingSlashes]
173
- return String(decoding: try! encoder.encode(JSON.array(Array(parts.dropFirst()))), as: UTF8.self)
174
- }
175
20
  }
@@ -7,7 +7,7 @@ import Darwin
7
7
 
8
8
  // Platform Abstraction Layer. The Rust Core decides; these perform what only the platform
9
9
  // can: keep a credential in hardware-backed storage, and vouch for the app binary.
10
- // See docs/MOBILE-SDK-AND-PAL.md.
10
+ // See docs/hld/surface-and-hosts.md.
11
11
 
12
12
  /// Where the Runtime credential lives, apart from the general state file. load returns an
13
13
  /// object (empty when nothing is stored). save replaces the whole object atomically.
@@ -81,32 +81,6 @@ final class SchedulerClaims: @unchecked Sendable {
81
81
  func held(_ identity: String) -> Bool { lock.withLock { holders[identity] != nil } }
82
82
  }
83
83
 
84
- /// One background run the OS granted (a BGTaskScheduler launch): opens or reaches the app's
85
- /// Runtime, delivers what is due, and reports whether that finished. `expire()` (the OS ending
86
- /// background time) cancels this run's own delivery, waiting behind another turn or running,
87
- /// never another turn of the Runtime (Atlas, #323 P1-1); after the run ended it does nothing.
88
- /// The delivery's notes stay pending, registered again, for the next run or foreground.
89
- final class BackgroundDelivery: @unchecked Sendable {
90
- private let open: @Sendable () async throws -> AgentEngine
91
- private let lock = NSLock()
92
- private var task: Task<Void, Never>?
93
- private var expired = false
94
- init(open: @escaping @Sendable () async throws -> AgentEngine) { self.open = open }
95
- func start(_ done: @escaping @Sendable (Bool) -> Void) {
96
- let open = self.open
97
- let task = Task {
98
- let runtime: AgentEngine
99
- do { runtime = try await open() } catch { done(false); return }
100
- // Cancelling this Task cancels this delivery only (`deliverDue`). Expired before it
101
- // began, it is cancelled at once, and its notes are registered again.
102
- let result = try? await runtime.deliverDue()
103
- done(!Task.isCancelled && (result.map { $0["ran"].bool != true || $0["delivered"].bool == true } ?? false))
104
- }
105
- if lock.withLock({ self.task = task; return expired }) { task.cancel() }
106
- }
107
- func expire() { lock.withLock { expired = true; return task }?.cancel() }
108
- }
109
-
110
84
  /// A 0600 file beside the state file. For hosts without a secret store (Linux, tests,
111
85
  /// command-line tools). On iOS and macOS apps, use KeychainSecretStore.
112
86
  final class FileRuntimeSecretStore: RuntimeSecretStore, @unchecked Sendable {
@@ -125,11 +125,15 @@ final class BackgroundLaunch: @unchecked Sendable {
125
125
 
126
126
  func start(_ done: @escaping @Sendable (Bool) -> Void) {
127
127
  let deliver = self.deliver
128
- let task = Task {
129
- let finished = await deliver()
130
- done(finished && !Task.isCancelled)
128
+ let started = lock.withLock { () -> Bool in
129
+ guard !expired else { return false }
130
+ task = Task {
131
+ let finished = await deliver()
132
+ done(finished && !Task.isCancelled)
133
+ }
134
+ return true
131
135
  }
132
- if lock.withLock({ self.task = task; return expired }) { task.cancel() }
136
+ if !started { done(false) }
133
137
  }
134
138
  func expire() { lock.withLock { expired = true; return task }?.cancel() }
135
139
  }
@@ -11,11 +11,13 @@ import Glibc
11
11
  /// refused or inert here: tools reach Core through `CoreToolDefinition`, and the cutover deletes them.
12
12
  final class PlatformPal: HostPal, @unchecked Sendable {
13
13
  private let storage: PlatformStorage
14
+ private let blobs: BlobFiles
14
15
  let secrets: any PlatformSecrets
15
16
  private let directory: URL
16
17
  private let bundle: Bundle
17
18
  let session = RuntimeSession()
18
19
  let images = NativeImagePal()
20
+ let imageAdapter: (any ImageAdapter)?
19
21
  /// Where this host runs (a fact Core reads); a React Native host sets `.reactNative`.
20
22
  var streamPlatformFact = HostStreamPlatform.other
21
23
 
@@ -34,9 +36,12 @@ final class PlatformPal: HostPal, @unchecked Sendable {
34
36
  backgroundRequests: (any BackgroundRequests)? = PlatformPal.osBackgroundRequests(),
35
37
  backgroundLaunches: (any BackgroundLaunches)? = PlatformPal.osBackgroundLaunches(),
36
38
  attestor: (any PlatformAttestor)? = PlatformPal.osAttestor(),
37
- preferredLanguages: @escaping @Sendable () -> [String] = { Locale.preferredLanguages }) {
39
+ preferredLanguages: @escaping @Sendable () -> [String] = { Locale.preferredLanguages },
40
+ imageAdapter: (any ImageAdapter)? = nil) {
41
+ self.imageAdapter = imageAdapter
38
42
  self.preferredLanguages = preferredLanguages
39
43
  let storage = PlatformStorage(directory: directory)
44
+ self.blobs = BlobFiles(directory: directory)
40
45
  self.storage = storage; self.directory = directory; self.bundle = bundle
41
46
  self.schedules = PlatformSchedule(requests: backgroundRequests); self.attestor = attestor
42
47
  self.registration = PlatformRegistration(launches: backgroundLaunches, requests: backgroundRequests)
@@ -83,7 +88,37 @@ final class PlatformPal: HostPal, @unchecked Sendable {
83
88
  do { return try body() } catch { throw LegacyCrocheError(error).ffi }
84
89
  }
85
90
 
91
+ func blobOperation(operation: String, key: String, cursor: String?, bytes: Data?) throws -> PalBlobReply {
92
+ try host {
93
+ switch operation {
94
+ case "get":
95
+ return PalBlobReply(bytes: try blobs.get(key), entries: [], nextCursor: nil)
96
+ case "put":
97
+ guard let bytes else { throw CocoaError(.fileWriteUnknown) }
98
+ try blobs.put(key, bytes)
99
+ case "delete":
100
+ try blobs.delete(key)
101
+ case "list":
102
+ let page = try blobs.list(key, cursor: cursor)
103
+ return PalBlobReply(bytes: nil, entries: page.entries.map { PalBlobEntry(key: $0.key, size: $0.size) }, nextCursor: page.nextCursor)
104
+ case "purgeStaging":
105
+ try blobs.purgeStaging(key)
106
+ default:
107
+ throw CocoaError(.fileWriteUnknown)
108
+ }
109
+ return PalBlobReply(bytes: nil, entries: [], nextCursor: nil)
110
+ }
111
+ }
112
+
86
113
  // MARK: Storage
114
+ func commitState(ops: [StateOp], condition: StateCondition) throws -> StateCommitResult {
115
+ try storage.commitState(ops, condition)
116
+ }
117
+ func listState(prefix: String, options: StateListOptions) throws -> StatePage {
118
+ try storage.listState(prefix, options)
119
+ }
120
+ func readVersioned(key: String) throws -> CoreVersionedValue { try storage.readVersioned(key).core() }
121
+ func writeIf(key: String, value: String?, expect: String?) throws -> CoreWriteOutcome { try storage.writeIf(key, value, expect).core(for: value) }
87
122
  func read(key: String) throws -> String? { try host { try storage.read("state", key) } }
88
123
  func write(key: String, value: String) throws { try host { try storage.write("state", key, value) } }
89
124
  func remove(key: String) throws { try host { try storage.remove("state", key) } }
@@ -94,6 +129,18 @@ final class PlatformPal: HostPal, @unchecked Sendable {
94
129
  func readSecret(key: String) throws -> String? { try host { try secrets.read(key) } }
95
130
  func writeSecret(key: String, value: String) throws { try host { try secrets.write(key, value) } }
96
131
  func removeSecret(key: String) throws { try host { try secrets.remove(key) } }
132
+ func purgeInstance(prefix: String) throws {
133
+ try host { try purgeStorage(prefix: prefix, localState: true, localSecret: true) }
134
+ }
135
+ func purgeStorage(prefix: String, localState: Bool, localSecret: Bool,
136
+ deleteSecret: () throws -> Void = {}, deleteState: () throws -> Void = {}) throws {
137
+ guard PlatformStorage.valid(prefix), prefix.count > 1, prefix.hasSuffix("/") else {
138
+ throw LegacyCrocheError("storage_error", "Invalid purge prefix.")
139
+ }
140
+ let values = localState ? try storage.instancePurgePlan("state", prefix) : nil
141
+ let secret = localSecret ? try secrets.instancePurgePlan(prefix) : nil
142
+ try eraseInstancePayloads(values: values, secrets: secret, deleteSecret: deleteSecret, deleteState: deleteState)
143
+ }
97
144
  func storeIdentity() -> String { directory.standardizedFileURL.path }
98
145
 
99
146
  // MARK: Assets, resolver, facts
@@ -103,9 +150,9 @@ final class PlatformPal: HostPal, @unchecked Sendable {
103
150
  /// (Keel's S2 ruling, pin 4).
104
151
  /// Facts only; Core applies them (Keel 23:55Z/00:27Z). `locale`: the device's first preferred
105
152
  /// language, which Core uses for an omitted `language`. `attestationPlatform`: set only when this
106
- /// host has an attestor. `browserFetch`: never (a native host is not a browser).
153
+ /// host has an attestor.
107
154
  func platformFacts() -> PalPlatformFacts {
108
- PalPlatformFacts(targetKind: AppBuildFacts.targetKind, debuggable: AppBuildFacts.debuggable, locale: preferredLanguages().first, attestationPlatform: attestationPlatform, browserFetch: nil)
155
+ PalPlatformFacts(targetKind: AppBuildFacts.targetKind, debuggable: AppBuildFacts.debuggable, locale: preferredLanguages().first, attestationPlatform: attestationPlatform)
109
156
  }
110
157
 
111
158
  // MARK: HTTP
@@ -120,21 +167,17 @@ final class PlatformPal: HostPal, @unchecked Sendable {
120
167
  }
121
168
 
122
169
  // MARK: Images
123
- func imageCodecAvailable() -> Bool { images.codecAvailable }
170
+ func imageSupport() -> String? { (imageAdapter?.support ?? images.support).map { text($0.json) } }
171
+ func imageOperation(operation: String, bytes: Data, optionsJson: String, cancel: CancelToken) throws -> PalImageReply {
172
+ try effect {
173
+ if let imageAdapter { return try runImageAdapterOperation(imageAdapter, operation, bytes, optionsJson, cancel) }
174
+ return try images.operation(operation, bytes, optionsJson, cancel)
175
+ }
176
+ }
124
177
  func readImage(request: PalImageReadRequest, cancel: CancelToken) throws -> Data {
125
178
  try effect { try images.read(request, cancel) }
126
179
  }
127
- func prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) throws -> PalImageBytes {
128
- try effect { try images.prepare(source, plan, cancel) }
129
- }
130
180
  func releaseImage(capture: String) { images.release(capture) }
131
- func decodeImage(bytes: Data, options: PalImageDecodeOptions, cancel: CancelToken) throws -> PalDecodedImage {
132
- try effect { try images.decode(bytes, options, cancel) }
133
- }
134
- func renderImage(request: PalImageRenderRequest, cancel: CancelToken) throws -> Data {
135
- try effect { try images.render(request, cancel) }
136
- }
137
- func releaseDecodedImage(handle: String) { images.releaseDecoded(handle) }
138
181
  /// A fact about the host, never a batching choice. A React Native host reports .reactNative.
139
182
  func streamPlatform() -> HostStreamPlatform { streamPlatformFact }
140
183
 
@@ -161,13 +204,6 @@ final class PlatformPal: HostPal, @unchecked Sendable {
161
204
  throw FfiError.Failure(code: "tool_not_dispatched", message: "Tools reach Core through their definitions.")
162
205
  }
163
206
  func wake(atMs: Double?) {}
164
- func archiveAppendLine(entry: String, line: String) throws { throw Self.noArchive }
165
- func archiveReadLines(entry: String) throws -> [String] { throw Self.noArchive }
166
- func archiveReplaceLines(entry: String, lines: [String]) throws { throw Self.noArchive }
167
- func archiveRemove(entry: String) throws { throw Self.noArchive }
168
- func archiveEntries(prefix: String) throws -> [ArchiveEntry] { throw Self.noArchive }
169
- func storageCapability() -> StorageCapability { .keyed }
170
- private static let noArchive = FfiError.Failure(code: "archive_unavailable", message: "Core keeps the archive in keyed storage.")
171
207
  }
172
208
 
173
209
  /// App asset references, resolved unchanged (APP-API: iOS = a main-bundle resource or a
@@ -0,0 +1,253 @@
1
+ import Foundation
2
+ #if os(Linux)
3
+ import CSQLite
4
+ import Glibc
5
+ #else
6
+ import Darwin
7
+ import SQLite3
8
+ #endif
9
+
10
+ /// The default platform database. The lock protects the connection; SQLite
11
+ /// serializes writers opened by other handles or processes.
12
+ final class PlatformStateStore: @unchecked Sendable {
13
+ private let path: URL
14
+ private let gate = NSLock()
15
+ private var connection: OpaquePointer?
16
+ var beforeCommit: (() throws -> Void)?
17
+
18
+ init(path: URL) { self.path = path }
19
+
20
+ #if DEBUG
21
+ /// SQLite's own step count for the latest `list`: how much of the table that page visited.
22
+ /// Debug builds only, for the range-read test (HLD storage, "Range reads").
23
+ private(set) var lastListSteps: Int32 = 0
24
+ #endif
25
+
26
+ deinit {
27
+ if let connection { sqlite3_close(connection) }
28
+ }
29
+
30
+ private func database(create: Bool) throws -> OpaquePointer? {
31
+ if let connection { return connection }
32
+ let parent = path.deletingLastPathComponent()
33
+ let manager = FileManager.default
34
+ if create {
35
+ try manager.createDirectory(at: parent, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
36
+ }
37
+ do {
38
+ let root = try manager.attributesOfItem(atPath: parent.path)
39
+ guard root[.type] as? FileAttributeType == .typeDirectory else { throw Self.failure(SQLITE_CANTOPEN) }
40
+ let current = try manager.attributesOfItem(atPath: path.path)
41
+ guard current[.type] as? FileAttributeType == .typeRegular else { throw Self.failure(SQLITE_CANTOPEN) }
42
+ } catch let error as CocoaError where error.code == .fileNoSuchFile || error.code == .fileReadNoSuchFile {
43
+ if !create { return nil }
44
+ }
45
+ // SQLite's NOFOLLOW also rejects ancestors such as Darwin's /var.
46
+ // Resolve only the parent so SQLite still checks the database file itself.
47
+ guard let resolved = parent.path.withCString({ realpath($0, nil) }) else {
48
+ throw Self.failure(SQLITE_CANTOPEN)
49
+ }
50
+ defer { free(resolved) }
51
+ let databasePath = String(cString: resolved) + "/" + path.lastPathComponent
52
+ var handle: OpaquePointer?
53
+ let flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_NOFOLLOW | (create ? SQLITE_OPEN_CREATE : 0)
54
+ let status = sqlite3_open_v2(databasePath, &handle, flags, nil)
55
+ guard status == SQLITE_OK, let db = handle else {
56
+ if let handle { sqlite3_close(handle) }
57
+ throw Self.failure(status)
58
+ }
59
+ do {
60
+ try Self.check(sqlite3_busy_timeout(db, 5_000), SQLITE_OK)
61
+ if create {
62
+ try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: databasePath)
63
+ }
64
+ try execute(db, "PRAGMA journal_mode = WAL")
65
+ try execute(db, "PRAGMA synchronous = NORMAL")
66
+ try execute(db, "CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL, version TEXT NOT NULL)")
67
+ } catch {
68
+ sqlite3_close(db)
69
+ throw error
70
+ }
71
+ connection = db
72
+ return db
73
+ }
74
+
75
+ private static func failure(_ code: Int32) -> LegacyCrocheError {
76
+ LegacyCrocheError("storage_error", "SQLite state operation failed (\(code)).")
77
+ }
78
+
79
+ private static func check(_ status: Int32, _ expected: Int32) throws {
80
+ guard status == expected else { throw failure(status) }
81
+ }
82
+
83
+ private func execute(_ db: OpaquePointer, _ query: String) throws {
84
+ try Self.check(sqlite3_exec(db, query, nil, nil, nil), SQLITE_OK)
85
+ }
86
+
87
+ private func statement<T>(_ db: OpaquePointer, _ query: String, _ bindings: [String],
88
+ _ body: (OpaquePointer) throws -> T) throws -> T {
89
+ var handle: OpaquePointer?
90
+ try Self.check(sqlite3_prepare_v2(db, query, -1, &handle, nil), SQLITE_OK)
91
+ guard let statement = handle else { throw Self.failure(SQLITE_ERROR) }
92
+ defer { sqlite3_finalize(statement) }
93
+ for (index, value) in bindings.enumerated() {
94
+ let size = Int32(exactly: value.utf8.count)
95
+ guard let size else { throw Self.failure(SQLITE_TOOBIG) }
96
+ let status = value.utf8CString.withUnsafeBufferPointer { bytes in
97
+ sqlite3_bind_text(statement, Int32(index + 1), bytes.baseAddress, size,
98
+ unsafeBitCast(-1, to: sqlite3_destructor_type.self))
99
+ }
100
+ try Self.check(status, SQLITE_OK)
101
+ }
102
+ return try body(statement)
103
+ }
104
+
105
+ private func execute(_ db: OpaquePointer, _ query: String, _ bindings: [String]) throws {
106
+ try statement(db, query, bindings) { try Self.check(sqlite3_step($0), SQLITE_DONE) }
107
+ }
108
+
109
+ private func text(_ row: OpaquePointer, _ column: Int32) throws -> String {
110
+ guard let pointer = sqlite3_column_text(row, column) else { throw Self.failure(SQLITE_ERROR) }
111
+ let bytes = UnsafeBufferPointer(start: pointer, count: Int(sqlite3_column_bytes(row, column)))
112
+ guard let value = String(bytes: bytes, encoding: .utf8) else { throw Self.failure(SQLITE_CORRUPT) }
113
+ return value
114
+ }
115
+
116
+ private func entry(_ db: OpaquePointer, _ key: String) throws -> VersionedValue {
117
+ try statement(db, "SELECT value, version FROM state WHERE key = ?", [key]) { row in
118
+ let status = sqlite3_step(row)
119
+ if status == SQLITE_DONE { return VersionedValue(value: nil, version: nil) }
120
+ try Self.check(status, SQLITE_ROW)
121
+ return VersionedValue(value: try text(row, 0), version: try text(row, 1))
122
+ }
123
+ }
124
+
125
+ func get(_ key: String) throws -> VersionedValue {
126
+ try validateStateKey(key)
127
+ return try gate.withLock {
128
+ guard let db = try database(create: false) else { return VersionedValue(value: nil, version: nil) }
129
+ return try entry(db, key)
130
+ }
131
+ }
132
+
133
+ func list(_ prefix: String, _ options: StateListOptions) throws -> StatePage {
134
+ let range = try StateRange(prefix: prefix, options: options)
135
+ return try gate.withLock {
136
+ guard let db = try database(create: false) else { return StatePage(entries: []) }
137
+ let rows = try statement(
138
+ db, range.statement(table: "state"), [range.from, range.to, String(range.limit + 1)]
139
+ ) { row in
140
+ var entries: [StateEntry] = []
141
+ while true {
142
+ let status = sqlite3_step(row)
143
+ #if DEBUG
144
+ if status == SQLITE_DONE { lastListSteps = sqlite3_stmt_status(row, SQLITE_STMTSTATUS_VM_STEP, 0) }
145
+ #endif
146
+ if status == SQLITE_DONE { return entries }
147
+ try Self.check(status, SQLITE_ROW)
148
+ entries.append(StateEntry(key: try text(row, 0), value: try text(row, 1)))
149
+ }
150
+ }
151
+ return try range.page(rows)
152
+ }
153
+ }
154
+
155
+ private func version(_ db: OpaquePointer, _ key: String) throws -> String? {
156
+ try statement(db, "SELECT version FROM state WHERE key = ?", [key]) { row in
157
+ let status = sqlite3_step(row)
158
+ if status == SQLITE_DONE { return nil }
159
+ try Self.check(status, SQLITE_ROW)
160
+ return try text(row, 0)
161
+ }
162
+ }
163
+
164
+ private func apply(_ db: OpaquePointer, _ op: StateOp) throws -> String? {
165
+ switch op {
166
+ case .put(let key, let value):
167
+ let version = UUID().uuidString.lowercased()
168
+ try execute(db, "INSERT OR REPLACE INTO state(key, value, version) VALUES (?, ?, ?)", [key, value, version])
169
+ return version
170
+ case .delete(let key):
171
+ try execute(db, "DELETE FROM state WHERE key = ?", [key])
172
+ return nil
173
+ }
174
+ }
175
+
176
+ private func transaction<T>(_ db: OpaquePointer, _ body: () throws -> T) throws -> T {
177
+ try execute(db, "BEGIN IMMEDIATE")
178
+ do {
179
+ let result = try body()
180
+ try execute(db, "COMMIT")
181
+ return result
182
+ } catch {
183
+ if sqlite3_get_autocommit(db) == 0 {
184
+ do {
185
+ try execute(db, "ROLLBACK")
186
+ } catch {
187
+ // Do not let the next operation use a connection with an open batch.
188
+ sqlite3_close_v2(db)
189
+ connection = nil
190
+ }
191
+ }
192
+ throw error
193
+ }
194
+ }
195
+
196
+ func commit(_ ops: [StateOp], _ condition: StateCondition) throws -> StateCommitResult {
197
+ try validateStateBatch(ops, condition)
198
+ return try gate.withLock {
199
+ guard let db = try database(create: true) else { throw Self.failure(SQLITE_CANTOPEN) }
200
+ return try transaction(db) {
201
+ var version = try version(db, condition.key)
202
+ guard version == condition.version else { return .conflict }
203
+ for op in ops {
204
+ let written = try apply(db, op)
205
+ if op.key == condition.key { version = written }
206
+ }
207
+ try beforeCommit?()
208
+ return .committed(version: version)
209
+ }
210
+ }
211
+ }
212
+
213
+ func write(_ key: String, _ value: String) throws {
214
+ try validateStateKey(key)
215
+ try gate.withLock {
216
+ guard let db = try database(create: true) else { throw Self.failure(SQLITE_CANTOPEN) }
217
+ _ = try apply(db, .put(key: key, value: value))
218
+ }
219
+ }
220
+
221
+ func remove(_ key: String) throws {
222
+ try validateStateKey(key)
223
+ try gate.withLock {
224
+ if let db = try database(create: false) { _ = try apply(db, .delete(key: key)) }
225
+ }
226
+ }
227
+
228
+ func writeIf(_ key: String, _ value: String?, _ expect: String?) throws -> WriteOutcome {
229
+ try validateStateKey(key)
230
+ _ = try storageVersion(expect)
231
+ return try gate.withLock {
232
+ guard let db = try database(create: true) else { throw Self.failure(SQLITE_CANTOPEN) }
233
+ return try transaction(db) {
234
+ let current = try version(db, key)
235
+ guard current == expect else { return .conflict(version: current) }
236
+ let operation: StateOp = value.map { .put(key: key, value: $0) } ?? .delete(key: key)
237
+ let version = try apply(db, operation)
238
+ try beforeCommit?()
239
+ return .written(version: version)
240
+ }
241
+ }
242
+ }
243
+
244
+ func purge(_ prefix: String) throws {
245
+ guard prefix.count > 1, prefix.hasSuffix("/") else { throw CocoaError(.fileWriteInvalidFileName) }
246
+ let range = try StateRange(prefix: prefix, options: StateListOptions())
247
+ try gate.withLock {
248
+ if let db = try database(create: false) {
249
+ try execute(db, "DELETE FROM state WHERE key >= ? AND key < ?", [range.lower, range.upper])
250
+ }
251
+ }
252
+ }
253
+ }